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

fix(conditions): use @cast/ability rulesToAST function to compose rule conditions #404

Merged
merged 1 commit into from
Aug 31, 2022
Merged
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
10 changes: 4 additions & 6 deletions src/access.service.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Injectable, NotFoundException, UnauthorizedException } from '@nestjs/common';
import { Ability, PureAbility, subject } from '@casl/ability';
import { Ability, subject } from '@casl/ability';
import { AnyObject, Subject } from '@casl/ability/dist/types/types';

import { AuthorizableRequest } from './interfaces/request.interface';
Expand Down Expand Up @@ -75,12 +75,10 @@ export class AccessService {
return true;
}

// for abilities without subject hook use PureAbility to bypass condition check
let userAbilities = this.abilityFactory.createForUser(user, ability.subjectHook ? Ability : PureAbility);

let userAbilities = this.abilityFactory.createForUser(user, Ability);
const relevantRules = userAbilities.rulesFor(ability.action, ability.subject);
const conditions = relevantRules.filter((rule) => rule.conditions).map((rule) => rule.conditions);
req.setConditions(new ConditionsProxy(conditions));

req.setConditions(new ConditionsProxy(userAbilities, ability.action, ability.subject));

// If no relevant rules with conditions or no subject hook exists check against subject class
if (!relevantRules.every((rule) => rule.conditions) || !ability.subjectHook) {
Expand Down
45 changes: 41 additions & 4 deletions src/proxies/conditions.proxy.spec.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,50 @@
import { defineAbility } from '@casl/ability';
import { ConditionsProxy } from './conditions.proxy';

describe('ConditionsProxy', () => {
it('translates proxied conditions to parametrized sql', () => {
const conditionsProxy = new ConditionsProxy([{ userId: 'userId' }]);
const ability = defineAbility((can) => {
can('update', 'Post', { userId: 'userId' });
});
const conditionsProxy = new ConditionsProxy(ability, 'update', 'Post');
expect(conditionsProxy.toSql()).toEqual(['"userId" = $1', ['userId'], []]);
});

it('should not join relations', () => {
const conditionsProxy = new ConditionsProxy([{ userId: 'userId' }]);
expect(conditionsProxy.joinRelation()).toBeFalsy();
it('negates cannot rule with not', () => {
const ability = defineAbility((can, cannot) => {
can('update', 'Movie');
cannot('update', 'Movie', { status: 'PUBLISHED' });
});
const conditionsProxy = new ConditionsProxy(ability, 'update', 'Movie');
expect(conditionsProxy.toSql()).toEqual(['not ("status" = $1)', ['PUBLISHED'], []]);
});

it('compose can rules', () => {
const ability = defineAbility((can) => {
can('read', 'Upload', { public: true });
can('read', 'Upload', { user: 'userId', public: false });
});
const conditionsProxy = new ConditionsProxy(ability, 'read', 'Upload');
expect(conditionsProxy.toSql()).toEqual([
'("user" = $1 and "public" = $2) or "public" = $3',
['userId', false, true],
[],
]);
});

it('return undefined when no rules found', () => {
const ability = defineAbility((can) => {
can('read', 'Upload', { public: true });
});
const conditionsProxy = new ConditionsProxy(ability, 'write', 'Upload');
expect(conditionsProxy.toSql()).toBeUndefined();
});

it('return undefined for rule without conditions', () => {
const ability = defineAbility((can) => {
can('read', 'Upload');
});
const conditionsProxy = new ConditionsProxy(ability, 'read', 'Upload');
expect(conditionsProxy.toSql()).toBeUndefined();
});
});
22 changes: 10 additions & 12 deletions src/proxies/conditions.proxy.ts
Original file line number Diff line number Diff line change
@@ -1,24 +1,22 @@
import { MongoQuery } from '@casl/ability';
import { MongoQueryParser, allParsingInstructions } from '@ucast/mongo';
import { AnyAbility, Subject } from '@casl/ability';
import { rulesToAST } from '@casl/ability/extra';
import { Condition } from '@ucast/mongo2js';
import { createSqlInterpreter, allInterpreters, pg } from '@ucast/sql';

export type SqlConditions = [string, unknown[], string[]];
export class ConditionsProxy {
constructor(private conditions: MongoQuery[]) {}
constructor(private abilitites: AnyAbility, private action: string, private subject: Subject) {}

public get(): MongoQuery[] {
return Object.assign({}, ...this.conditions);
public toAst(): Condition | null {
return rulesToAST(this.abilitites, this.action, this.subject);
}

public toAst(): Condition {
const parser = new MongoQueryParser(allParsingInstructions);
return parser.parse(this.get());
}

public toSql(): SqlConditions {
public toSql(): SqlConditions | undefined {
const ast = this.toAst();
// eslint-disable-next-line @typescript-eslint/no-explicit-any
if (ast === null || !Array.from(ast.value as any).length) return undefined;
const interpret = createSqlInterpreter(allInterpreters);
return interpret(this.toAst(), {
return interpret(ast, {
...pg,
joinRelation: this.joinRelation,
});
Expand Down