Skip to content

Commit

Permalink
feat(prisma): adds prisma integration (#505)
Browse files Browse the repository at this point in the history
* feat(prisma): adds interpreter for model properties

Relates to #161

* feat(prisma): implements Prisma interpreter and required `WhereInput` generic type for prisma query

Removes interpreter that translates AST into prisma query as it seems to be redundant if we define rules using Prisma syntax

Relates to #161

* feat(prisma): adds `accessibleBy` function that creates PrismaQuery out of Ability

* feat(prisma): adds `PrismaAbility`

* feat(prisma): adds model type setting middleware

* chore: adds dx to prisma package

* chore(dx): adds jest.chai config

* test(prisma): adds tests for equals, lt/e, gt/e and in operators

Also did small reorganization of code in lib

* test(prisma): adds tests for PrismaQuery interpreter

* fix(prisma): re-exports WhereInput so it can be used internally

* style(prisma): fixes eslint

* chore: fixes aurelia test run

* test(prisma): adds tests for PrismaAbility and accessibleBy

* chore: replaces env var for enabling coverage with option

* test(prisma): adds tests for `addModelType` Prisma middleware

* refactor(prisma): removes `addModelType` middleware and adds `Subjects` helper that generates all possible subjects from type object

`addModelType` middleware was removed due to comments in prisma/prisma#5315

* docs(prisma): updates README to reflect actual package functionality
  • Loading branch information
stalniy committed May 10, 2021
1 parent 44e2dde commit 9f91ac4
Show file tree
Hide file tree
Showing 33 changed files with 1,509 additions and 74 deletions.
3 changes: 2 additions & 1 deletion .eslintrc
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,8 @@
"ObjectPattern": "never"
}],
"func-names": "off",
"class-methods-use-this": "warn"
"class-methods-use-this": "warn",
"no-multi-assign": "off"
},
"overrides": [
{
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/main.yml
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ jobs:
- name: lint & test
run: |
pnpm run -r lint
WITH_COVERAGE=1 pnpm run -r test
pnpm run -r test -- --coverage
- name: submit coverage
env:
CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }}
Expand Down
3 changes: 2 additions & 1 deletion git-hooks/pre-commit
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
#!/usr/bin/env bash

cd packages/dx && bin/dx.js lint-staged

packages/dx/bin/dx.js lint-staged
3 changes: 1 addition & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,9 @@
"scripts": {
"build.docs": "cd docs-src && NODE_ENV=production npm run build",
"coverage.submit": "codecov",
"postinstall": "dx install"
"prepare": "cd packages/dx && bin/dx.js install"
},
"devDependencies": {
"@casl/dx": "workspace:^1.0.0",
"codecov": "^3.0.0"
},
"repository": {
Expand Down
2 changes: 1 addition & 1 deletion packages/casl-ability/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@
"prebuild": "rm -rf dist/*",
"build": "npm run build.types && npm run build.core && npm run build.extra",
"lint": "dx eslint src/ spec/",
"test": "dx jest",
"test": "dx jest --config ../dx/config/jest.chai.config.js",
"prerelease": "npm run lint && npm test && NODE_ENV=production npm run build",
"release": "dx semantic-release"
},
Expand Down
2 changes: 1 addition & 1 deletion packages/casl-ability/src/AbilityBuilder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ class RuleBuilder<T extends AnyAbility> {
type InstanceOf<T extends AnyAbility, S extends SubjectType> = S extends AnyClass<infer R>
? R
: S extends string
? Exclude<Normalize<Generics<T>['abilities']>[1], SubjectType> extends { kind: string }
? Exclude<Normalize<Generics<T>['abilities']>[1], SubjectType> extends TaggedInterface<string>
? Extract<Normalize<Generics<T>['abilities']>[1], TaggedInterface<S>>
: AnyObject
: never;
Expand Down
1 change: 1 addition & 0 deletions packages/casl-ability/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ export type {
EventHandler,
Unsubscribe
} from './RuleIndex';
export * as hkt from './hkt';
export {
setSubjectType as subject,
detectSubjectType,
Expand Down
2 changes: 1 addition & 1 deletion packages/casl-aurelia/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@
"build": "BUILD_TYPES=es5m,es6m,umd dx rollup -n casl.au -g aurelia-framework:au,@casl/ability:casl",
"build.types": "dx tsc",
"lint": "dx eslint src/",
"test": "dx jest --env jsdom",
"test": "dx jest --env jsdom --config ../dx/config/jest.chai.config.js",
"prerelease": "npm run lint && npm test && NODE_ENV=production npm run build",
"release": "dx semantic-release"
},
Expand Down
2 changes: 1 addition & 1 deletion packages/casl-mongoose/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
"build": "BUILD_TYPES=es6m,es6c dx rollup -e @casl/ability/extra,@casl/ability,mongoose",
"build.types": "dx tsc",
"lint": "dx eslint src/ spec/",
"test": "dx jest",
"test": "dx jest --config ../dx/config/jest.chai.config.js",
"prerelease": "npm run lint && npm test && NODE_ENV=production npm run build",
"release": "dx semantic-release"
},
Expand Down
21 changes: 21 additions & 0 deletions packages/casl-prisma/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2017-2021 Sergii Stotskyi

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
145 changes: 145 additions & 0 deletions packages/casl-prisma/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
# CASL Prisma

