= Permissions :nav-title: Permissions :description: Permissions decide what each role may do in your service: which paths, which methods, and which documents, checked on the server for every request. :keywords: access control, permissions, ACL, role-based access, row-level security, authorization backend, readFilter :group: Your users :order: 20 A permission says what a role may do in your service: which paths, which methods, and optionally which documents. Permissions are documents in the `acl` collection, managed under **Permissions**. Use them to decide who reads and writes what. For example, users with the role `user` may read `/orders`, and see only the orders they own. What you get: * **Checks on the server.** Every request to your service is checked against the permissions on the server, where the client cannot bypass them. * **Rules per document.** Filters can limit a user to their own documents, or hide fields from them. * **One set of rules for every client.** Your app, a script and an AI agent over MCP follow the same permissions. image::/assets/docs-images/permissions.png[The Permissions page: each rule with its roles, predicate and priority] == How a request is checked Every request is checked against the permissions in the `acl` collection: 1. Only the permissions for the user's roles count. 2. They are tried in descending `priority` order: **higher numbers are evaluated first**. 3. The first one whose `predicate` matches the request (path, method, query string and so on) allows it, and its `mongo` options apply. 4. If none matches, the request is refused. === The path on Enterprise [cols="1,2"] |=== | Plan | ACL collection path | Free, Starter and Pro | `/acl` | Enterprise | `/restheart/acl` |=== In the console the page is always **Permissions**, whatever the plan. == A permission document [source,json] ---- { "_id": "usersCanReadOrders", "roles": ["user"], "predicate": "path-prefix('/orders') and method('GET')", "priority": 100, "mongo": { "readFilter": { "owner": "@user._id" }, "writeFilter": null, "mergeRequest": null, "projectResponse": null } } ---- [cols="1,1,3"] |=== | Field | Required | Description | `_id` | Yes | A unique name for the permission. Make it say what it does, such as `readersCanGetPosts`. | `roles` | Yes | The role names the permission applies to. A user who holds at least one of them is covered. Roles are set on each user, on the xref:managing-users.adoc[Users] page. | `predicate` | Yes | The condition a request must meet for the permission to match. See <> below. | `priority` | Yes | The evaluation order. Higher values are evaluated first, so give the more specific permissions the higher numbers. | `mongo` | No | Filters and changes applied to the data the request reads or writes. See <>. | `apiKeys` | No | Only on a permission for `/keys`: which roles an API key issued under it may carry, and its limits. See <> below. |=== == The list The page lists the permissions with their roles, predicate and priority, a page at a time. === Filter and sort Type a MongoDB query in the **Filter** field, for example: [source,json] ---- { "roles": "user" } ---- or [source,json] ---- { "priority": { "$lt": 50 } } ---- The **Sort** field takes a sort document, such as `{"priority": -1}`. == Add a permission . Click **Add permission**. . Fill in the form fields: ** **Permission ID** (`_id`): a unique name. ** **Roles**: one or more role names, separated by commas. ** **Predicate**: which requests it is about (see below). The console checks it as you type. ** **Priority**: higher numbers are evaluated first. ** **MongoDB permissions**: optionally, the switches and the JSON of the `mongo` block: `readFilter`, `sort`, `writeFilter`, `mergeRequest`, `projectResponse`. See <>. ** **API key issuance**: optionally, the `apiKeys` block of a permission on `/keys`. See <>. . Click **Create permission**. The console sends `POST /acl` with the document. == Edit a permission . Click **Edit** on a permission. The form opens in place. . Change any field except the ID. . Click **Save**. The console sends `PUT /acl/` with the whole document. == Delete a permission Click **Delete** on a permission and confirm. The console sends `DELETE /acl/`. WARNING: A deleted permission stops working within 20 seconds, the time any change to a permission takes to apply. Users whose access relied on it alone are refused from then on. == The predicate language [[predicate-language]] A predicate is a condition on the request, written in the Undertow predicate language. These are the ones you will use most: === Paths [cols="1,2,2"] |=== | Predicate | Description | Example | `path('/exact/path')` | Matches the exact request path. | `path('/status')` | `path-prefix('/prefix')` | Matches any path that starts with the given prefix. | `path-prefix('/orders')` | `path-template('/users/{id}')` | Matches a path with variable segments. Refer to a captured segment later in the predicate as `${id}`. | `path-template('/users/{id}/profile')` | `path-suffix('.json')` | Matches paths ending with the given suffix. | `path-suffix('.csv')` | `regex(pattern: '...', value: %R)` | Matches the path against a regular expression. | `regex(pattern: '^/data/[0-9]+$', value: %R)` |=== === Methods [cols="1,2"] |=== | Predicate | Example | `method('GET')` | `method('POST')` | `method('PUT')` | `method('DELETE')` | `method('PATCH')` | |=== === Combining them Combine predicates with `and`, `or` and `not`: [source] ---- path-prefix('/orders') and method('GET') ---- [source] ---- path-prefix('/reports') and (method('GET') or method('POST')) ---- [source] ---- path-prefix('/admin') and not method('GET') ---- === Common predicates [cols="2,3"] |=== | Goal | Predicate | Allow GET on any path | `method('GET')` | Allow all methods on `/orders` and sub-paths | `path-prefix('/orders')` | Allow POST only to `/users` | `path('/users') and method('POST')` | Allow GET and PATCH on `/products/{id}` | `path-template('/products/{id}') and (method('GET') or method('PATCH'))` | Allow everything under `/public` | `path-prefix('/public')` | Allow every method except DELETE, on every path | `not method('DELETE')` | Allow a user to edit only their own document | `path-template('/users/{userId}') and method(PATCH) and equals(@user._id, ${userId})` | ... and only one field of it | `... and bson-request-whitelist(consents)` |=== `@user._id` is the id of the user making the request, with Basic auth and with a token alike: the tokens a service issues carry `_id` as a claim. `@qparams['name']` is the query parameter `?name=`, as a string, exactly as the client wrote it. `bson-request-whitelist` takes one or more comma-separated keys, dotted for nested ones (`bson-request-whitelist(profile.name, profile.surname)`), and checks the request body as the client sent it, before any `mergeRequest` adds to it. TIP: The **Predicate reference** panel at the bottom of the Permissions page lists the predicates, and the help icon beside the **Predicate** field opens this section. == Limit what a user sees and writes [[mongo-options]] The optional `mongo` object acts on the data. It applies to every request the permission allows, and the client does not see it. === `readFilter` A MongoDB filter added to every read (`GET`). The client sees only the documents that match it, whatever `filter` it sends. *Each user sees only their own documents:* [source,json] ---- { "mongo": { "readFilter": { "owner": "@user._id" } } } ---- `@user._id` is replaced with the `_id` of the user making the request, whether the request carries Basic auth or a token. A condition can depend on the request. With `$ifvar` it applies only when the client passes a parameter. The client can only restrict the results further: [source,json] ---- { "mongo": { "readFilter": { "$and": [ { "published": true }, { "$ifvar": ["category", { "category": { "$var": "category" } }] } ] } } } ---- `GET /products?category=desk` returns the published desks. Without `category` the condition is dropped, and only `{ "published": true }` applies. Keep the mandatory part outside the `$ifvar`. <> explain how a parameter is read. === `sort` [[sort]] The order of every read the permission allows, as a MongoDB sort document: `1` ascending, `-1` descending. Without it, documents come newest first, by `_id` descending. [source,json] ---- { "mongo": { "readFilter": { "published": true }, "sort": { "name": 1 } } } ---- When the sort does not end on `_id`, the server appends it. The same page then returns the same documents every time. The permission can declare several orders and let the client pick one by name: [source,json] ---- { "mongo": { "sort": { "$ifvar": ["order", { "by-name": { "name": 1 }, "newest": { "createdAt": -1 } }, { "createdAt": -1 } ] } } } ---- `?order=by-name` sorts by name. Without `order` the third element applies. A name the permission does not declare gets 400. To let the client choose only the direction, `$var` with a default is enough. `{ "createdAt": { "$var": ["dir", -1] } }` sorts newest first, and `?dir=1` oldest first. Any value other than `1` or `-1` gets 400. On a large collection, sort on indexed fields: without an index MongoDB may exceed its in-memory sort limit. === `writeFilter` A MongoDB filter applied to every write (`PUT`, `PATCH`, `DELETE`). A write reaches only the documents that match it, and nothing tells the client. *Users cannot change other users' documents:* [source,json] ---- { "mongo": { "writeFilter": { "owner": "@user._id" } } } ---- === `mergeRequest` A document merged into the body of every write before it is stored. Use it for fields the server sets and the client cannot forge. *A new document is stamped with its owner:* [source,json] ---- { "mongo": { "mergeRequest": { "owner": "@user._id" } } } ---- Write sub-documents as nested objects, without dotted keys. MongoDB rejects a merged request that touches both a field and a path inside it, with `ConflictingUpdateOperators`. ==== Update operators in `mergeRequest` Plain fields are merged into `$set`. A MongoDB update operator can be merged too, written with a **leading underscore** because a key starting with `$` cannot be stored in a document. `_$push` becomes `$push` when the request is merged. *Append to a history the server controls, which the client cannot overwrite:* [source,json] ---- { "mongo": { "mergeRequest": { "lastSeenAt": "@now", "_$push": { "auditTrail": { "at": "@now", "by": "@user._id" } } } } } ---- The client sends the field only to satisfy whatever `bson-request-whitelist` the predicate carries; the value it sends for a key that an array operator manages is discarded, so the two cannot conflict. === `projectResponse` A MongoDB projection applied to every document in the response. Use it to hide sensitive fields. *Hide sensitive fields:* [source,json] ---- { "mongo": { "projectResponse": { "passwordHash": 0, "internalNotes": 0 } } } ---- === `allowFilter` [[allow-filter]] Off by default. A read whose request carries `filter`, `sort` or `sort_by` does not match the permission, and gets 403 unless another permission allows it. In the form it is the **Free queries** switch. With `"allowFilter": true` the client may send its own query in a read, within the `readFilter`. The permission's `sort` becomes the default order, used when the client sends no `sort`. [source,json] ---- { "mongo": { "allowFilter": true } } ---- We advise against it. It lets the client run any query on the collection the permission covers. We suggest a query you declare: an xref:aggregations.adoc[aggregation]. The app calls it by name, and it reads from the request only the parameters it declares. For many reads the permission alone is enough: * the documents of the caller, or the public ones: `GET /`, with `readFilter`, paged with `page` and `pagesize`; * one document: `GET //`, with the same `readFilter`; * the count: `GET //_size`, which counts only the documents of the `readFilter`; * an order, or a criterion among the ones you declare: <> and `$ifvar` in `readFilter`. `allowFilter` covers reads only. A `PATCH` or `DELETE` on `//*` needs a `filter`, and `allowBulkPatch` and `allowBulkDelete` decide whether it is allowed. In a new service, the `rootCanDoEverything` permission of the `root` role has `allowFilter` on. === Variables you can use [[variables]] [cols="1,3"] |=== | Variable | Value at runtime | `@user._id` | The `_id` of the authenticated user. | `@user.roles` | The `roles` array of the authenticated user. | `@now` | The current instant, as a BSON date. In a JSON Schema, declare it as `{"_$date": {"type": "number"}}`. |=== They can also be written `{ "$var": "@user._id" }`. A query parameter `?x=` can be read in two ways: [cols="1,3"] |=== | Written as | Value at runtime | `{ "$var": "x" }` | The parameter read as JSON: `?x=1` is the number 1. A value that contains an operator gets 400. Only in JSON: the `mongo` block and the stages of an xref:aggregations.adoc#avars[aggregation]. With a default: `{ "$var": ["x", "en"] }`. | `@qparams['x']` | The parameter as a string, exactly as the client wrote it. In predicates and in JSON. |=== == API keys [[api-keys]] A request that authenticates with an xref:api-keys.adoc[API key] goes through the same permissions as a password sign-in, with one difference: it carries the **key's roles**, which can differ from the roles of the user who issued it. A key's roles are usually narrower than its owner's, and each one is an ordinary role that you grant permissions to like any other. `readFilter`, `projectResponse` and the rest apply as usual. Which roles a key may be given is decided here too. A permission that lets a role reach `/keys` carries an `apiKeys` block: [source,json] ---- { "_id": "usersIssueKeys", "roles": ["user"], "predicate": "path-prefix('/keys')", "priority": 100, "apiKeys": { "roles": ["cli-ro"], "max-expires-in-days": 90, "max-keys-per-user": 5 } } ---- [cols="1,3"] |=== | Field | Meaning | `roles` | The roles a key issued under this permission may carry. Required: a non-empty array of distinct role names. | `max-expires-in-days` | The longest life such a key may have. Optional; the service default applies otherwise, and a user may always ask for less. | `max-keys-per-user` | How many keys one user may hold at a time. Optional; the service default applies otherwise. |=== Three things to know: * **A permission on `/keys` without the block issues nothing.** Its roles reach the endpoint and get a `403` that says so. * **A malformed block is refused when the permission is written**, with a `400` that names the field, whether it comes from the console, `ulabase` or `curl`. * **The key's roles need not be roles the user holds.** With the example above a `user` may issue a `cli-ro` key, and what that key can do is whatever *other* permissions grant to `cli-ro`. The **API Keys** page lists the permissions on `/keys` with the roles each one grants and adds new ones from three fields. They are the same documents you see on the Permissions page. == Priority Permissions with **higher** priority numbers are evaluated **first**. When a user has more than one role, the permissions of all their roles are compared together: among those that match the request, the one with the highest priority applies, together with its `mongo` options. Between two matching permissions with the same priority, the one with the higher `_id` wins, whichever roles they belong to; with generated ids, that is the newer one. Give different priorities to permissions that can match the same request, and the `_id` never decides. [cols="1,3"] |=== | Priority value | Typical use | `200` and up | Specific exceptions that must win over a standard permission: an exact path, a single method. | `100` | Standard application permissions. | `1` to `99` | Catch-all or fallback permissions. | `0` | `rootCanDoEverything` and `rootCanDeleteSrvDb`, the permissions of the `root` role. |=== TIP: When two permissions of the same role match a request, the one with the higher number decides. Give the most specific ones the highest numbers. == A worked example: orders Three permissions for a typical order system: .Allow admins to do everything on `/orders` [source,json] ---- { "_id": "adminsFullOrders", "roles": ["admin"], "predicate": "path-prefix('/orders')", "priority": 10 } ---- .Allow users to create orders (with auto-stamped owner) [source,json] ---- { "_id": "usersCreateOrders", "roles": ["user"], "predicate": "path('/orders') and method('POST')", "priority": 100, "mongo": { "mergeRequest": { "owner": "@user._id" } } } ---- .Allow users to read only their own orders [source,json] ---- { "_id": "usersReadOwnOrders", "roles": ["user"], "predicate": "path-prefix('/orders') and method('GET')", "priority": 100, "mongo": { "readFilter": { "owner": "@user._id" } } } ---- == From a script [cols="2,3"] |=== | Operation | Endpoint | List permissions | `GET /acl?page=...&pagesize=...&filter=...&sort=...` | Create permission | `POST /acl` | Update permission | `PUT /acl/` with the whole document, or `PATCH /acl/` with the fields to change | Delete permission | `DELETE /acl/` |=== On **Enterprise** plans replace `/acl` with `/restheart/acl` in all paths above. == Do it from the command line You can keep your permissions in git and apply them with xref:cli.adoc[`ulabase setup`]. The step below writes the third permission of the example above, which lets users read their own orders: [source,typescript] ---- import { defineSetup, step } from '@ulabase/cli'; // users may read orders, and see only those they own const usersReadOwnOrders = { roles: ['user'], predicate: "path-prefix('/orders') and method('GET')", priority: 100, mongo: { readFilter: { owner: '@user._id' } }, }; export default defineSetup('Permissions', [ step('usersReadOwnOrders in place', { async check({ service }) { if (!(await service.permissionExists('usersReadOwnOrders'))) return false; // compare the saved permission with the file: if you changed it in git, the apply saves it again const res = await service.fetch('/acl/usersReadOwnOrders'); const { roles, predicate, priority, mongo } = await res.json(); return JSON.stringify({ roles, predicate, priority, mongo }) === JSON.stringify(usersReadOwnOrders); }, apply: ({ service }) => service.putPermission('usersReadOwnOrders', usersReadOwnOrders), }), ]); ---- The check compares the stored permission with the one in the file. If you change it in git, the next run writes it again. == Related pages * xref:managing-users.adoc[Users]: the users and the roles permissions refer to. * xref:guards.adoc[Guards]: rules checked *after* permissions, on the user's state. * xref:root-user-setup.adoc[Root user]: where the `rootCanDoEverything` permission comes from. * xref:users-and-permissions.adoc[Users and permissions through the API]: the requests behind this page. * xref:api-keys.adoc[API keys]: the `apiKeys` block, and what a request made with a key may do. * xref:plans.adoc[Plans]: the collection paths that change on Enterprise.