npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

casl-policies

v0.0.9

Published

A package to manage and enforce policies in a NestJS application using CASL

Downloads

2

Readme

Casl Policies

A package to manage and enforce policies in a NestJS application using CASL. This package extends the functionality of the CASL package to provide fine-grained permission checking in a NestJS application. It enhances policy definitions to resemble Amazon policies, making it highly customizable and easy to define resource limitations, their properties, and constraints on condition fields using MongoQuery. Furthermore, it supports a pattern {{field}} that gets replaced by the authenticated user's property values, making the policy guard more robust and flexible.

Installation

To install the package, use the following command:

npm install casl-policies @casl/ability lodash

Setup

Step 1: Define Action and Subject Types

Define your Action and Subject types. If not defined, default ones will be used.

export type Action = 'create' | 'read' | 'update' | 'delete' | 'manage';
export type Subject = 'Policy' | 'Account' | 'UserGroup' | 'all';

Step 2: Importing Necessary Classes from casl-policies package

Import the necessary classes such as Guard, and CaslModule from casl-policies package.

// app.module.ts
import { Module } from '@nestjs/common';
import { CaslModule, PoliciesGuard, DynamicModelFetcher } from 'casl-policies';

// Define your action and subject types
type MyAction = 'create' | 'read' | 'update' | 'delete';
type MySubject = 'User' | 'Post';

@Module({
  imports: [
    CaslModule.forRoot<MyAction, MySubject>(),
  ],
  providers: [
    DynamicModelFetcher,
    {
      provide: 'POLICIES_GUARD',
      useClass: PoliciesGuard<MyAction, MySubject>,
    },
  ],
})
export class AppModule {}

Step 3: Custom Decorator

Define a custom decorator that will call CheckPolicies<A, S>, imported from casl-policies.

// custom-check-policies.decorator.ts
import { CheckPolicies, RequiredPolicy } from 'casl-policies';
import { applyDecorators } from '@nestjs/common';

export const AppCheckPolicies = (...policies: RequiredPolicy<MyAction, MySubject>[]) => {
  return applyDecorators(CheckPolicies<MyAction, MySubject>(...policies));
};

Step 4: Using the Decorator in Controller

// my.controller.ts
import { Controller, Get, Post, Body, Param } from '@nestjs/common';
import { CustomCheckPolicies } from './custom-check-policies.decorator';

@Controller('my-controller')
export class MyController {
  @CustomCheckPolicies<MyAction, MySubject>({ action: 'read', subject: 'User', conditions: {} })
  @Get(':id')
  findOne(@Param('id') id: string) {
    return `This action returns a user with id ${id}`;
  }

  @CustomCheckPolicies<MyAction, MySubject>({ action: 'write', subject: 'User', conditions: {} })
  @Post()
  create(@Body() createDto: any) {
    return 'This action adds a new user';
  }
}

Step5: Put into practices with Example Policy

[
  {
    "version": "2012-10-17",
    "statements": [
      {
        "effect": "Allow",
        "actions": ["read"],
        "resources": ["Account"],
        "fields": [],
        "conditions": {
          "title": {
            "$nin": ["CEO", "CTO"]
          }
        }
      }
    ]
  },
  {
    "version": "2012-10-17",
    "statements": [
      {
        "effect": "Allow",
        "actions": [update", "delete"],
        "resources": ["Account"],
        "fields": [],
        "conditions": {
          "_id": "{{_id}}"
        }
      }
    ]
  },
  {
    "version": "2012-10-17",
    "statements": [
      {
        "effect": "Deny",
        "actions": ["update", "delete"],
        "resources": ["Policy"],
        "fields": ["version"],
        "conditions": {}
      }
    ]
  }
]

Explanation

Building Ability in CaslFactory

The CaslAbilityFactory class is responsible for defining user abilities based on policies. It processes policies, replaces placeholders in conditions with user data, and builds abilities using AbilityBuilder. Allow rules are pushed to the end of the rules array, while deny rules are unshifted to the beginning, ensuring deny rules are applied first.

How PoliciesGuard Works

The PoliciesGuard class checks if the current request can proceed based on defined policies. It retrieves policies defined for the route handler and class using Reflector, then defines abilities based on the user's policies using CaslAbilityFactory. It validates fields in the request body against updatable fields defined in the policies, fetches entities dynamically if an ID is present in the request parameters, and checks if all policies are satisfied using the can method of the ability object.

/**
   * Main method that determines if the current request can proceed based on defined policies.
   * @param context - The execution context, containing the request and response objects.
   * @returns A boolean indicating whether the request is allowed.
   */
  async canActivate(context: ExecutionContext): Promise<boolean> {
    // Retrieve policies defined for the route handler and class
    const policies =
      this.reflector.getAllAndOverride<RequiredPolicy<A, S>[]>(
        CHECK_POLICIES_KEY,
        [context.getHandler(), context.getClass()],
      ) || [];
    if (isEmpty(policies)) {
      return true;
    }

    const request = context.switchToHttp().getRequest();
    const account = request.user;
    // Define the abilities based on the user's policies
    const ability = await this.caslAbilityFactory.defineAbility(
      account.policies,
      account,
    );

    const conditionContext: Record<string, any> = {};

    for (const policy of policies) {
      const subject: string = policy.subject as string;

      // Validate fields in the request body against updatable fields defined in the policies
      if (request.body) {
        this.checkUpdatableFields(policy, ability, request);
      }

      // Fetch entity dynamically if ID is present in the request parameters
      if (request.params[`${subject.toLowerCase()}Id`]) {
        await this.fetchEntityIfNeeded(subject, request, conditionContext);
      }
    }

    // Check if all policies are satisfied
    return this.checkPolicies(policies, ability, conditionContext);
  }

Conclusion

The casl-policies package provides a robust framework for managing and enforcing policies in a NestJS application using CASL. By defining your Action and Subject types, importing necessary classes from the casl-policies package, and setting up the CaslModule and PoliciesGuard, you can easily implement fine-grained access control in your application. Custom decorators such as CheckPolicies allow you to enforce these policies at the controller level, ensuring that only authorized actions are permitted based on the defined rules.

License

This project is licensed under the MIT License - see the LICENSE file for details.