[![@casl/prisma NPM version](https://badge.fury.io/js/%40casl%2Fprisma.svg)](https://badge.fury.io/js/%40casl%2Fprisma)
[![](https://img.shields.io/npm/dm/%40casl%2Fprisma.svg)](https://www.npmjs.com/package/%40casl%2Fprisma)
[![CASL Join the chat](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/stalniy-casl/casl)

This package allows to define [CASL] permissions on [Prisma] models using Prisma `WhereInput`. And that brings a lot of power in terms of permission management in SQL world:

1. We can use Prisma Query to define permissions, no need to learn MongoDB query language anymore.
2. Additionally, we can ask our SQL database questions like: "Which records can be read?" or "Which records can be updated?".

## Installation

```sh
npm install @casl/prisma @casl/ability
# or
yarn add @casl/prisma @casl/ability
# or
pnpm add @casl/prisma @casl/ability
```

## Usage

This package is a bit different from all others because it provides a custom `PrismaAbility` class that is configured to check permissions using Prisma [WhereInput](https://www.prisma.io/docs/reference/api-reference/prisma-client-reference#where):

```ts
import { User, Post, Prisma } from '@prisma/client';
import { AbilityClass, AbilityBuilder, subject } from '@casl/ability';
import { PrismaAbility, Model } from '@casl/prisma';

type AppAbility = PrismaAbility<[string, Models<{
User: User,
Post: Post
}>]>;
const AppAbility = PrismaAbility as AbilityClass<AppAbility>;
const { can, cannot, build } = new AbilityBuilder(AppAbility);

can('read', 'Post', { authorId: 1 });
cannot('read', 'Post', { title: { startsWith: '[WIP]:' } });

const ability = build();
ability.can('read', 'Post');
ability.can('read', subject('Post', { title: '...', authorId: 1 })));
```

> See [CASL guide](https://casl.js.org/v5/en/guide/intro) to learn how to define abilities. Everything is the same except of conditions language.
### Note on subject helper

Because Prisma returns DTO objects without exposing any type information on it, we need to use `subject` helper to provide that type manually, so CASL can understand what rules to apply to passed in object.

Unfortunately, there is no easy way to automate this, except of adding additional column to all models. For more details, check [this issue](https://github.com/prisma/prisma/issues/5315).

> To get more details about object type detection, please read [CASL Subject type detection](https://casl.js.org/v5/en/guide/subject-type-detection)
### Note on Prisma Query runtime interpreter

`@casl/prisma` uses [ucast](https://github.com/stalniy/ucast) to interpret Prisma [WhereInput](https://www.prisma.io/docs/reference/api-reference/prisma-client-reference#where) in JavaScript runtime. However, there are few caveats:
- equality of JSON columns is not implemented
- equality of array/list columns is not implemented (however operators like `has`, `hasSome` and `hasEvery` should be more than enough)
- when defining conditions on relation, always specify one of operators (`every`, `none`, `some`, `is` or `isNot`)

Interpreter throws a `ParsingQueryError` in cases it receives invalid parameters for query operators or if some operation is not supported.

## Finding Accessible Records

One nice feature of [Prisma] and [CASL] integration is that we can get all records from the database our user has access to. To do this, just use `accessibleBy` helper function:

```ts
// ability is a PrismaAbility instance created in the example above

const accessiblePosts = await prisma.post.findMany({
where: accessibleBy(ability).Post
});
```

That function accepts `PrismaAbility` instance and `action` (defaults to `read`), returns an object with keys that corresponds to Prisma model names and values being aggregated from permission rules `WhereInput` objects.

**Important**: in case user doesn't have ability to access any posts, `accessibleBy` throws `ForbiddenError`, so be ready to catch it!

To combine this with business logic conditions, just use `AND`:

```ts
const accessiblePosts = await prisma.post.findMany({
where: {
AND: [
accessibleBy(ability).Post,
{ /* business related conditions */ }
]
}
})
```

## TypeScript support

The package is written in TypeScript what provides comprehensive IDE hints and compile time validation.

> Makes sure to call `prisma generate`. `@casl/prisma` uses Prisma generated types, so if client is not generated nothing will work.
Additionally, there are several helpers that makes it easy to work with Prisma and CASL:

### PrismaQuery

It's a generic type that provides `Prisma.ModelWhereInput` in generic way. We need to pass inside a named model:

```ts
import { User } from '@prisma/client';
import { Model } from '@casl/prisma';

// almost the same as Prisma.UserWhereInput except that it's a higher order type
type UserWhereInput = PrismaQuery<Model<User, 'User'>>;
```

### Model

Just gives a name to a model. That name is stored using `ForcedSubject<TName>` helper from `@casl/ability`. To use a separate column or another strategy to name models, don't use this helper because it only works in combination with `subject` helper.

### Subjects

Creates a union of all possible subjects out of passed in object:

```ts
import { User } from '@prisma/client';
import { Subjects } from '@casl/prisma';

type AppSubjects = Subjects<{
User: User
}>; // 'User' | Model<User, 'User'>
```

## Want to help?

Want to file a bug, contribute some code, or improve documentation? Excellent! Read up on guidelines for [contributing].

If you'd like to help us sustain our community and project, consider [to become a financial contributor on Open Collective](https://opencollective.com/casljs/contribute)

> See [Support CASL](https://casl.js.org/v5/en/support-casljs) for details
## License

[MIT License](http://www.opensource.org/licenses/MIT)

[contributing]: https://github.com/stalniy/casl/blob/master/CONTRIBUTING.md
[Prisma]: https://prisma.io/
[CASL]: https://github.com/stalniy/casl
61 changes: 61 additions & 0 deletions packages/casl-prisma/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
{
"name": "@casl/prisma",
"version": "0.0.1",
"description": "Allows to query accessible records using Prisma client based on CASL rules",
"main": "dist/es6c/index.js",
"es2015": "dist/es6m/index.mjs",
"typings": "dist/types/index.d.ts",
"exports": {
".": {
"import": "./dist/es6m/index.mjs",
"require": "./dist/es6c/index.js"
}
},
"repository": {
"type": "git",
"url": "https://github.com/stalniy/casl.git"
},
"publishConfig": {
"access": "public"
},
"homepage": "https://casl.js.org",
"scripts": {
"prebuild": "rm -rf dist/* && npm run build.types",
"build": "BUILD_TYPES=es6m,es6c dx rollup -e @casl/ability/extra,@casl/ability,@prisma/client,@ucast/core",
"build.types": "dx tsc",
"lint": "dx eslint src/ spec/",
"test": "dx jest",
"prerelease": "npm run lint && npm test && NODE_ENV=production npm run build",
"release": "dx semantic-release",
"prepare": "prisma generate"
},
"keywords": [
"mongo",
"access control",
"authorization",
"acl",
"security",
"permissions"
],
"author": "Sergii Stotskyi <sergiy.stotskiy@gmail.com>",
"license": "MIT",
"peerDependencies": {
"@casl/ability": "^5.1.0",
"@prisma/client": "^2.14.0"
},
"devDependencies": {
"@casl/ability": "^5.1.0",
"@casl/dx": "workspace:^1.0.0",
"@prisma/client": "^2.22.0",
"prisma": "^2.22.1"
},
"files": [
"dist",
"*.d.ts",
"index.js"
],
"dependencies": {
"@ucast/core": "^1.10.0",
"@ucast/js": "^3.0.1"
}
}
23 changes: 23 additions & 0 deletions packages/casl-prisma/schema.prisma
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}

generator client {
provider = "prisma-client-js"
}

model User {
id Int @id
firstName String
lastName String
age Int
posts Post[]
}

model Post {
id Int @id
title String
author User @relation(fields: [authorId], references: [id])
authorId Int
}
10 changes: 10 additions & 0 deletions packages/casl-prisma/spec/AppAbility.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { AbilityClass } from '@casl/ability'
import { User, Post } from '@prisma/client'
import { PrismaAbility, Subjects } from '../src'

export type AppAbility = PrismaAbility<[string, Subjects<{
User: User,
Post: Post
}>]>
// eslint-disable-next-line @typescript-eslint/no-redeclare
export const AppAbility = PrismaAbility as AbilityClass<AppAbility>
Loading

0 comments on commit 9f91ac4

Please sign in to comment.