Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ACL for JSON API #85

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions libs/acl-permissions/nestjs-acl-permissions/.eslintrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
{
"extends": ["../../../.eslintrc.base.json"],
"ignorePatterns": ["!**/*"],
"overrides": [
{
"files": ["*.ts", "*.tsx", "*.js", "*.jsx"],
"rules": {}
},
{
"files": ["*.ts", "*.tsx"],
"rules": {}
},
{
"files": ["*.js", "*.jsx"],
"rules": {}
},
{
"files": ["*.json"],
"parser": "jsonc-eslint-parser",
"rules": {
"@nx/dependency-checks": "error"
}
}
]
}
11 changes: 11 additions & 0 deletions libs/acl-permissions/nestjs-acl-permissions/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
# nestjs-acl-permissions

This library was generated with [Nx](https://nx.dev).

## Building

Run `nx build nestjs-acl-permissions` to build the library.

## Running unit tests

Run `nx test nestjs-acl-permissions` to execute the unit tests via [Jest](https://jestjs.io).
11 changes: 11 additions & 0 deletions libs/acl-permissions/nestjs-acl-permissions/jest.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
/* eslint-disable */
export default {
displayName: 'nestjs-acl-permissions',
preset: '../../../jest.preset.js',
testEnvironment: 'node',
transform: {
'^.+\\.[tj]s$': ['ts-jest', { tsconfig: '<rootDir>/tsconfig.spec.json' }],
},
moduleFileExtensions: ['ts', 'js', 'html'],
coverageDirectory: '../../../coverage/libs/nestjs-acl-permissions',
};
10 changes: 10 additions & 0 deletions libs/acl-permissions/nestjs-acl-permissions/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"name": "@klerick/acl-json-api-nestjs",
"version": "0.0.1",
"dependencies": {
"tslib": "^2.3.0"
},
"type": "commonjs",
"main": "./src/index.js",
"typings": "./src/index.d.ts"
}
24 changes: 24 additions & 0 deletions libs/acl-permissions/nestjs-acl-permissions/project.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
{
"name": "nestjs-acl-permissions",
"$schema": "../../../node_modules/nx/schemas/project-schema.json",
"sourceRoot": "libs/nestjs-acl-permissions/src",
"projectType": "library",
"targets": {
"build": {
"executor": "@nx/js:tsc",
"outputs": ["{options.outputPath}"],
"options": {
"outputPath": "dist/libs/nestjs-acl-permissions",
"tsConfig": "libs/nestjs-acl-permissions/tsconfig.lib.json",
"packageJson": "libs/nestjs-acl-permissions/package.json",
"main": "libs/nestjs-acl-permissions/src/index.ts",
"assets": ["libs/nestjs-acl-permissions/*.md"]
}
},
"publish": {
"command": "node tools/scripts/publish.mjs nestjs-acl-permissions {args.ver} {args.tag}",
"dependsOn": ["build"]
}
},
"tags": []
}
1 change: 1 addition & 0 deletions libs/acl-permissions/nestjs-acl-permissions/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './lib/nestjs-acl-permissions.module';
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import {
Actions,
Method,
MethodActionMap as MethodActionMapType,
} from '../types';

export const IS_PUBLIC_META_KEY = Symbol('IS_PUBLIC_META_KEY');
export const GET_PERMISSION_RULES = Symbol('GET_PERMISSION_RULES');

export const MethodActionMap: MethodActionMapType = {
[Method.DELETE]: Actions.delete,
[Method.GET]: Actions.read,
[Method.PATCH]: Actions.update,
[Method.POST]: Actions.create,
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import { getPermissionRules } from './get-permission-rules.factory';
import { Actions, PermissionRule } from '../types';

describe('UserPermissionRulesService', () => {
describe('getPermissionRules method', () => {
it('should return a correct set of rules', () => {
const mockPermissionRule: PermissionRule = {
defaultRules: {
subject1: {
[Actions.create]: true,
[Actions.delete]: true,
[Actions.update]: true,
[Actions.read]: true,
},
},
customRules: {
subject1: [
{
permission: 'can',
condition: {
id: '${currentUser.id}',
},
action: Actions.update,
},
],
subject2: [
{
permission: 'can',
action: Actions.create,
},
],
},
};
const rules = getPermissionRules(mockPermissionRule);
expect(rules).toEqual([
{ action: 'create', subject: 'subject1' },
{ action: 'delete', subject: 'subject1' },
{ action: 'update', subject: 'subject1' },
{ action: 'read', subject: 'subject1' },
{
action: 'update',
subject: 'subject1',
conditions: { id: '${currentUser.id}' },
},
{ action: 'create', subject: 'subject2' },
]);
});
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import { AbilityBuilder, createMongoAbility, RawRuleOf } from '@casl/ability';
import { ValueProvider } from '@nestjs/common';

import { AbilityRules, Actions, PermissionRule } from '../types';
import { GET_PERMISSION_RULES } from '../constants';

export function getPermissionRules(
permission: PermissionRule
): RawRuleOf<AbilityRules>[] {
const abilityBuilder = new AbilityBuilder<AbilityRules>(createMongoAbility);

const defaultRules = Object.entries(permission.defaultRules).reduce<
Required<PermissionRule>['customRules']
>((acum, [subject, rules]) => {
acum[subject] = Object.entries(rules).map(([action, permission]) => ({
permission: permission ? 'can' : 'cannot',
action: action as Actions,
}));
return acum;
}, {});

const resultRules = Object.entries(permission.customRules || {}).reduce(
(acum, [subject, rules]) => {
if (!acum[subject]) {
acum[subject] = [...rules];
} else {
acum[subject].push(...rules);
}
acum[subject] = acum[subject] || [...rules];
return acum;
},
defaultRules
);

for (const [subject, rules] of Object.entries(resultRules)) {
for (const { permission, fields, action, condition } of rules) {
abilityBuilder[permission](action, subject, fields, condition);
}
}

return abilityBuilder.build().rules;
}

export type GetPermissionRules = typeof getPermissionRules;

export const getPermissionRulesFactory: ValueProvider<GetPermissionRules> = {
provide: GET_PERMISSION_RULES,
useValue: getPermissionRules,
};
Empty file.
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { Module } from '@nestjs/common';

@Module({
controllers: [],
providers: [],
exports: [],
})
export class NestjsAclPermissionsModule {}
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
import { Injectable } from '@nestjs/common';

@Injectable()
export class CaslAbilityService {}
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
import { Test } from '@nestjs/testing';
import { ExecutionContext } from '@nestjs/common';
import { Request } from 'express';

import { CheckAccessService } from './check-access.service';
import { JsonApi } from 'json-api-nestjs';
import { RawRuleOf } from '@casl/ability';
import { AbilityRules, Actions } from '../../types';

describe('CheckAccessService', () => {
let checkAccessService: CheckAccessService;
let context: ExecutionContext;

beforeEach(async () => {
const moduleRef = await Test.createTestingModule({
providers: [CheckAccessService],
}).compile();

checkAccessService = moduleRef.get<CheckAccessService>(CheckAccessService);
context = {
getClass: jest.fn(),
getHandler: jest.fn(),
switchToHttp: jest.fn().mockReturnValue({
getRequest: jest.fn(),
method: 'GET',
}),
} as unknown as ExecutionContext;
});

describe('validate input before checkAccess', () => {
it('should return false if the request does not contain a user', async () => {
const httpContext = context.switchToHttp();
@JsonApi(class TestEntity {})
class TestControllerJsonApi {}
jest.spyOn(context, 'getClass').mockReturnValue(TestControllerJsonApi);
jest.spyOn(httpContext, 'getRequest').mockReturnValue({} as Request);
const result = await checkAccessService.checkAccess(context);
expect(result).toEqual(false);
});

it('should return true, entity doesnt assign to controller', async () => {
const httpContext = context.switchToHttp();
jest.spyOn(httpContext, 'getRequest').mockReturnValue({} as Request);

jest.spyOn(context, 'getClass').mockReturnValue(class TestController {});
const result = await checkAccessService.checkAccess(context);
expect(result).toEqual(true);
});

it('should throw error incorrect http methode', async () => {
const permissionRules: RawRuleOf<AbilityRules>[] = [];
const httpContext = context.switchToHttp();
jest
.spyOn(httpContext, 'getRequest')
.mockReturnValue({ permissionRules, user: {} } as Request);
httpContext.getRequest<Request>().method = 'incorrect';
@JsonApi(class TestEntity {})
class TestControllerJsonApi {}
jest.spyOn(context, 'getClass').mockReturnValue(TestControllerJsonApi);
expect.assertions(1);
try {
await checkAccessService.checkAccess(context);
} catch (e) {
expect(e).toBeInstanceOf(Error);
}
});

it('return true because permissionRules empty', async () => {
class TestEntity {}

@JsonApi(TestEntity)
class TestControllerJsonApi {}

const permissionRules: RawRuleOf<AbilityRules>[] = [
{ action: Actions.create, subject: TestEntity.name },
{ action: Actions.delete, subject: TestEntity.name },
{ action: Actions.update, subject: TestEntity.name },
{
action: Actions.update,
subject: 'subject1',
conditions: { id: '${currentUser.id}' },
},
];
const httpContext = context.switchToHttp();
jest.spyOn(httpContext, 'getRequest').mockReturnValue({
permissionRules,
method: 'GET',
user: {},
} as Request);

jest.spyOn(context, 'getClass').mockReturnValue(TestControllerJsonApi);
const result = await checkAccessService.checkAccess(context);
expect(result).toBe(true);
});
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
import { ExecutionContext, Inject, Injectable } from '@nestjs/common';
import { Logger } from '@nestjs/common';
import { Request, Response } from 'express';
import { entityForClass } from 'json-api-nestjs';

import { checkInputHttpMethod } from '../../utils';
import { MethodActionMap } from '../../constants';
import { Actions } from '../../types';

@Injectable()
export class CheckAccessService {
private readonly logger = new Logger(CheckAccessService.name);

public async checkAccess(context: ExecutionContext): Promise<boolean> {
const request = context.switchToHttp().getRequest<Request>();
const { method, user, permissionRules, body, url, params } = request;

const controller = context.getClass();
const entity = entityForClass(controller);
if (!entity) {
this.logger.debug(
'Entity doesnt assign to controller: ' + controller.name
);
return true;
}

if (!user) {
this.logger.debug('User doesnt assign to request');
return false;
}

if (!permissionRules) {
this.logger.debug('Permission rules doesnt assign to request');
return false;
}

if (!('name' in entity)) {
this.logger.debug('Entity doesnt have name');
return false;
}

checkInputHttpMethod(method);

const action = MethodActionMap[method];
const entityName = entity.name;

const rulesForCurrentRequest = permissionRules.filter(
(rule) => rule.action === action && rule.subject === entityName
);
if (rulesForCurrentRequest.length === 0) {
this.logger.debug('No permission rules found for current request');
return true;
}

switch (action) {
case Actions.read:
case Actions.update:
case Actions.create:
case Actions.delete:
}
return true;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export * from './permission/permission.guard';
export * from './check-access/check-access.service';
export * from './casl-ability/casl-ability.service';
Loading
Loading