Simple Role-Based Access Control in JavaScript

Published by Apoorv Tripathi on July 19, 2024
Simple Role-Based Access Control in JavaScript

Introduction

In this tutorial, we have a To-Do List application made using HTML, CSS, and JS, and we will integrate it with Cerbos to add authorization to the app. Authorization determines if a user can perform specific actions or access certain resources or data. It enables organizations to control and secure access to sensitive databases, private and personal data, and corporate resources. In our JS application, authorization will define what actions the users can do (create a to-do and read the to-dos) and what actions the admin can do (create, read, and delete the to-dos).

Introduction to RBAC

Role-based access control (RBAC) is an access control method that assigns permissions to end-users based on their organizational role. RBAC provides fine-grained control, offering a simple, manageable approach to access management that is less error-prone than individually assigning permissions.

The advantage of using RBAC is that managing authorization privileges becomes easier because system managers can manage users and permissions in bulk instead of one by one.
We have defined RBAC policies and will be integrating Cerbos for authorization to create, read, and delete to-dos based on who the user is. Our business requirements for who can do what are as follows:

  • Admins can do all actions (create, read, and delete)
  • Users can create and read to-dos but not delete a to-do.

What is Cerbos and Why Cerbos?

Cerbos is an open-source authorization layer that enables you to easily implement authorization for your applications. At Cerbos, we offer fine-grained access control to enhance security while making your application faster and more scalable. Authorizing with Cerbos carries various advantages that are unavailable using strictly JS code

  • Greater Security: Threats to digital infrastructure are ever-present and access management is always a pressing concern. When you have integrated Cerbos authorization in your JS app, you enable fine-grained access control and securely eliminate unauthorized access with a few lines of code. \

  • Scalability: Cerbos has a centralized policy management system that is easily scalable. As the number of users in your application grows, your authorization solution will scale with your app, and the policies can be modified with a few clicks without having to change a single line of code.

Best Practices for Policy Generation

When an organization adopts the RBAC access model it is imperative they adhere to best practices regarding security and administration and that they are committed to continual improvement of their access protocols to stay ahead of emerging threats.

The following list contains some of the RBAC best practices you must follow:

  1. Identify Needs and Roles: Understand your organization's specific needs and establish a clear hierarchy of roles. Clearly define responsibilities to guide the design of your RBAC system.
  2. Establish and Enforce Policies: Create comprehensive RBAC policies that outline access rules, scope, and objectives, and ensure they are accessible to all stakeholders.
  3. Apply the Principle of Least Privilege: Assign only the minimum permissions required for each role, adhering to the principle of least privilege to prevent unauthorized access.
  4. Regularly Review and Automate: Review role assignments regularly to ensure they reflect organizational changes and use automation for efficient permission assignment and removal.
  5. Prioritize Monitoring and Response: Implement logging and monitoring to detect suspicious behavior and develop incident response procedures to swiftly address unauthorized access.

Modeling Policies

We will use these roles in our example code to demonstrate how access control works.

image9.png

With Cerbos, access rules are always resource-oriented, and the policies you write map to these resources within your system. A resource can be anything, and the way you model your policies is up to you — you can achieve the same logical outcome in numerous ways: action-led, role-led, attribute-led, or with combinations thereof.

That said, some patterns will lend themselves more naturally to specific scenarios — let’s look at some different approaches. Consider this permission model:

Actions Roles
CPO CTO Exec-1 Exec-2 Exec-3
View Allowed Allowed Allowed Allowed Allowed
Add Allowed Allowed Allowed Allowed Allowed
Delete Allowed Allowed Not Allowed Not Allowed Not Allowed

We will describe Action-led policies as we have implemented Action-led policies for our JS application.

Action-led

Here, we focus on an action and list all the roles that can perform that action. An example from our documentation to understand this better is listed as follows:

# Principals in the following three roles can perform the `run` action
  - actions:
      - "run"
    effect: EFFECT_ALLOW
    roles:
      - JR_MANAGER
      - SR_MANAGER
      - CFO

# All principals can perform the `view` action
  - actions:
      - "view"
    effect: EFFECT_ALLOW
    roles:
      - ["*"]

This approach might be suitable if any of the following apply to your system:

  • Your roles are "similar" in what they can do, like JR_MANAGER and SR_MANAGER; it’s likely that JR_MANAGER will have a subset of the permissions of SR_MANAGER. There will of course be duplication in either direction, but it’s often easier to reason about this from an action perspective.
  • You have "high-risk" actions — you want to be able to tell at a glance which roles have access to a particular action. The act of explicitly listing roles per action makes it much more difficult to accidentally give unwanted permissions to the wrong user.
  • You have a relatively high number of roles to a low number of actions.

