Skip to content
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
200 changes: 200 additions & 0 deletions docs/guides/check-permission.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,200 @@
---
description: Checking permissions without hitting the database.
sidebar_position: 13
---

# Checking Permissions Without Hitting the Database (Preview)

## Introduction

ZenStack's access policies provide a protection layer around Prisma's CRUD operations and filter/deny access to the data automatically. However, there are cases where you simply want to check if an operation is permitted without actually executing it. For example, you might want to show or hide a button based on the user's permission.

Of course, you can determine the permission by executing the operation to see if it's allowed (try reading data, or mutating inside a transaction then aborting). But this comes with the cost of increased database load, slower UI rendering, and data pollution risks.

Another choice is to implement permission checking logic directly inside your frontend code. However, it'll be much nicer if the access policies in ZModel can be reused, so it stays as the single source of truth for access control.

This guide introduces how to use ZenStack's `check` API to check permissions without accessing the database. The feature is in preview, and feedback is highly appreciated.

:::danger

Permission checking is an approximation and can be over-permissive. You MUST NOT trust it and circumvent the real access control mechanism (e.g., calling raw Prisma CRUD operations without further authorization checks).

:::

## Understanding the Problem

ZenStack's access policies are by design coupled with the data model, which implies that to check permission precisely, you'll have to evaluate it against the actual data. In reality, what you often need is an approximation, or in other words, a "weak" check. For example, you may want to check if the current user, given his role, can read entities of a particular model, and if so, render the corresponding part of UI. You don't really want to guarantee that the user is allowed to read every row of that model. What you care about is if he's potentially allowed.

With this in mind, "checking permission" is equivalent to answering the following question:

