UNPKG

19.2 kBMarkdownView Raw
1<h1 align="center">Welcome to objection-authorize 👋</h1>
2
3[![CircleCI](https://circleci.com/gh/JaneJeon/objection-authorize.svg?style=shield)](https://circleci.com/gh/JaneJeon/objection-authorize)
4[![Coverage](https://codecov.io/gh/JaneJeon/objection-authorize/branch/master/graph/badge.svg)](https://codecov.io/gh/JaneJeon/objection-authorize)
5[![NPM](https://img.shields.io/npm/v/objection-authorize)](https://www.npmjs.com/package/objection-authorize)
6[![Downloads](https://img.shields.io/npm/dt/objection-authorize)](https://www.npmjs.com/package/objection-authorize)
7[![install size](https://packagephobia.now.sh/badge?p=objection-authorize)](https://packagephobia.now.sh/result?p=objection-authorize)
8[![Dependencies](https://img.shields.io/david/JaneJeon/objection-authorize)](https://david-dm.org/JaneJeon/objection-authorize)
9[![Known Vulnerabilities](https://snyk.io//test/github/JaneJeon/objection-authorize/badge.svg?targetFile=package.json)](https://snyk.io//test/github/JaneJeon/objection-authorize?targetFile=package.json)
10[![License](https://img.shields.io/npm/l/objection-authorize)](https://github.com/JaneJeon/objection-authorize/blob/master/LICENSE)
11[![Docs](https://img.shields.io/badge/docs-github-blue)](https://janejeon.github.io/objection-authorize)
12[![Prettier code style](https://img.shields.io/badge/code_style-prettier-ff69b4.svg)](https://github.com/prettier/prettier)
13
14> isomorphic, &#34;magical&#34; access control integrated with objection.js
15
16This plugin automatically takes away a lot of the manual wiring that you'd need to do if you were to implement your access control on a request/route level, including:
17
18- checking the user against the resource and the ACL
19- filtering request body according to the action and the user's access
20- figuring out _which_ resource to check the user's grants against automatically(!)
21- even filtering the result from a query according to a user's read access!
22
23Not sure why you would need this? Read below for examples or [see here](https://janejeon.dev/integrating-access-control-to-your-node-js-apps) to learn just how complex access control can be and how you can manage said complexity with this plugin!
24
25**TL;DR:**
26
27Before:
28
29```js
30class Post extends Model {}
31
32app.put('/posts/:id', (req, res, next) => {
33 // Need to handle random edge cases like the user not being signed in
34 if (!req.user) next(new Error('must be signed in'))
35
36 // Need to first fetch the post to know "can this user edit this post?"
37 Post.query()
38 .findById(req.params.id)
39 .then(post => {
40 if (req.user.id !== post.authorId || req.user.role !== 'editor')
41 return next(new Error("Cannot edit someone else's post!"))
42
43 // Prevent certain fields from being set after creation
44 const postBody = omit(req.body, ['id', 'views', 'authorId'])
45
46 // Prevent certain fields from being *changed*
47 if (
48 post.visibility === 'public' &&
49 get(postBody, 'visibility') !== post.visibility &&
50 req.user.role !== 'admin'
51 )
52 return next(
53 new Error('Cannot take down a post without admin privileges!')
54 )
55
56 req.user
57 .$relatedQuery('posts')
58 .updateAndFetchById(post.id, postBody)
59 .then(post => {
60 // filter the resulting post based on user's access before sending it over
61 if (req.user.role !== 'admin') post = omit(post, ['superSecretField'])
62
63 res.send(post)
64 })
65 .catch(err => next(err))
66 })
67 .catch(err => next(err))
68})
69
70// And you need to repeat ALL of this validation on the frontend as well...
71```
72
73After:
74
75```js
76// Use the plugin...
77class Post extends require('objection-authorize')(acl, library, opts)(Model) {}
78
79app.put('/posts/:id', (req, res, next) => {
80 // ...and the ACL is automagically hooked in for ALL queries!
81 Post.query()
82 .updateAndFetchById(req.params.id, req.body)
83 .authorize(req.user)
84 .fetchResourceContextFromDB()
85 .diffInputFromResource()
86 .then(post => {
87 res.send(post.authorizeRead(req.user))
88 })
89 .catch(err => next(err))
90})
91
92// AND you can re-use the ACL on the frontend as well *without* any changes!
93```
94
95### 🏠 [Homepage](https://github.com/JaneJeon/objection-authorize)
96
97## Installation
98
99To install the plugin itself:
100
101```sh
102yarn add objection-authorize # or
103npm i objection-authorize --save
104```
105
106Note that Objection.js v1 support was dropped on the v4 release of this plugin, so if you need support for the previous version of the ORM, use v3 of this plugin!
107
108And you can install [@casl/ability](https://github.com/stalniy/casl) as your authorization library. Note that only `@casl/ability` of version 4 or above is supported.
109
110For now, only `@casl/ability` is supported as the authorization library, but this plugin is written in an implementation-agnostic way so that any AuthZ/ACL library could be implemented as long as the library of choice supports _synchronous_ authorization checks.
111
112## Changelog
113
114Starting from the 1.0 release, all changes will be documented at the [releases page](https://github.com/JaneJeon/objection-authorize/releases).
115
116## Terminology
117
118A quick note, I use the following terms interchangeably:
119
120- `resource` and `item(s)` (both refer to model instance(s) that the query is fetching/modifying)
121- `body` and `input` and `inputItem(s)` (all of them refer to the `req.body`/`ctx.body` that you pass to the query to modify said model instances; e.g. `Model.query().findById(id).update(inputItems)`)
122
123## Usage
124
125Plugging in `objection-authorize` to work with your existing authorization setup is as easy as follows:
126
127```js
128const acl = ... // see below for defining acl
129
130const { Model } = require('objection')
131const authorize = require('objection-authorize')(acl, library[, opts])
132
133class Post extends authorize(Model) {
134 // That's it! This is just a regular objection.js model class
135}
136```
137
138### Options
139
140You can pass an _optional_ options object as the third parameter during initialization. The default values are as follows:
141
142```js
143const opts = {
144 defaultRole: 'anonymous',
145 unauthenticatedErrorCode: 401,
146 unauthorizedErrorCode: 403
147}
148```
149
150For explanations on what each option does, see below:
151
152<details>
153<summary>defaultRole</summary>
154
155When the user object is empty, a "default" user object will be created with the `defaultRole` (e.g. `{ role: opts.defaultRole }`).
156
157</details>
158
159<details>
160<summary>unauthenticatedErrorCode</summary>
161
162Error code thrown when an unauthenticated user is not allowed to access a resource.
163
164</details>
165
166<details>
167<summary>unauthorizedErrorCode</summary>
168
169Error code thrown when an authenticated user is not allowed to access a resource.
170
171</details>
172
173### Methods
174
175After initialization, the following "magic" methods are available for use:
176
177<details>
178<summary>QueryBuilder.authorize(user[, resource[, opts]])</summary>
179
180This is the bread and butter of this library. You can chain `.authorize()` to any Objection Model query (i.e. `Model.query().authorize()`) to authorize that specific ORM call/HTTP request.
181
182First, an explanation of the parameters:
183
184The `user` should be an object representation of the user; typically, you can just plug in `req.user` (express) or `ctx.user` (koa) directly, _even if the user is not signed in_ (aka `req.user === undefined`)!
185
186The `resource` object is an optional parameter, and for most queries, you won't need to manually specify the resource.
187
188The `opts` can be used to override any of the default options that you passed during initialization of this plugin (i.e. you don't have to pass the whole options object in; only the parts you want to override for this specific query).
189
190So, what are we _actually_ checking here with this function?
191
192When you chain `.authorize()` to the ORM query, the query is (typically) doing one of four things: create, read, update, or delete (CRUD) - which is the action they're trying to take. These correspond to the HTTP verbs: GET/POST/PUT/PATCH/DELETE (if you're not familiar with how this is the case, please read up on REST API design).
193
194In addition, the query already provides the following contexts: the resource/item(s) that the user is acting on (e.g. read a **user**'s email, or create a **post**), the body/inputItem(s) that the user is supplying. This is typically the `req.body` that you pass to the `.insert()/.update()/.delete()` query methods, aka _how_ you want to change the resource.
195
196So, given this information, we can just rely on the ACL (see below for how to define it) to check whether the `user` is allowed to take the specified `action` on `resource/items` with the given `body/inputItems`! Specifically, the authorization check involves the following functionalities:
197
1981. Check if the user is allowed to apply the specified `action` on the `items`, and if not, throw an `httpError` with the appropriate HTTP error code
1992. If there's `inputItems`, check if the user is allowed to modify/add the specific fields in `inputItems`. If a user tries to set/modify a property they're not allowed to, error is thrown again.
200
201That's it!
202
203The nuances of this plugin comes with how it's able to drastically simplify said ACL calls & context fetching. For example, while figuring out the `inputItems` might be simple, how does the plugin know which `items` the `action` applies to?
204
205The plugin looks at the following places to fetch the appropriate `resource(s)`:
206
2071. If the `resource` parameter is specified in the `.authorize()` call, it takes precedence and is set as the only item(s) that we check against.
2082. If the `resource` parameter is not specified, then it looks at the model instance (if you're calling `.$query()` or `.$relatedQuery()`)
2093. If you call `.fetchContextFromDB()`, then the plugin executes a pre-emptive SQL SELECT call to fetch the rows that the query would affect.
210
211And once the plugin figures out `items` and `inputItems`, it simply iterates along both arrays and checks the ACL whether the user can take `action` on `items[i]` with input `inputItems[j]`.
212
213That's it.
214
215**TIP**: the `.authorize()` call can happen _anywhere_ within the query chain!
216
217</details>
218
219<details>
220<summary>QueryBuilder.action(action)</summary>
221
222Rather than using the "default" actions (create/read/update/delete), you can override the action per query.
223
224This is useful when you have custom actions in your ACL (such as `promote`) for a specific endpoint/query. Just chain a `.action(customAction)` somewhere in the query (in this case, the `customAction` would be `"promote"`).
225
226</details>
227
228<details>
229<summary>QueryBuilder.fetchResourceContextFromDB()</summary>
230
231Sometimes, you need to know the values of the resource(s) you're trying to access before you can make an authorization decision. So instead of loading the model instance(s) yourself and running `.$query()` on them, you can chain `.fetchResourceContextFromDB()` to your query and automatically populate the `inputs`/resources that would've been affected by the query.
232
233e.g.
234
235```js
236await Person.query()
237 .authorize(user)
238 .where('lastName', 'george')
239 .update({ lastName: 'George' }) // input item
240 .fetchResourceContextFromDB() // Loads all people that would be affected by the update,
241// and runs authorization check on *all* of those individuals against the input item.
242```
243
244</details>
245
246<details>
247<summary>QueryBuilder.diffInputFromResource()</summary>
248
249This method is particularly useful for UPDATE requests, where the client is sending the _entire_ object (rather than just the changes, like PATCH). Obviously, if you put the whole object through the AuthZ check, it will trip up (for example, the client may include the object's id as part of an UPDATE request, and you don't want the ACL to think that the client is trying to change the id)!
250
251Therefore, call this method anywhere along the query chain, and the plugin will automatically diff the input object(s) with whatever the resource is! The beauty of this method is that it also works for _nested fields_, so even if your table includes a JSON field, only the exact diff - all the way down to the nested subfields - will be passed along to the ACL.
252
253e.g.
254
255```js
256Model.query()
257 .authorize(user, { id: 1, foo: { bar: 'baz', a: 0 } })
258 .updateById(id, { id: 1, foo: { bar: 'baz', b: 0 } })
259 .diffInputFromResource() // the diff will be { foo: { b: 0 } }
260```
261
262**NOTE**: the plugin is ONLY able to detect changes to an existing field's value or an addition of a _new_ field, NOT the deletion of an existing field (see above how the implicit deletion of `foo.a` is not included in the diff).
263
264Therefore, care must be taken during UPDATE queries where fields (_especially_ nested fields) may be added/removed dynamically. Having JSON subfields doesn't mean you throw out schema Mongo-style; so if you need to monitor for _deletion_ of a field (rather than mutation or addition), I would recommend assigning all of the possible fields' value with `null`, rather than leaving it out entirely, so that deletions would show up as mutations.
265
266e.g. in the above case, if you wanted to check whether field `foo.a` was deleted or not:
267
268```js
269resource = { id: 1, foo: { bar: 'baz', a: 0, b: null } }
270input = { id: 1, foo: { bar: 'baz', a: null, b: 0 } }
271```
272
273</details>
274
275<details>
276<summary>modelInstance.authorizeRead(user, [action = 'read'[, opts]])</summary>
277
278Prior to objection-authorize v4, the plugin "automatically" filtered any resulting model instances against a user's read access, but it didn't work consistently and I found it to be too hacky, so from v4 and on, you will need to manually call the `.authorizeRead()` on your model instance to filter it according to the user's read access (which can be overridden with the `action` parameter).
279
280This call is synchronous and will return the filtered model instance directly. Note that the result is a plain object, not an instance of the model _class_ anymore, since this call is meant to be for "finalizing" the model instance for returning to the user as a raw JSON.
281
282</details>
283
284## Defining the ACL
285
286The ACL is what actually checks the validity of a request, and `objection-authorize` passes all of the necessary context in the form of function parameters (thus, you should wrap your ACL in the following function format):
287
288```js
289function acl(user, resource, action, body, opts) {
290 // your ACL definition goes here
291}
292```
293
294**NOTE**: while `user` is cast into plain object form (simply due to the fact that `req.user` could be empty, and we would need to create a "fake" user with a default role), `resource` and `body` (aka `item` and `inputItem`) are cast into their respective _Models_ - this is to maintain consistency with the internal Objection.js static hooks' behaviour.
295
296For example, in a query:
297
298```js
299await Person.relatedQuery('pets')
300 .for([1, 2])
301 .insert([{ name: 'doggo' }, { name: 'catto' }])
302 .authorize(user)
303 .fetchContextFromDB()
304```
305
306The `resource` is an instance of model `Person`, and the `body` is an instance of model `Pet`. How do I know what class to wrap it in? Magic! ;)
307
308### @casl/ability
309
310For `casl`, because it doesn't allow dynamically checking against any resource or action, we have to wrap it with a function, and that function takes in `(user, resource, action, body, opts)` and returns an _instance_ of ability.
311
312This is essentially the same as the `defineAbilitiesFor(user)` method described [in the casl docs](https://stalniy.github.io/casl/abilities/2017/07/20/define-abilities.html), but obviously with a lot more context.
313
314So you might define your ability like this (and it doesn't matter if you use `AbilityBuilder` or `Ability`):
315
316```js
317const { AbilityBuilder } = require('@casl/ability')
318
319function acl(user, resource, action, body, opts) {
320 return AbilityBuilder.define((allow, forbid) => {
321 if (user.isAdmin()) {
322 allow('manage', 'all')
323 } else {
324 allow('read', 'all')
325 }
326 })
327}
328```
329
330**TIP**: If you want to cut down on the time it takes to check access, one thing you might want to do is to use the `resource` parameter to ONLY define rules relevant to that resource:
331
332```js
333function acl(user, resource, action, body, opts) {
334 return AbilityBuilder.define((allow, forbid) => {
335 switch (resource.constructor.name) {
336 case 'User':
337 allow('read', 'User')
338 forbid('read', 'User', ['email'])
339 break
340 case 'Post':
341 allow('create', 'Post')
342 forbid('read', 'Post', { private: true })
343 }
344 })
345}
346```
347
348### Note on Resource Names
349
350_For both libraries_, note that the resource name IS the corresponding model's name. So if you have a model class `Post`, you should be referring to that resource as `Post` and not `post` in your ACL definition.
351
352### Note on Sharing the ACL between frontend and the backend
353
354The resources that are passed to this plugin in the backend are typically going to be wrapped in their respective model classes: e.g. `req.user` typically will be an instance of the `User` class, and the resource will _always_ be wrapped with its respective class.
355
356So if you want to share your ACL between frontend and the backend, as the frontend doesn't have access to Objection models, any transformation you have on your models should be _symmetric_.
357
358For example, if you have `user.id` and `post.creatorId` and you hash ID's when you export it to JSON, you want to make sure if `user.id = post.creatorId = 1`, the transformed values are _also_ the same (`user.id = post.creatorId = XYZ`, for example).
359
360This also means that you _shouldn't_ rely on virtuals and asymmetrically-transformed fields on your ACL (if you want to use your ACL on the frontend, that is). For an example of symmetric transformation out in the wild, see https://github.com/JaneJeon/objection-hashid.
361
362## Relation support
363
364With objection-authorize v4, I added _experimental_ relation support, so on your ACL wrapper (the function that takes in 5 parameters - I really should just wrap them in an object but that would break compatibility), now there is an optional, 6th parameter called `relation`:
365
366```js
367function acl(user, resource, action, body, opts, relation) {
368 // your ACL definition goes here
369}
370```
371
372And that `relation` property is simply a string representation of the relation between `item` and `inputItem` that you specified in the resource model's `relationMappings`. So you can use that `relation` key to detect relations and do fancy things with it.
373
374In reality, most of the relation support is well-tested and already proven to be working, as the hardest part was to wrap the `inputItem` in the appropriate related class (rather than using the same class for both the `item` and `inputItem`); it's just that I can't test the `relation` string itself due to some... Objection finnickyness.
375
376## Run tests
377
378```sh
379npm test
380```
381
382## Author
383
384👤 **Jane Jeon**
385
386- Github: [@JaneJeon](https://github.com/JaneJeon)
387
388## 🤝 Contributing
389
390Contributions, issues and feature requests are welcome!<br />Feel free to check [issues page](https://github.com/JaneJeon/objection-authorize/issues).
391
392## Show your support
393
394Give a ⭐️ if this project helped you!
395
396## 📝 License
397
398Copyright © 2020 [Jane Jeon](https://github.com/JaneJeon).<br />
399This project is [MIT](https://github.com/JaneJeon/objection-authorize/blob/master/LICENSE) licensed.