Prerequisites

  1. WSL (if Windows is your primary OS)
  2. Docker

Integrating Cerbos in a JavaScript Application

  1. To get started, clone this repository and follow along. Make sure you are in the master branch of the repository.

File Structure of Our Application

image13.png

After the build is successful, you should see the web page loading on your browser at localhost:5500.

image5.png

Currently, without any policies, the CPO and CTO in this application are granted permission to delete a to-do, while the Executives(1, 2, and 3) can only view and add to-dos. However, as we have not integrated Cerbos with the application for permission management, the CTO and CPO are not able to delete the to-dos. After Cerbos is successfully integrated, the CTO and CPO will be able to DELETE the to-dos.

image12.png

Integrating Cerbos as a service

To integrate Cerbos into our JavaScript application, we will begin by launching the Cerbos Docker container. In the root directory (/to-dolist-cerbos) use the following to run the Docker container:

docker run --rm --name cerbos -d -v $(pwd)/cerbos/policies:/policies -p 3592:3592 -p 3593:3593 ghcr.io/cerbos/cerbos:0.34.0 

Generate Policy Files with Cerbos RBAC Policy Generator

Cerbos Playground is a utility for creating and testing policies online. The Cerbos playground is a great way to learn about policy creation—and even generate usable policies:: https://play.cerbos.dev/new?generator.

How to use the RBAC Policy Generator to generate a policy for our javascript application?

We have two roles: user and admin (where CTO/CPO are the admins and executives are users). Add the actions and select checkboxes based on the permissions we want to grant.

image11.png

After selecting based on preference, we can click the **Generate **button to generate a YAML policy file named to-dos.yaml.

image8.png

Once you use the generator to generate a policy, just copy it and add it to your application’s file structure. The policy generator also generates a to-dos_test.yaml file, which is intended to help automate the testing of your access control policies. Ensure that the test file always ends with _test suffix. Here's what it typically contains and does:

image2.png

Now that we have integrated Cerbos with the JS application, we will run it to check if the policies are working as expected.

Testing Our Policy File

Let’s test the policy file with the test file and the _testdata _generated by the Cerbos RBAC Policy Generator.

image3.jpg

You can use this Docker command (in the PowerShell terminal) to run the tests:

docker run -i -t -v "$(Get-Location)/cerbos/policies:/policies" ghcr.io/cerbos/cerbos:latest compile /policies

image10.png

On running this command, the tests are successfully executed.

Policies Taking Effect in the Application UI

If the Executives (having the role: user) try to delete a to-do:

image7.png

As the policies are now being applied, executives are not allowed to delete a to-do; they get an alert: You are not authorized to delete this to-do. That privilege is only granted to CPO and CTO roles.

As per the policy, an executive can add a to-do to the list:

image1.png

Adding the task to the textbox and clicking the ADD to-do button added it to the to-do list.

image6.png

The CPO was authorized, and the to-do was successfully deleted.

This hands-on demonstration successfully depicts the integration of Cerbos with our JS application.

Frequently Asked Questions

Q1. What are some best practices we must consider while making RBAC policies?

A1: When an organization adopts the RBAC access model, it is imperative that it adhere to best practices regarding security and administration and is committed to continual improvement of its access protocols to stay ahead of emerging threats.

The following list contains a fair sampling of RBAC best practices:

  1. Identify Needs: Understand organizational roles and responsibilities to guide RBAC design.
  2. Generate a Policy: Develop a clear RBAC policy detailing rules, scope, and objectives and share it with stakeholders.
  3. Establish Role Hierarchy: Define roles and responsibilities aligned with the organization's structure.
  4. Apply Least Privilege: Grant minimum permissions for each role to limit access.

Q2. Can policies be tested using Cerbos before they are live?

A2: Yes, policies can be tested using Cerbos before they are live. Cerbos provides robust policy testing capabilities, allowing you to validate your access control rules before deploying them in a production environment. Using Cerbos' testing framework available in Cerbos Policy Generator, you can ensure that policies enforce the desired access control rules and avoid potential issues in live scenarios. This pre-deployment testing helps maintain the integrity and security of your access control policies, reducing the risk of unauthorized access and ensuring compliance with your organization's security guidelines.

Conclusion

You have successfully integrated Cerbos into a demo to-do list application through the following key steps:

  • We are deploying Cerbos in a Docker container to ensure a consistent and isolated environment.
  • Crafting and refining policy files to define clear access control rules.
  • Rebuilding the application to incorporate these policies.
  • Verified that the application adheres to the established authorization rules, ensuring secure and controlled access.

Book a free Policy Workshop to discuss your requirements and get your first policy written by the Cerbos team