This is the second article about RBAC in CakePHP series (2/2).
In our previous post we did a quick introduction to RBAC and how to setup CakeDC/Auth plugin in an example project, dealing with basic array based rules.
Today we'll talk about how to debug rules, and provide complex Auth rules to check permissions. We'll also discuss how to encapsulate the rules logic into `Rules` classes, and how to deal with RBAC in big projects.
Debugging rules
Notice when debug is enabled, a detailed trace of the matched rule allowing a given action is logged into debug.log
For example: 2017-10-04 23:58:10 Debug: For {"prefix":null,"plugin":null,"extension":null,"controller":"Categories","action":"index","role":"admin"} --> Rule matched {"role":"*","controller":"*","action":["index","view"],"allowed":true} with result = 1
This log could save you some time while debugging why a specific action is granted.
Callbacks for complex authentication rules
Let's imagine a more complex rule, for example, we want to block access to the articles/add action if the user has more than 3 articles already created.
In this case we are going to use a callback to define at runtime the result of the allowed
key in the rule.
[
'role' => '*',
'controller' => 'Articles',
'action' => 'add',
'allowed' => function (array $user, $role, \Cake\Http\ServerRequest $request) {
$userId = $user['id'] ?? null;
if (!$userId) {
return false;
}
$articlesCount = \Cake\ORM\TableRegistry::get('Articles')->findByUserId($userId)->count();
return $articlesCount <= 3;
}
],
Rules example
As previously discussed, we have the ability to create complex logic to check if a given role is allowed to access an action, but we could also extend this concept to define permission rules that affect specific users.
One common use case is allowing the owner of the resource access to a restricted set of actions, for example the author of a given article could have access to edit and delete the entry.
This case was so common that we've included a predefined Rule class you can use after minimal configuration. The final rule would be like this one:
[
'role' => '*',
'controller' => 'Articles',
'action' => ['edit', 'delete'],
'allowed' => new \CakeDC\Auth\Rbac\Rules\Owner(),
],
The Owner rule will use by default the user_id
field in articles
table to match the logged in user id. You can customize the columns, and how the article id is extracted. This covers most of the cases where you need to identify the owner of a given row to assign specific permissions.
Other considerations
Permissions and big projects
Having permission rules in a single file could be a solution for small projects, but when they grow, it's usually hard to manage them. How could we deal with the complexity?
-
Break permission file into additional configuration files
-
Per role, usually a good idea when you have a different set of permissions per role. You can use the
Configure
class to append the permissions, usually having a defaults file with common permissions would be a good idea, then you can read N files, one per role to apply the specific permissions per role. -
Per feature/plugin, useful when you have a lot of actions, and a small set of roles, or when the roles are mostly the same regarding permissions, with a couple changes between them. In this case you will define the rules in N files, each one covering a subset of the actions in your application, for example
invoices.php
file would add the pemissions to the Invoices plugin. In the case you work with plugins, keep in mind you could write the permission rules inside each plugin and share/distribute the rules if you reuse the plugin in other apps (as long as the other apps will have similar roles). -
QA and maintenance
-
It's always a good idea to think about the complexity of testing the application based on the existing roles. Automated integration testing helps a lot, but if you are planning to have some real humans doing click through, each role will multiply the time to pass a full regression test on the release. Key question here is "Do we really need this role?"
-
Having a clear and documented permissions matrix file, with roles vs actions and either "YES" | "NO" | "RuleName" in the cell value will help a lot to understand if the given role should be allowed to access to a given action. If it's a CSV file it could be actually used to create a unit test and check at least the static permission rules.
-
Debugging and tracing is also important, for that reason we've included a trace feature in CakeDC/Auth that logs to debug.log the rule matched to allow/deny a specific auth check.
About performance
Performance "could" become an issue in the case you have a huge amount of rules, and some of them would require database access to check if they are matching. As a general recommendation, remember the following tips:
- Rules are matched top to bottom
- Try to leave the permission rules reading the database to the end of the file
- Cache the commonly used queries, possibly the same query will be used again soon
- Note cache invalidation is always fun, and could lead to very complex scenarios, keep it simple
- If you need too much context and database interaction for a given rule, maybe the check should be done elsewhere. You could give some flexibility and get some performance in return
Last words
We've collected some notes about the implementation of a RBAC based system in CakePHP using our CakeDC/Auth plugin. As stated before, there are many other ways, but this is ours, worked well on several projects and we thought it was a good idea to share it with other members of the CakePHP community to expose a possible solution for their next project Authorization flavor.
Please let us know if you use it, we are always improving on them - And happy to get issues and pull requests for our open source plugins. As part of our open source work in CakeDC, we maintain many open source plugins as well as contribute to the CakePHP Community.
Reference