models: move ACL LDL def into a json file

This commit is contained in:
Miroslav Bajtoš 2014-10-13 10:55:08 +02:00
parent ef890d5f26
commit 7c01d59d80
5 changed files with 360 additions and 351 deletions

View File

@ -5,9 +5,7 @@
var loopback = require('../../lib/loopback') var loopback = require('../../lib/loopback')
, assert = require('assert') , assert = require('assert')
, uid = require('uid2') , uid = require('uid2')
, DEFAULT_TOKEN_LEN = 64 , DEFAULT_TOKEN_LEN = 64;
, Role = require('./role').Role
, ACL = require('./acl').ACL;
/** /**
* Token based authentication and access control. * Token based authentication and access control.

View File

@ -45,6 +45,8 @@ var role = require('./role');
var Role = role.Role; var Role = role.Role;
/** /**
* A Model for access control meta data.
*
* System grants permissions to principals (users/applications, can be grouped * System grants permissions to principals (users/applications, can be grouped
* into roles). * into roles).
* *
@ -54,18 +56,6 @@ var Role = role.Role;
* For a given principal, such as client application and/or user, is it allowed * For a given principal, such as client application and/or user, is it allowed
* to access (read/write/execute) * to access (read/write/execute)
* the protected resource? * the protected resource?
*/
var ACLSchema = {
model: String, // The name of the model
property: String, // The name of the property, method, scope, or relation
accessType: String,
permission: String,
principalType: String,
principalId: String
};
/**
* A Model for access control meta data.
* *
* @header ACL * @header ACL
* @property {String} model Name of the model. * @property {String} model Name of the model.
@ -78,394 +68,395 @@ var ACLSchema = {
* - DENY: Explicitly denies access to the resource. * - DENY: Explicitly denies access to the resource.
* @property {String} principalType Type of the principal; one of: Application, Use, Role. * @property {String} principalType Type of the principal; one of: Application, Use, Role.
* @property {String} principalId ID of the principal - such as appId, userId or roleId * @property {String} principalId ID of the principal - such as appId, userId or roleId
* @class *
* @inherits Model * @class ACL
* @inherits PersistedModel
*/ */
var ACL = loopback.PersistedModel.extend('ACL', ACLSchema); module.exports = function(ACL) {
ACL.ALL = AccessContext.ALL; ACL.ALL = AccessContext.ALL;
ACL.DEFAULT = AccessContext.DEFAULT; // Not specified ACL.DEFAULT = AccessContext.DEFAULT; // Not specified
ACL.ALLOW = AccessContext.ALLOW; // Allow ACL.ALLOW = AccessContext.ALLOW; // Allow
ACL.ALARM = AccessContext.ALARM; // Warn - send an alarm ACL.ALARM = AccessContext.ALARM; // Warn - send an alarm
ACL.AUDIT = AccessContext.AUDIT; // Audit - record the access ACL.AUDIT = AccessContext.AUDIT; // Audit - record the access
ACL.DENY = AccessContext.DENY; // Deny ACL.DENY = AccessContext.DENY; // Deny
ACL.READ = AccessContext.READ; // Read operation ACL.READ = AccessContext.READ; // Read operation
ACL.WRITE = AccessContext.WRITE; // Write operation ACL.WRITE = AccessContext.WRITE; // Write operation
ACL.EXECUTE = AccessContext.EXECUTE; // Execute operation ACL.EXECUTE = AccessContext.EXECUTE; // Execute operation
ACL.USER = Principal.USER; ACL.USER = Principal.USER;
ACL.APP = ACL.APPLICATION = Principal.APPLICATION; ACL.APP = ACL.APPLICATION = Principal.APPLICATION;
ACL.ROLE = Principal.ROLE; ACL.ROLE = Principal.ROLE;
ACL.SCOPE = Principal.SCOPE; ACL.SCOPE = Principal.SCOPE;
/** /**
* Calculate the matching score for the given rule and request * Calculate the matching score for the given rule and request
* @param {ACL} rule The ACL entry * @param {ACL} rule The ACL entry
* @param {AccessRequest} req The request * @param {AccessRequest} req The request
* @returns {Number} * @returns {Number}
*/ */
ACL.getMatchingScore = function getMatchingScore(rule, req) { ACL.getMatchingScore = function getMatchingScore(rule, req) {
var props = ['model', 'property', 'accessType']; var props = ['model', 'property', 'accessType'];
var score = 0; var score = 0;
for (var i = 0; i < props.length; i++) { for (var i = 0; i < props.length; i++) {
// Shift the score by 4 for each of the properties as the weight // Shift the score by 4 for each of the properties as the weight
score = score * 4; score = score * 4;
var val1 = rule[props[i]] || ACL.ALL; var val1 = rule[props[i]] || ACL.ALL;
var val2 = req[props[i]] || ACL.ALL; var val2 = req[props[i]] || ACL.ALL;
var isMatchingMethodName = props[i] === 'property' && req.methodNames.indexOf(val1) !== -1; var isMatchingMethodName = props[i] === 'property' && req.methodNames.indexOf(val1) !== -1;
if (val1 === val2 || isMatchingMethodName) { if (val1 === val2 || isMatchingMethodName) {
// Exact match // Exact match
score += 3; score += 3;
} else if (val1 === ACL.ALL) { } else if (val1 === ACL.ALL) {
// Wildcard match // Wildcard match
score += 2; score += 2;
} else if (val2 === ACL.ALL) { } else if (val2 === ACL.ALL) {
// Doesn't match at all // Doesn't match at all
score += 1; score += 1;
} else { } else {
return -1; return -1;
}
} }
}
// Weigh against the principal type into 4 levels // Weigh against the principal type into 4 levels
// - user level (explicitly allow/deny a given user) // - user level (explicitly allow/deny a given user)
// - app level (explicitly allow/deny a given app) // - app level (explicitly allow/deny a given app)
// - role level (role based authorization) // - role level (role based authorization)
// - other // - other
// user > app > role > ... // user > app > role > ...
score = score * 4; score = score * 4;
switch(rule.principalType) { switch (rule.principalType) {
case ACL.USER: case ACL.USER:
score += 4;
break;
case ACL.APP:
score += 3;
break;
case ACL.ROLE:
score += 2;
break;
default:
score +=1;
}
// Weigh against the roles
// everyone < authenticated/unauthenticated < related < owner < ...
score = score * 8;
if(rule.principalType === ACL.ROLE) {
switch(rule.principalId) {
case Role.OWNER:
score += 4; score += 4;
break; break;
case Role.RELATED: case ACL.APP:
score += 3; score += 3;
break; break;
case Role.AUTHENTICATED: case ACL.ROLE:
case Role.UNAUTHENTICATED:
score += 2; score += 2;
break; break;
case Role.EVERYONE:
score += 1;
break;
default: default:
score += 5; score += 1;
} }
}
score = score * 4;
score += AccessContext.permissionOrder[rule.permission || ACL.ALLOW] - 1;
return score;
};
/** // Weigh against the roles
* Get matching score for the given `AccessRequest`. // everyone < authenticated/unauthenticated < related < owner < ...
* @param {AccessRequest} req The request score = score * 8;
* @returns {Number} score if (rule.principalType === ACL.ROLE) {
*/ switch (rule.principalId) {
case Role.OWNER:
ACL.prototype.score = function(req) { score += 4;
return this.constructor.getMatchingScore(this, req); break;
} case Role.RELATED:
score += 3;
/*! break;
* Resolve permission from the ACLs case Role.AUTHENTICATED:
* @param {Object[]) acls The list of ACLs case Role.UNAUTHENTICATED:
* @param {Object} req The request score += 2;
* @returns {AccessRequest} result The effective ACL break;
*/ case Role.EVERYONE:
ACL.resolvePermission = function resolvePermission(acls, req) { score += 1;
if(!(req instanceof AccessRequest)) { break;
req = new AccessRequest(req); default:
} score += 5;
// Sort by the matching score in descending order }
acls = acls.sort(function (rule1, rule2) {
return ACL.getMatchingScore(rule2, req) - ACL.getMatchingScore(rule1, req);
});
var permission = ACL.DEFAULT;
var score = 0;
for (var i = 0; i < acls.length; i++) {
score = ACL.getMatchingScore(acls[i], req);
if (score < 0) {
// the highest scored ACL did not match
break;
} }
if (!req.isWildcard()) { score = score * 4;
// We should stop from the first match for non-wildcard score += AccessContext.permissionOrder[rule.permission || ACL.ALLOW] - 1;
permission = acls[i].permission; return score;
break; };
} else {
if(req.exactlyMatches(acls[i])) { /**
permission = acls[i].permission; * Get matching score for the given `AccessRequest`.
* @param {AccessRequest} req The request
* @returns {Number} score
*/
ACL.prototype.score = function(req) {
return this.constructor.getMatchingScore(this, req);
}
/*!
* Resolve permission from the ACLs
* @param {Object[]) acls The list of ACLs
* @param {Object} req The request
* @returns {AccessRequest} result The effective ACL
*/
ACL.resolvePermission = function resolvePermission(acls, req) {
if (!(req instanceof AccessRequest)) {
req = new AccessRequest(req);
}
// Sort by the matching score in descending order
acls = acls.sort(function(rule1, rule2) {
return ACL.getMatchingScore(rule2, req) - ACL.getMatchingScore(rule1, req);
});
var permission = ACL.DEFAULT;
var score = 0;
for (var i = 0; i < acls.length; i++) {
score = ACL.getMatchingScore(acls[i], req);
if (score < 0) {
// the highest scored ACL did not match
break; break;
} }
// For wildcard match, find the strongest permission if (!req.isWildcard()) {
if(AccessContext.permissionOrder[acls[i].permission] // We should stop from the first match for non-wildcard
> AccessContext.permissionOrder[permission]) {
permission = acls[i].permission; permission = acls[i].permission;
break;
} else {
if (req.exactlyMatches(acls[i])) {
permission = acls[i].permission;
break;
}
// For wildcard match, find the strongest permission
if (AccessContext.permissionOrder[acls[i].permission]
> AccessContext.permissionOrder[permission]) {
permission = acls[i].permission;
}
} }
} }
}
if(debug.enabled) { if (debug.enabled) {
debug('The following ACLs were searched: '); debug('The following ACLs were searched: ');
acls.forEach(function(acl) { acls.forEach(function(acl) {
acl.debug(); acl.debug();
debug('with score:', acl.score(req)); debug('with score:', acl.score(req));
}); });
} }
var res = new AccessRequest(req.model, req.property, req.accessType, var res = new AccessRequest(req.model, req.property, req.accessType,
permission || ACL.DEFAULT); permission || ACL.DEFAULT);
return res; return res;
}; };
/*! /*!
* Get the static ACLs from the model definition * Get the static ACLs from the model definition
* @param {String} model The model name * @param {String} model The model name
* @param {String} property The property/method/relation name * @param {String} property The property/method/relation name
* *
* @return {Object[]} An array of ACLs * @return {Object[]} An array of ACLs
*/ */
ACL.getStaticACLs = function getStaticACLs(model, property) { ACL.getStaticACLs = function getStaticACLs(model, property) {
var modelClass = loopback.findModel(model); var modelClass = loopback.findModel(model);
var staticACLs = []; var staticACLs = [];
if (modelClass && modelClass.settings.acls) { if (modelClass && modelClass.settings.acls) {
modelClass.settings.acls.forEach(function (acl) { modelClass.settings.acls.forEach(function(acl) {
if (!acl.property || acl.property === ACL.ALL if (!acl.property || acl.property === ACL.ALL
|| property === acl.property) { || property === acl.property) {
staticACLs.push(new ACL({
model: model,
property: acl.property || ACL.ALL,
principalType: acl.principalType,
principalId: acl.principalId, // TODO: Should it be a name?
accessType: acl.accessType || ACL.ALL,
permission: acl.permission
}));
}
});
}
var prop = modelClass &&
(modelClass.definition.properties[property] // regular property
|| (modelClass._scopeMeta && modelClass._scopeMeta[property]) // relation/scope
|| modelClass[property] // static method
|| modelClass.prototype[property]); // prototype method
if (prop && prop.acls) {
prop.acls.forEach(function(acl) {
staticACLs.push(new ACL({ staticACLs.push(new ACL({
model: model, model: modelClass.modelName,
property: acl.property || ACL.ALL, property: property,
principalType: acl.principalType, principalType: acl.principalType,
principalId: acl.principalId, // TODO: Should it be a name? principalId: acl.principalId,
accessType: acl.accessType || ACL.ALL, accessType: acl.accessType,
permission: acl.permission permission: acl.permission
})); }));
} });
}); }
} return staticACLs;
var prop = modelClass && };
(modelClass.definition.properties[property] // regular property
|| (modelClass._scopeMeta && modelClass._scopeMeta[property]) // relation/scope
|| modelClass[property] // static method
|| modelClass.prototype[property]); // prototype method
if (prop && prop.acls) {
prop.acls.forEach(function (acl) {
staticACLs.push(new ACL({
model: modelClass.modelName,
property: property,
principalType: acl.principalType,
principalId: acl.principalId,
accessType: acl.accessType,
permission: acl.permission
}));
});
}
return staticACLs;
};
/** /**
* Check if the given principal is allowed to access the model/property * Check if the given principal is allowed to access the model/property
* @param {String} principalType The principal type. * @param {String} principalType The principal type.
* @param {String} principalId The principal ID. * @param {String} principalId The principal ID.
* @param {String} model The model name. * @param {String} model The model name.
* @param {String} property The property/method/relation name. * @param {String} property The property/method/relation name.
* @param {String} accessType The access type. * @param {String} accessType The access type.
* @callback {Function} callback Callback function. * @callback {Function} callback Callback function.
* @param {String|Error} err The error object * @param {String|Error} err The error object
* @param {AccessRequest} result The access permission * @param {AccessRequest} result The access permission
*/ */
ACL.checkPermission = function checkPermission(principalType, principalId, ACL.checkPermission = function checkPermission(principalType, principalId,
model, property, accessType, model, property, accessType,
callback) { callback) {
if(principalId !== null && principalId !== undefined && (typeof principalId !== 'string') ) { if (principalId !== null && principalId !== undefined && (typeof principalId !== 'string')) {
principalId = principalId.toString(); principalId = principalId.toString();
} }
property = property || ACL.ALL; property = property || ACL.ALL;
var propertyQuery = (property === ACL.ALL) ? undefined : {inq: [property, ACL.ALL]}; var propertyQuery = (property === ACL.ALL) ? undefined : {inq: [property, ACL.ALL]};
accessType = accessType || ACL.ALL; accessType = accessType || ACL.ALL;
var accessTypeQuery = (accessType === ACL.ALL) ? undefined : {inq: [accessType, ACL.ALL]}; var accessTypeQuery = (accessType === ACL.ALL) ? undefined : {inq: [accessType, ACL.ALL]};
var req = new AccessRequest(model, property, accessType); var req = new AccessRequest(model, property, accessType);
var acls = this.getStaticACLs(model, property); var acls = this.getStaticACLs(model, property);
var resolved = this.resolvePermission(acls, req); var resolved = this.resolvePermission(acls, req);
if(resolved && resolved.permission === ACL.DENY) { if (resolved && resolved.permission === ACL.DENY) {
debug('Permission denied by statically resolved permission'); debug('Permission denied by statically resolved permission');
debug(' Resolved Permission: %j', resolved); debug(' Resolved Permission: %j', resolved);
process.nextTick(function() { process.nextTick(function() {
callback && callback(null, resolved); callback && callback(null, resolved);
}); });
return; return;
}
var self = this;
this.find({where: {principalType: principalType, principalId: principalId,
model: model, property: propertyQuery, accessType: accessTypeQuery}},
function(err, dynACLs) {
if (err) {
callback && callback(err);
return;
}
acls = acls.concat(dynACLs);
resolved = self.resolvePermission(acls, req);
if (resolved && resolved.permission === ACL.DEFAULT) {
var modelClass = loopback.findModel(model);
resolved.permission = (modelClass && modelClass.settings.defaultPermission) || ACL.ALLOW;
}
callback && callback(null, resolved);
});
};
ACL.prototype.debug = function() {
if (debug.enabled) {
debug('---ACL---');
debug('model %s', this.model);
debug('property %s', this.property);
debug('principalType %s', this.principalType);
debug('principalId %s', this.principalId);
debug('accessType %s', this.accessType);
debug('permission %s', this.permission);
}
} }
var self = this; /**
this.find({where: {principalType: principalType, principalId: principalId, * Check if the request has the permission to access.
model: model, property: propertyQuery, accessType: accessTypeQuery}}, * @options {Object} context See below.
function (err, dynACLs) { * @property {Object[]} principals An array of principals.
* @property {String|Model} model The model name or model class.
* @property {*} id The model instance ID.
* @property {String} property The property/method/relation name.
* @property {String} accessType The access type: READE, WRITE, or EXECUTE.
* @param {Function} callback Callback function
*/
ACL.checkAccessForContext = function(context, callback) {
if (!(context instanceof AccessContext)) {
context = new AccessContext(context);
}
var model = context.model;
var property = context.property;
var accessType = context.accessType;
var modelName = context.modelName;
var methodNames = context.methodNames;
var propertyQuery = (property === ACL.ALL) ? undefined : {inq: methodNames.concat([ACL.ALL])};
var accessTypeQuery = (accessType === ACL.ALL) ? undefined : {inq: [accessType, ACL.ALL]};
var req = new AccessRequest(modelName, property, accessType, ACL.DEFAULT, methodNames);
var effectiveACLs = [];
var staticACLs = this.getStaticACLs(model.modelName, property);
var self = this;
var roleModel = loopback.getModelByType(Role);
this.find({where: {model: model.modelName, property: propertyQuery,
accessType: accessTypeQuery}}, function(err, acls) {
if (err) { if (err) {
callback && callback(err); callback && callback(err);
return; return;
} }
acls = acls.concat(dynACLs); var inRoleTasks = [];
resolved = self.resolvePermission(acls, req);
if(resolved && resolved.permission === ACL.DEFAULT) {
var modelClass = loopback.findModel(model);
resolved.permission = (modelClass && modelClass.settings.defaultPermission) || ACL.ALLOW;
}
callback && callback(null, resolved);
});
};
ACL.prototype.debug = function() { acls = acls.concat(staticACLs);
if(debug.enabled) {
debug('---ACL---');
debug('model %s', this.model);
debug('property %s', this.property);
debug('principalType %s', this.principalType);
debug('principalId %s', this.principalId);
debug('accessType %s', this.accessType);
debug('permission %s', this.permission);
}
}
/** acls.forEach(function(acl) {
* Check if the request has the permission to access. // Check exact matches
* @options {Object} context See below. for (var i = 0; i < context.principals.length; i++) {
* @property {Object[]} principals An array of principals. var p = context.principals[i];
* @property {String|Model} model The model name or model class. if (p.type === acl.principalType
* @property {*} id The model instance ID. && String(p.id) === String(acl.principalId)) {
* @property {String} property The property/method/relation name. effectiveACLs.push(acl);
* @property {String} accessType The access type: READE, WRITE, or EXECUTE. return;
* @param {Function} callback Callback function }
*/ }
ACL.checkAccessForContext = function (context, callback) { // Check role matches
if(!(context instanceof AccessContext)) { if (acl.principalType === ACL.ROLE) {
context = new AccessContext(context); inRoleTasks.push(function(done) {
} roleModel.isInRole(acl.principalId, context,
function(err, inRole) {
if (!err && inRole) {
effectiveACLs.push(acl);
}
done(err, acl);
});
});
}
});
var model = context.model; async.parallel(inRoleTasks, function(err, results) {
var property = context.property; if (err) {
var accessType = context.accessType; callback && callback(err, null);
var modelName = context.modelName;
var methodNames = context.methodNames;
var propertyQuery = (property === ACL.ALL) ? undefined : {inq: methodNames.concat([ACL.ALL])};
var accessTypeQuery = (accessType === ACL.ALL) ? undefined : {inq: [accessType, ACL.ALL]};
var req = new AccessRequest(modelName, property, accessType, ACL.DEFAULT, methodNames);
var effectiveACLs = [];
var staticACLs = this.getStaticACLs(model.modelName, property);
var self = this;
var roleModel = loopback.getModelByType(Role);
this.find({where: {model: model.modelName, property: propertyQuery,
accessType: accessTypeQuery}}, function (err, acls) {
if (err) {
callback && callback(err);
return;
}
var inRoleTasks = [];
acls = acls.concat(staticACLs);
acls.forEach(function (acl) {
// Check exact matches
for (var i = 0; i < context.principals.length; i++) {
var p = context.principals[i];
if (p.type === acl.principalType
&& String(p.id) === String(acl.principalId)) {
effectiveACLs.push(acl);
return; return;
} }
} var resolved = self.resolvePermission(effectiveACLs, req);
if (resolved && resolved.permission === ACL.DEFAULT) {
resolved.permission = (model && model.settings.defaultPermission) || ACL.ALLOW;
}
debug('---Resolved---');
resolved.debug();
callback && callback(null, resolved);
});
});
};
// Check role matches /**
if (acl.principalType === ACL.ROLE) { * Check if the given access token can invoke the method
inRoleTasks.push(function (done) { * @param {AccessToken} token The access token
roleModel.isInRole(acl.principalId, context, * @param {String} model The model name
function (err, inRole) { * @param {*} modelId The model id
if (!err && inRole) { * @param {String} method The method name
effectiveACLs.push(acl); * @callback {Function} callback Callback function
} * @param {String|Error} err The error object
done(err, acl); * @param {Boolean} allowed is the request allowed
}); */
}); ACL.checkAccessForToken = function(token, model, modelId, method, callback) {
} assert(token, 'Access token is required');
var context = new AccessContext({
accessToken: token,
model: model,
property: method,
method: method,
modelId: modelId
}); });
async.parallel(inRoleTasks, function (err, results) { this.checkAccessForContext(context, function(err, access) {
if(err) { if (err) {
callback && callback(err, null); callback && callback(err);
return; return;
} }
var resolved = self.resolvePermission(effectiveACLs, req); callback && callback(null, access.permission !== ACL.DENY);
if(resolved && resolved.permission === ACL.DEFAULT) {
resolved.permission = (model && model.settings.defaultPermission) || ACL.ALLOW;
}
debug('---Resolved---');
resolved.debug();
callback && callback(null, resolved);
}); });
}); };
};
/** }
* Check if the given access token can invoke the method
* @param {AccessToken} token The access token
* @param {String} model The model name
* @param {*} modelId The model id
* @param {String} method The method name
* @callback {Function} callback Callback function
* @param {String|Error} err The error object
* @param {Boolean} allowed is the request allowed
*/
ACL.checkAccessForToken = function (token, model, modelId, method, callback) {
assert(token, 'Access token is required');
var context = new AccessContext({
accessToken: token,
model: model,
property: method,
method: method,
modelId: modelId
});
this.checkAccessForContext(context, function (err, access) {
if (err) {
callback && callback(err);
return;
}
callback && callback(null, access.permission !== ACL.DENY);
});
};
module.exports.ACL = ACL;

