diff --git a/docs/guides/check-permission.md b/docs/guides/check-permission.md new file mode 100644 index 00000000..eddeb7c1 --- /dev/null +++ b/docs/guides/check-permission.md @@ -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; +``` + +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`. diff --git a/docs/guides/polymorphism.md b/docs/guides/polymorphism.md index 6b5b5557..ad70febc 100644 --- a/docs/guides/polymorphism.md +++ b/docs/guides/polymorphism.md @@ -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 diff --git a/docs/reference/error-handling.md b/docs/reference/error-handling.md index b3de378a..f25da75d 100644 --- a/docs/reference/error-handling.md +++ b/docs/reference/error-handling.md @@ -1,6 +1,6 @@ --- description: Error handling -sidebar_position: 6 +sidebar_position: 7 --- # Error Handling diff --git a/docs/reference/plugins/_category_.yml b/docs/reference/plugins/_category_.yml index a2d8b377..29d8f6f3 100644 --- a/docs/reference/plugins/_category_.yml +++ b/docs/reference/plugins/_category_.yml @@ -1,4 +1,4 @@ -position: 4 +position: 5 label: Plugins collapsible: true collapsed: true diff --git a/docs/reference/plugins/swr.mdx b/docs/reference/plugins/swr.mdx index 512c9432..77aaa2ab 100644 --- a/docs/reference/plugins/swr.mdx +++ b/docs/reference/plugins/swr.mdx @@ -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). diff --git a/docs/reference/plugins/tanstack-query.mdx b/docs/reference/plugins/tanstack-query.mdx index d466cc2d..2aa265f0 100644 --- a/docs/reference/plugins/tanstack-query.mdx +++ b/docs/reference/plugins/tanstack-query.mdx @@ -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: diff --git a/docs/reference/prisma-client-ext.md b/docs/reference/prisma-client-ext.md new file mode 100644 index 00000000..63358e8f --- /dev/null +++ b/docs/reference/prisma-client-ext.md @@ -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; +``` + +#### 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 } +}); +``` diff --git a/docs/reference/runtime-api.md b/docs/reference/runtime-api.md index f0f15576..835b74a9 100644 --- a/docs/reference/runtime-api.md +++ b/docs/reference/runtime-api.md @@ -19,7 +19,7 @@ Creates an enhanced wrapper for a `PrismaClient`. The return value has the same ```ts function enhance( prisma: DbClient, - context?: WithPolicyContext, + context?: EnhancementContext, options?: EnhancementOptions ): DbClient; ``` diff --git a/docs/reference/server-adapters/_category_.yml b/docs/reference/server-adapters/_category_.yml index 21ccbbc0..a69eb540 100644 --- a/docs/reference/server-adapters/_category_.yml +++ b/docs/reference/server-adapters/_category_.yml @@ -1,4 +1,4 @@ -position: 5 +position: 6 label: Server Adapters collapsible: true collapsed: true diff --git a/docs/reference/server-adapters/api-handlers/rpc.mdx b/docs/reference/server-adapters/api-handlers/rpc.mdx index 4b7864df..ecfd1c96 100644 --- a/docs/reference/server-adapters/api-handlers/rpc.mdx +++ b/docs/reference/server-adapters/api-handlers/rpc.mdx @@ -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 diff --git a/docs/upgrade.md b/docs/upgrade.md index 358b3964..aad81beb 100644 --- a/docs/upgrade.md +++ b/docs/upgrade.md @@ -113,9 +113,23 @@ You can switch back to the old behavior in the extension settings (VSCode only). We've updated the `@zenstackhq/runtime` package to be compatible with Vercel Edge Runtime and Cloudflare Workers. See [this documentation](./guides/edge) for more details. -### 6. Permission Checker API 🚧 +### 6. Permission Checker API (Preview) -Coming soon. Please watch [this feature request](https://github.com/zenstackhq/zenstack/issues/242) for updates. +ZenStack's access policies prevent unauthorized users to query or mutate data. 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. + +The new permission checker API allows to check a user's permission without querying the database. + +```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 } +}); +``` + +Please check [this guide](./guides/check-permission) for more details. ## Upgrading