> Assuming we can have arbitrary rows of data in the database, can the access policies for the given operation possibly evaluate to `TRUE` for the current user?
The problem then becomes a [Boolean Satisfiability Problem](https://en.wikipedia.org/wiki/Boolean_satisfiability_problem). We can treat model fields as "variables" and use a [SAT Solver](https://en.wikipedia.org/wiki/SAT_solver) to find a solution for those variables that satisfy the access policies. If a solution exists, then the permission is possible.

Let's make the discussion more concrete by looking at an example:

```zmodel
model Post {
id Int @id @default(autoincrement())
title String
author User @relation(fields: [authorId], references: [id])
authorId Int
published Boolean @default(false)
@@allow('read', published || authorId == auth().id)
}
```

The "read" policy rule can be converted to a boolean formula like:

```mermaid
flowchart LR
OR((OR)) --> A["[published] == true"]
OR((OR)) --> B["[authorId] == context.user.id"]
```

:::info

- The `context` object is the second argument you pass to the `enhance` API call.
- A name wrapped with square brackets represents a named variable in a boolean formula.

:::

To check if a user can read posts, we simply need to find a solution for the `published` and `authorId` variables that make the boolean formula evaluate to `TRUE`.

## Using the `check` API

ZenStack adds a `check` API to every model in the enhanced PrismaClient. The feature is still in preview, so you need to explicitly opt in by turning on the "generatePermissionChecker" flag on the "@core/enhancer" plugin in ZModel:

```zmodel
plugin enhancer {
provider = '@core/enhancer'
generatePermissionChecker = true
}
```

Then, rerun `zenstack generate`, and the `check` API will be available on each model with the following signature (using the `Post` model as an example):

```ts
type CheckArgs = {
/**
* The operation to check for
*/
operation: 'create' | 'read' | 'update' | 'delete';

/**
* The optional additional constraints to impose on the model fields
*/
where?: { id?: number; title?: string; published?: boolean; authorId?: number };
}

check(args: CheckArgs): Promise<boolean>;
```

Let's see how to use it to check `Post` readability for different use cases. Just to recap, the boolean formula for the "read" policy is:

```mermaid
flowchart LR
OR((OR)) --> A["[published] == true"]
OR((OR)) --> B["[authorId] == context.user.id"]
```

### 1. Can an anonymous user read posts?

The scenario is to determine if the `Posts` UI tab should be visible when the current user is not logged in. We can do the checking as follows:

```ts
const db = enhance(prisma); // enhance without a user context
await canRead = await db.post.check({ operation: 'read' });
```

The result will be `true` with the following variable assignments:

- `published -> true`
- `authorId -> 0`

Note that the `authorId` variable can actually be any integer.

### 2. Can an anonymous user read unpublished posts?

The scenario is to determine if the `Drafts` UI tab should be visible when the current user is not logged in.

```ts
const db = enhance(prisma); // enhance without a user context
await canRead = await db.post.check({ operation: 'read', where: { published: false } });
```

We're now adding an additional constraint `published == false` that the solver needs to consider besides the original formula:

```mermaid
flowchart LR
OR((OR)) --> A["[published] == true"]
OR((OR)) --> B["[authorId] == context.user.id"]
AND((AND)) --> C["[published] == false"]
AND((AND)) --> OR
style C stroke-dasharray: 5, 5
```

The result will be `false` because there are no assignments of the `published` and `authorId` variables that satisfy the formula. Note that the `context.user.id` value is undefined thus cannot be equal to `authorId`.

### 3. Can `user#1` read unpublished posts

The scenario is to determine if the `Drafts` UI tab should be visible for a currently logged-in user.

```ts
const db = enhance(prisma, { user: { id: 1 } }); // enhance with user context
await canRead = await db.post.check({ operation: 'read', where: { published: false } });
```

We're now providing a value `1` to `context.user.id`, and the formula becomes:

```mermaid
flowchart LR
OR((OR)) --> A["[published] == true"]
OR((OR)) --> B["[authorId] == 1"]
AND((AND)) --> C["[published] == false"]
AND((AND)) --> OR
style C stroke-dasharray: 5, 5
```

The result will be `true` with the following variable assignments:

- `published -> false`
- `authorId -> 1`

## Server Adapters and Hooks

The `check` API is also available in the [RPC API Handler](../reference/server-adapters/api-handlers/rpc) and can be used with all [server adapters](../category/server-adapters).

The [@zenstackhq/tanstack-query](../reference/plugins/tanstack-query) and [@zenstackhq/swr](../reference/plugins/swr) plugins have been updated to generate `useCheck[Model]` hooks for checking permissions in the frontend.

```ts
import { useCheckPost } from '~/lib/hooks';

const { data: canReadDrafts } = useCheckPost({
operation: 'read',
where: { published: false }
});
```

## Limitations

ZenStack uses the [logic-solver](https://www.npmjs.com/package/logic-solver) package for SAT solving. The solver is lightweighted, but only supports boolean and bits (non-negative integer) types. This resulted in the following limitations:

- Only `Boolean`, `Int`, `String`, and enum types are supported.
- Functions (e.g., `startsWith`, `contains`, etc.) are not supported.
- Array fields are not supported.
- Relation fields are not supported.
- Collection predicates are not supported.

You can still use the `check` API even if your access policies use these unsupported features. Boolean components containing unsupported features are ignored during SAT solving by being converted to free variables, which can be assigned either `true` or `false` in a solution.

## Notes About Anonymous Context

Access policy rules often use `auth()` and members of `auth()` (e.g., `auth().role`) in them. When a PrismaClient is enhanced in an anonymous context (calling `enhance` without context user object), neither `auth()` nor its members are unavailable. In such cases, the following evaluation rules apply:

- `auth() == null` evaluates to `true`.
- `auth() != null` evaluates to `false`.
- Any other form of boolean component involving `auth()` or its members evaluates to `false`.
2 changes: 1 addition & 1 deletion docs/guides/polymorphism.md
Original file line number Diff line number Diff line change
Expand Up @@ -265,7 +265,7 @@ The main thing that ZenStack does internally is to translate between these two "

- Inheriting from multiple `@delegate` models is not supported yet.

- You cannot access base fields when calling `count`, `aggregate`, and `groupBy`. The following query is not supported:
- You cannot access base fields when calling `count`, `aggregate`, and `groupBy` with a concrete model. The following query is not supported:

```ts
// you can't access base fields (`published` here) when aggregating
Expand Down
2 changes: 1 addition & 1 deletion docs/reference/error-handling.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
---
description: Error handling
sidebar_position: 6
sidebar_position: 7
---

# Error Handling
Expand Down
2 changes: 1 addition & 1 deletion docs/reference/plugins/_category_.yml
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
position: 4
position: 5
label: Plugins
collapsible: true
collapsed: true
Expand Down
30 changes: 30 additions & 0 deletions docs/reference/plugins/swr.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,36 @@ export default MyApp;
| ------- | ------ | ------------------------------------------------------- | -------- | ------- |
| output | String | Output directory (relative to the path of ZModel) | Yes | |

### Hooks Signature

The generated hooks have the following signature convention.

- **Query Hooks**

```ts
function use[Operation][Model](args?, options?);
```

- `[Operation]`: query operation. E.g., "FindMany", "FindUnique", "Count".
- `[Model]`: the name of the model. E.g., "Post".
- `args`: Prisma query args. E.g., `{ where: { published: true } }`.
- `options`: swr options.

The `data` field returned by the hooks call contains the Prisma query result.

- **Mutation Hooks**

```ts
function use[Operation][Model](options?);
```

- `[Operation]`: mutation operation. E.g., "Create", "UpdateMany".
- `[Model]`: the name of the model. E.g., "Post".
- `options`: swr options.

The `trigger` function returned with the hooks call takes the corresponding Prisma mutation args as input. E.q., `{ data: { title: 'Post1' } }`.


### Example

Here's a quick example with a blogging app. You can find a fully functional Todo app example [here](https://github.com/zenstackhq/sample-todo-nextjs).
Expand Down
29 changes: 29 additions & 0 deletions docs/reference/plugins/tanstack-query.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,35 @@ npm install --save-dev @zenstackhq/tanstack-query
| target | String | Target framework to generate for. Choose from "react", "vue", and "svelte". | Yes | |
| version | String | Version of TanStack Query to generate for. Choose from "v4" and "v5". | No | v5 |

### Hooks Signature

The generated hooks have the following signature convention.

- **Query Hooks**

```ts
function use[Operation][Model](args?, options?);
```

- `[Operation]`: query operation. E.g., "FindMany", "FindUnique", "Count".
- `[Model]`: the name of the model. E.g., "Post".
- `args`: Prisma query args. E.g., `{ where: { published: true } }`.
- `options`: tanstack-query options.

The `data` field returned by the hooks call contains the Prisma query result.

- **Mutation Hooks**

```ts
function use[Operation][Model](options?);
```

- `[Operation]`: mutation operation. E.g., "Create", "UpdateMany".
- `[Model]`: the name of the model. E.g., "Post".
- `options`: TanStack-Query options.

The `mutate` and `mutateAsync` functions returned with the hooks call take the corresponding Prisma mutation args as input. E.q., `{ data: { title: 'Post1' } }`.

### Context Provider

The generated hooks allow you to control their behavior by setting up context. The following options are available on the context:
Expand Down
57 changes: 57 additions & 0 deletions docs/reference/prisma-client-ext.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
---
description: APIs ZenStack adds to the PrismaClient
sidebar_position: 4
sidebar_label: Added PrismaClient APIs
---

# Added PrismaClient APIs

ZenStack's enhancement to PrismaClient not only alters its existing APIs' behavior, but also adds new APIs.

### check

#### Scope

This API is added to each model in the PrismaClient.

#### Description

Checks if the current user is allowed to perform the specified operation on the model based on the access policies in ZModel. The check is done via pure logical inference and doesn't query the database.

Please refer to [Checking Permissions Without Hitting the Database](../guides/check-permission) for more details.

:::danger

Permission checking is an approximation and can be over-permissive. You MUST NOT trust it and circumvent the real access control mechanism (e.g., calling raw Prisma CRUD operations without further authorization checks).

:::

#### Signature

```ts
type CheckArgs = {
/**
* The operation to check for
*/
operation: 'create' | 'read' | 'update' | 'delete';

/**
* The optional additional constraints to impose on the model fields
*/
where?: { ... };
}

check(args: CheckArgs): Promise<boolean>;
```

#### Example

```ts
const db = enhance(prisma, { user: getCurrentUser() });

// check if the current user can read published posts
await canRead = await db.post.check({
operation: 'read',
where: { published: true }
});
```
2 changes: 1 addition & 1 deletion docs/reference/runtime-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ Creates an enhanced wrapper for a `PrismaClient`. The return value has the same
```ts
function enhance<DbClient extends object>(
prisma: DbClient,
context?: WithPolicyContext,
context?: EnhancementContext,
options?: EnhancementOptions
): DbClient;
```
Expand Down
2 changes: 1 addition & 1 deletion docs/reference/server-adapters/_category_.yml
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
position: 5
position: 6
label: Server Adapters
collapsible: true
collapsed: true
Expand Down
4 changes: 4 additions & 0 deletions docs/reference/server-adapters/api-handlers/rpc.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -236,6 +236,10 @@ The following part explains how the `meta` information is included for different

_Http method:_ `DELETE`

- **[model]/check**

_Http method:_ `GET`

## HTTP Status Code and Error Responses

### Status code
Expand Down
Loading