17
common/models/acl.json Normal file
View File

@ -0,0 +1,17 @@
{
"name": "ACL",
"properties": {
"model": {
"type": "string",
"description": "The name of the model"
},
"property": {
"type": "string",
"description": "The name of the property, method, scope, or relation"
},
"accessType": "string",
"permission": "string",
"principalType": "string",
"principalId": "string"
}
}

View File

@ -281,7 +281,7 @@ AccessRequest.prototype.exactlyMatches = function(acl) {
*/ */
AccessRequest.prototype.isAllowed = function() { AccessRequest.prototype.isAllowed = function() {
return this.permission !== require('../common/models/acl').ACL.DENY; return this.permission !== loopback.ACL.DENY;
} }
AccessRequest.prototype.debug = function() { AccessRequest.prototype.debug = function() {

View File

@ -15,7 +15,10 @@ module.exports = function(loopback) {
loopback.Role = require('../common/models/role').Role; loopback.Role = require('../common/models/role').Role;
loopback.RoleMapping = require('../common/models/role').RoleMapping; loopback.RoleMapping = require('../common/models/role').RoleMapping;
loopback.ACL = require('../common/models/acl').ACL;
loopback.ACL = createModel(
require('../common/models/acl.json'),
require('../common/models/acl.js'));
loopback.Scope = createModel( loopback.Scope = createModel(
require('../common/models/scope.json'), require('../common/models/scope.json'),