Security

Permission Management

RESTHeart Ulabase

Configuration

The URL and credentials the examples on this page use

localhost:8080 with admin:secret Saved in your browser

Setup Guide

Where to run the examples on this page

To run the examples on this page, you need a RESTHeart instance.

Option 1: Use Ulabase (Recommended)

The fastest way to get started is with Ulabase. Create a free service in minutes:

  1. Sign up at ulabase.com

  2. Create a free API service

  3. Set up your root user following the Root User Setup guide

  4. Use the configuration panel above to set your service URL and credentials

Tip
All code examples on this page will automatically use your configured Ulabase credentials.

Option 2: Run RESTHeart Locally

If you prefer local development, follow the Setup Guide to install RESTHeart on your machine.

Note
Local instances run at http://localhost:8080 with default credentials admin:secret

Introduction

This page describes the permissions of the ACL (Access Control List): their format, how they are evaluated, and how to manage them.

An authorizer is a plugin, and RESTHeart can run more than one. This page covers mongoAclAuthorizer and fileAclAuthorizer, which share the same permission format:

  • mongoAclAuthorizer: Stores permissions as JSON documents in a MongoDB collection (default: /acl)

  • fileAclAuthorizer: Stores permissions in a YAML configuration file

With both, a permission declares which roles may execute which requests, and what they may read and write.

Tip
For an overview of RESTHeart’s security architecture, see Security Overview and Authorization.

Permission Format

A permission document defines who can access what resources under which conditions. The structure is the same whether stored in MongoDB (JSON) or in a configuration file (YAML).

Permission Properties

Property Type Description

predicate

string

A undertow predicate that defines when the permission applies. If the predicate resolves to true, the request is authorized. See Understanding Predicates for details.

roles

array of strings

The roles that this permission applies to. Use the special role $unauthenticated for requests without authentication.

priority

number

When multiple permissions match a request, higher priority permissions are evaluated first. Use this to create hierarchical permission rules.

mongo

object or null

Optional. For requests to MongoDB REST API, specifies additional MongoDB-specific permissions. See MongoDB-Specific Permissions for details.

_id

string

(Optional but recommended) A unique identifier for the permission. Useful for updates and debugging.

description

string or array

(Optional) Human-readable description of what the permission does.

Your Own Fields

A permission may carry fields of your own beside the ones above: the authorizer keeps the document whole and ignores what it does not know. This is how a plugin reads a setting from the permission that let the request in, rather than from a lookup of its own that might pick a different one:

var permission = BaseAclPermission.of(request);        // what the authorizer attached

if (permission != null && permission.getRaw() instanceof BsonDocument raw) {
    var block = raw.get("apiKeys");                    // your field, as written
}

Ulabase uses this for the API Keys permission, whose apiKeys block names the roles a key may be given. Available from RESTHeart 9.9: earlier releases loaded permissions with a projection and dropped every field they did not read.

Basic Permission Example (JSON)

{
  "_id": "userCanReadInventory",
  "description": "Users can read the inventory collection",
  "roles": ["user"],
  "predicate": "path('/inventory') and method(GET)",
  "priority": 100
}

Basic Permission Example (YAML)

- _id: userCanReadInventory
  description: Users can read the inventory collection
  roles: [ user ]
  predicate: path('/inventory') and method(GET)
  priority: 100

Understanding Predicates

Predicates use the undertow predicate language to define conditions that must be met for a permission to apply.

Common Predicate Functions

Function Description Example

path()

Matches exact path

path('/inventory')

path-prefix()

Matches path prefix

path-prefix('/api')

path-template()

Matches path with variables

path-template('/{userid}/orders')

method()

Matches HTTP method

method(GET) or method(POST)

equals()

Compares two values

equals(@user._id, ${userid})

regex()

Matches path with regex

regex('/.*/orders')

Combining Predicates

Use and, or, and not to create complex conditions:

method(GET) and path-prefix('/api')
(method(GET) or method(POST)) and path('/users')
path-prefix('/admin') and not method(DELETE)

RESTHeart Custom Predicates

RESTHeart extends the undertow predicate language with additional predicates specifically designed for API security:

Query Parameter Predicates
Predicate Description Example

qparams-contain

Request must include specified query parameters

qparams-contain(page, pagesize)

qparams-blacklist

Request must NOT include blacklisted parameters

qparams-blacklist(filter, sort)

qparams-whitelist

Request must only include whitelisted parameters

qparams-whitelist(page, pagesize, limit)

qparams-size

Request must have exactly N query parameters

qparams-size(2)

Request Body Predicates (BSON/JSON)
Predicate Description Example

bson-request-contains

Request body must contain specified properties

bson-request-contains(name, email)

bson-request-whitelist

Request body can only contain whitelisted properties

bson-request-whitelist(title, status)

bson-request-blacklist

Request body must NOT contain blacklisted properties

bson-request-blacklist(password, secret)

bson-request-prop-equals

Property in request must equal a value

bson-request-prop-equals(key=status, value='"draft"')

bson-request-array-contains

Array property must contain all specified values

bson-request-array-contains(key=tags, values='"public"')

bson-request-array-is-subset

Array property must be subset of allowed values

bson-request-array-is-subset(key=roles, values={'user','admin'})

Note
When using BSON predicates with values, use valid JSON/BSON syntax: "1" for strings, 1 for numbers, {"foo":"bar"} for objects.
Other Custom Predicates
Predicate Description Example

in

Check if value is in array

in(value=${tenant}, array=@user.tenants)

gte

Numeric >= comparison

gte(@subscription.seats.over_limit_days, 5)

lte

Numeric ⇐ comparison

lte(@request.body.amount, 1000)

Caution
gte and lte are available since RESTHeart 9.8.0.

Use gte/lte rather than equals whenever you compare numbers: equals compares its operands as strings, so "10" sorts before "9". Both operands are parsed as numbers. An operand that is not numeric, such as an @-variable that did not resolve, makes the predicate false: a comparison that cannot be evaluated grants nothing.

Using Variables in Predicates

Predicates can reference dynamic values using special variables:

Telling an anonymous caller apart

A permission says who it is for with roles. A predicate sometimes needs the same information. Two cases:

  • one permission serves anonymous and signed-in callers together;

  • a plugin evaluates a predicate for a rule of its own, outside a permission, where no roles say who the rule is for.

A comparison on a property of the user cannot answer. equals(@user.termsAccepted, 'true') is false for a user who has not accepted the terms, and it is false for a caller with no account too: the variable does not resolve. The predicate treats the two in the same way, without any error.

@authenticated tells them apart. It is the string 'true' when the request carries an account and 'false' when it does not:

# only applies to callers who are signed in
equals(@authenticated, 'true')

# only applies to anonymous ones
equals(@authenticated, 'false')

For example, this permission lets everyone read the posts, and only signed-in callers read the drafts:

{
  "roles": ["$unauthenticated", "user"],
  "predicate": "method(GET) and path-prefix('/posts') and (equals(@authenticated, 'true') or not path-prefix('/posts/drafts'))"
}

@roles is the caller’s roles as an array, for deciding which signed-in callers a rule is about:

# only applies to staff
in(value='staff', array=@roles)

# only applies to callers who are neither staff nor admin
not in(value='staff', array=@roles) and not in(value='admin', array=@roles)
Warning

Do not test for anonymity through @roles. For a request with no account @roles is ["$unauthenticated"], the name mongoAclAuthorizer uses. The comparison cannot be written, because in a predicate $ marks an exchange attribute of Undertow:

# BROKEN: never matches, not even for an anonymous caller
in(value='$unauthenticated', array=@roles)

'$unauthenticated' in a value position is read as an attribute of that name. It resolves to nothing, and the comparison is false for everybody.

The negated form is the dangerous one. not in(value='$unauthenticated', array=@roles) is true for every request: a rule meant to skip anonymous callers applies to all of them, and no error says so.

Use equals(@authenticated, 'true').

Note
For an authenticated account with no roles, @roles is an empty array. An API key that names no roles is still a credential, and a rule written for guests must not apply to it. For the same reason @roles cannot replace @authenticated: an empty array does not say whether anyone is signed in.
Variable Description

@user

Properties of the authenticated account. Which properties exist depends on how the caller authenticated: see Identifying the caller below. With mongoRealmAuthenticator they are the user document’s (@user._id, @user.email, …​); with fileRealmAuthenticator, @user.userid and the roles; with a JWT, the token’s claims (@user.sub, plus anything in account-properties-claims).

@authenticated

'true' when the request carries an account, 'false' when it does not. Available from RESTHeart 9.8.

@roles

The caller’s roles, as an array. Use it for role names. It cannot test for anonymity: see Telling an anonymous caller apart. Available from RESTHeart 9.8.

@request

Request properties (e.g., @request.remoteIp)

@request.body

Request body content for fine-grained authorization (e.g., @request.body.amount, @request.body.items.0)

@qparams['key']

Query parameter value by key (e.g., @qparams['category'], @qparams['status'])

@rnd(bits)

Cryptographically secure random string (hexadecimal, e.g., @rnd(32) for 32-bit random value)

@mongoPermissions

Current MongoDB permissions object (e.g., @mongoPermissions.writeFilter)

@now

Current date and time

@filter

Value of the filter query parameter

@team

The caller’s active team, { _id, role }, as @team._id and @team.role: read from the membership provider, not from the token, so it is the same whatever token the caller holds. Registered by restheart-accounts, named after its team-claim-name. Available from RESTHeart 9.12.0.

${variable}

Path template variable (e.g., ${userid} from path /{userid})

Identifying the caller

@user carries whatever the authenticator put in the account, and the three shipped ones put in different things:

Authenticator Identity Also available

mongoRealmAuthenticator

@user._id

every property of the user document

fileRealmAuthenticator

@user.userid

the properties declared in the YAML

jwtAuthenticationMechanism, and any Bearer token issued by /token

@user.sub

the token’s other claims, plus whatever jwtTokenManager/account-properties-claims adds

Warning
A JWT account has no _id. A permission written as readFilter: {"owner": "@user._id"} therefore leaves the variable unresolved for every JWT caller. Since 9.8.2 the filter then matches no document. Before 9.8.2 it matched every document without an owner. Use @user.sub when callers authenticate with a token, or add _id to jwtTokenManager/account-properties-claims so it travels in the token (string ids only). A permission that must serve both kinds of caller can test either: equals(@user._id, …​) or equals(@user.sub, …​) in a predicate, and {"$or": [{"owner": "@user._id"}, {"owner": "@user.sub"}]} in a filter.
Tip
Ulabase Kit applications authenticate with a JWT: Basic only on POST /token, Bearer afterwards. Their ACLs identify the caller by @user.sub.

All of the above work in the same way in the predicate string and in the readFilter and mergeRequest properties of a permission.

Adding a custom variable: the VarResolver SPI

Caution
Since RESTHeart 9.7.0.

Each variable in the table above is a VarResolver, registered at startup. A plugin registers its own in the same way. The new @ variable, e.g. @subscription, then works wherever the built-in ones do: predicate strings, readFilter and mergeRequest.

public class SubscriptionVarResolver implements VarResolver {
    @Override
    public String name() {
        return "subscription"; // matches @subscription, @subscription.plan, ...
    }

    @Override
    public BsonValue resolve(Request<?> request, String var) {
        var account = request.getAuthenticatedAccount();
        if (!(account instanceof MongoRealmAccount mra)) {
            return null; // unresolved: see failure semantics below
        }

        var plan = lookUpPlan(mra.properties().getString("_id").getValue());

        // "var" is the full expression, e.g. "@subscription.plan": parse whatever
        // suffix your variable supports; here only the bare form is implemented.
        return "@subscription".equals(var) ? plan.asBson() : null;
    }
}

@RegisterPlugin(name = "subscriptionVarResolverRegistrar", description = "registers @subscription")
public class SubscriptionVarResolverRegistrar implements Initializer {
    @Inject("acl-vars-registry")
    private AclVarsRegistry vars;

    @Override
    public void init() {
        vars.register(new SubscriptionVarResolver());
    }
}

Then use it exactly like a built-in:

{
  "predicate": "path('/reports') and equals(@subscription.plan, 'enterprise')"
}

Registration. The built-in resolvers register first, at class-loading time. Registering a name already taken, e.g. user, fails at startup with a ConfigurationException.

Failure semantics. Returning null (or throwing) from resolve() is treated as "unresolved", and an unresolved variable never widens access:

  • in a predicate string the expression is replaced with an unguessable random token, so any comparison against it fails;

  • in a readFilter or writeFilter the same happens (since 9.8.2): the variable becomes a random value that matches no document, and a warning naming it is logged. The rest of the filter still applies, so {"$or": [{"owner": "@user._id"}, {"public": true}]} keeps returning the public documents;

  • in a mergeRequest an unresolved @user variable refuses the write with 403, rather than storing null.

Warning
Before 9.8.2 an unresolved variable became MongoDB null in a filter. {"owner": null} matches every document that has no owner, so the filter widened the read. The negation of an unresolved variable still matches, as in {"owner": {"$ne": "@user._id"}}: do not negate @ variables in filters.
Tip
restheart-stripe registers @subscription, to gate features by subscription plan and seat licence. Plan Gates & ACL has a working example and the mistakes to avoid.

The resolver contract:

  • No secrets in the returned value. The value of a registered variable also goes into readFilter, and from there into MongoDB queries.

  • Declare a resolver that returns filters. Since v9.17 a resolved value that carries MongoDB operators is not put in a query: see Variables in a filter are values. A resolver that returns filters overrides operatorsAllowed() and returns true, as the built-in @mongoPermissions and @filter do. The default is false.

  • Deterministic and request-scoped. resolve() must be a pure function of the request and of the authenticated identity. It takes no input from whoever writes the predicate.

  • The cache belongs to the resolver. RESTHeart calls a resolver once per request for each distinct full expression: @subscription.plan is computed once even if three permissions use it. A resolver that does one expensive lookup behind several sub-properties, such as @subscription.plan and @subscription.status, must cache that lookup itself. For a variable that is not deterministic, set cacheable() to false, as the built-in @rnd does: each occurrence must give an independent value.

Example: User Can Only Access Their Own Data
{
  "_id": "userCanAccessOwnProfile",
  "roles": ["user"],
  "predicate": "path-template('/{userid}') and equals(@user._id, ${userid})",
  "priority": 100
}

This permission: - Matches paths like /john123, /mary456 - Extracts the {userid} from the path - Only authorizes if ${userid} equals the authenticated user’s _id

Example: Request Body Predicates

Control authorization based on the content of the request body:

{
  "_id": "limitTransactionAmount",
  "roles": ["user"],
  "predicate": "path('/transactions') and method(POST) and less-than(@request.body.amount, 1000)",
  "priority": 100
}

This permission: - Allows users to create transactions via POST /transactions - Only authorizes transactions where the amount field is less than 1000 - Requests with amount >= 1000 are rejected with 403 Forbidden

Nested Properties:

{
  "_id": "requireCreditCardPayment",
  "roles": ["customer"],
  "predicate": "path('/orders') and method(POST) and equals(@request.body.payment.method, 'credit_card')",
  "priority": 100
}

Array Elements:

{
  "_id": "limitFirstItem",
  "roles": ["user"],
  "predicate": "path('/carts') and less-than(@request.body.items.0.quantity, 10)",
  "priority": 100
}
Note
A missing property, and a request whose body is not JSON/BSON, leave the variable unresolved. In a predicate the comparison then fails; in a readFilter or writeFilter the condition matches no document; in a mergeRequest the write is refused with 403. See the VarResolver failure semantics above.
Example: Query Parameter Access with @qparams

Authorize requests based on query parameter values:

{
  "_id": "userCanFilterOwnCategory",
  "roles": ["user"],
  "predicate": "path('/products') and method(GET) and equals(@qparams['category'], @user.category)",
  "priority": 100
}

This permission: - Allows users to query products via GET /products?category=electronics - Only authorizes if the category query parameter matches the user’s assigned category - Example: User with category: "electronics" can only query ?category=electronics

Example: Secure Random Strings with @rnd

Generate cryptographically secure random values for tokens, OTPs, and API keys:

User Registration with OTP:

{
  "_id": "userSignup",
  "roles": ["$unauthenticated"],
  "predicate": "path('/users') and method(POST)",
  "priority": 100,
  "mongo": {
    "mergeRequest": {
      "otp": "@rnd(32)",
      "verified": false,
      "role": "pending"
    }
  }
}

This permission: - Allows unauthenticated users to register via POST /users - Automatically generates a 32-bit random OTP (8 hexadecimal characters) - Sets initial user status as verified: false and role: "pending"

Account Verification:

{
  "_id": "verifyAccount",
  "roles": ["pending"],
  "predicate": "path-template('/users/{userid}/verify') and method(PATCH) and equals(@user._id, ${userid}) and equals(@user.otp, @qparams['otp'])",
  "priority": 100,
  "mongo": {
    "mergeRequest": {
      "verified": true,
      "role": "user"
    }
  }
}

This permission: - Allows pending users to verify their account via PATCH /users/{userid}/verify?otp=abc123def - Validates that the OTP in the query parameter matches the stored OTP - Upon success, escalates user to role: "user" and sets verified: true

Complete OTP Workflow:

  1. User registers: POST /users → System generates and stores OTP

  2. User receives OTP via email/SMS (handled by your application)

  3. User verifies: PATCH /users/{userid}/verify?otp={received-otp}

  4. System validates OTP from @qparams['otp'] against @user.otp

  5. On match: user is verified and granted full access

Other Use Cases for @rnd:

{
  "mongo": {
    "mergeRequest": {
      "apiKey": "@rnd(128)",          // 128-bit API key (32 hex chars)
      "resetToken": "@rnd(64)",        // Password reset token
      "sessionId": "@rnd(256)"         // Session identifier
    }
  }
}
Important
@rnd() uses java.security.SecureRandom for cryptographic security. The parameter specifies bits, resulting in bits/4 hexadecimal characters (e.g., @rnd(32) = 8 hex characters).

MongoDB-Specific Permissions

For requests handled by RESTHeart’s MongoDB REST API, you can specify additional fine-grained permissions using the mongo object.

MongoPermissions Structure

{
  "mongo": {
    "allowManagementRequests": false,
    "allowBulkPatch": false,
    "allowBulkDelete": false,
    "allowWriteMode": false,
    "allowFilter": false,
    "readFilter": {"status": "public"},
    "writeFilter": {"author": "@user._id"},
    "mergeRequest": {"author": "@user._id", "createdAt": "@now"},
    "projectResponse": {"password": 0, "secret": 0},
    "sort": {"name": 1}
  }
}

MongoPermissions Properties

Property Description

allowManagementRequests

Allows database/collection management operations (create/delete databases, collections, indexes, etc.). Default: false

allowBulkPatch

Allows bulk PATCH operations (updating multiple documents). Default: false

allowBulkDelete

Allows bulk DELETE operations (deleting multiple documents). Default: false

allowWriteMode

Allows using the ?wm=insert|update|upsert query parameter. Default: false

allowFilter

Allows a read to send its own query with filter, sort and sort_by. Default: the mongo option default-allow-filter, which is false. Since v9.16, see allowFilter

readFilter

Automatically adds filter conditions to all read operations

writeFilter

Limits write operations to documents matching the filter

mergeRequest

Automatically merges properties into write request bodies

projectResponse

Removes (or includes) specific fields from responses

sort

The order of the reads the permission authorizes. Since v9.16, see sort

readFilter, writeFilter and projectResponse apply to the requests a client shapes: a read, a query, a write. They do not apply to aggregations and, since v9.16, to change streams, which segregate the documents in their own stages. See Aggregations and permissions.

Important
Even if allowManagementRequests, allowBulkPatch, allowBulkDelete, allowWriteMode or allowFilter is set to true, the permission’s predicate must also resolve to true for the request to be authorized.
readFilter

The readFilter adds a filter condition to all read operations (GET requests) authorized by this permission. This is useful for data partitioning by role.

{
  "roles": ["user"],
  "predicate": "method(GET) and path-prefix('/posts')",
  "mongo": {
    "readFilter": {
      "$or": [
        {"status": "public"},
        {"author": "@user._id"}
      ]
    }
  }
}

Users with the user role can only see posts that are either public OR authored by themselves.

writeFilter

The writeFilter limits write operations (PATCH, PUT, DELETE) to documents matching the specified condition.

{
  "roles": ["user"],
  "predicate": "method(PATCH) and path-prefix('/posts')",
  "mongo": {
    "writeFilter": {"author": "@user._id"}
  }
}
Warning
writeFilter only restricts updates to existing documents. It cannot prevent creating documents that don’t match the filter. Use mergeRequest to enforce properties on creation.
Variables in a filter are values

A readFilter or a writeFilter is written by whoever writes the permission. A variable in it is a value, also when the value comes from the client: @request.body.<path> is the body the client sent, and @user.<property> can be a property the account is allowed to write.

Since v9.17:

  • a variable whose value carries a MongoDB operator, a key starting with $, matches no document, and a warning naming it is logged. The rest of the filter still applies, as with an unresolved variable;

  • under $expr, a variable whose value is a string starting with $ is bound as {"$literal": value}. MongoDB then reads it as a string. Outside $expr the string is already a value.

For example, with this permission:

"mongo": { "writeFilter": { "owner": "@request.body.owner" } }

a client that sends {"owner": {"$ne": null}} in the body matches no document. Before v9.17 the condition became {"owner": {"$ne": null}} and matched every document with an owner.

@mongoPermissions and @filter are the exceptions: their values are filters. @qparams['name'] is always a string. Predicates are not affected: there a value is quoted.

In an aggregation the same value refuses the request with 400.

mergeRequest

The mergeRequest automatically merges specified properties into the request body. This ensures certain fields are set server-side and cannot be overridden by clients.

{
  "roles": ["user"],
  "predicate": "method(POST) and path('/posts')",
  "mongo": {
    "mergeRequest": {
      "author": "@user._id",
      "status": "draft",
      "createdAt": "@now"
    }
  }
}

When a user creates a post, these properties are automatically added: - author is set to the user’s ID - status is set to "draft" - createdAt is set to the current timestamp

Tip
Use mergeRequest together with writeFilter to ensure data integrity. Set required fields on creation, then restrict updates using the filter.
projectResponse

The projectResponse removes (or includes) specific fields from API responses. This is useful for hiding sensitive data.

Negative projection (hide specific fields):

{
  "roles": ["user"],
  "predicate": "path-prefix('/users')",
  "mongo": {
    "projectResponse": {"password": 0, "secret": 0, "internal.data": 0}
  }
}

Positive projection (only show specific fields):

{
  "roles": ["public"],
  "predicate": "path-prefix('/users')",
  "mongo": {
    "projectResponse": {"name": 1, "email": 1, "avatar": 1}
  }
}
Note
You can use dot notation to hide nested properties: "internal.secret": 0
Important
projectResponse hides a field from the response. A client that may send filter or sort can still put a condition on the field, or sort by it, and learn its value over several requests. Leave allowFilter off for the roles that must not see the field. RESTHeart itself refuses a filter or a sort on the password and on the one-time tokens of the accounts: see Security Hardening.
allowFilter

Since v9.16, allowFilter decides whether a read may send its own query. A permission that does not allow it does not match a GET with the filter, sort or sort_by query parameter. The request gets 403 when no other permission of the caller allows it. This applies to _size too.

The reason is projectResponse. A permission can hide a field from the response. A filter written by the client can still test that field: a condition on it tells which documents match, and a sort on it tells the order of its values. With allowFilter off on every permission of the caller, a hidden field stays hidden: see A caller with several permissions on the same read.

The application queries through aggregations. Whoever writes the permissions declares the aggregation on the collection, and the client sends only the values of its variables.

A read without a query of its own works as before. It returns the documents the readFilter allows, paged with page and pagesize, and _size counts them.

To let a role send its own queries, set allowFilter in its permission:

{
  "roles": ["admin"],
  "predicate": "method(GET) and path-prefix('/orders')",
  "mongo": {
    "allowFilter": true
  }
}

A permission that does not set allowFilter takes the value of the mongo option default-allow-filter, which is false:

mongo:
  # true keeps the behaviour of the versions before v9.16
  default-allow-filter: false

The client gets 403 with the message filter, sort and sort_by are not allowed. The log of RESTHeart says, at INFO, the method and path of the request and what would allow it. In the MCP catalog, the query and size actions do not show the filter parameter to a caller whose permissions do not allow it.

allowFilter does not apply to:

  • writes: a bulk PATCH or DELETE needs a filter, and allowBulkPatch and allowBulkDelete decide about it. The filter of a bulk write tells, with the number of documents it matches, what the filter of a read tells: grant bulk writes only on collections without hidden fields;

  • the root role, and the requests a plugin allows through the ACLRegistry: they do not go through the permissions;

  • aggregations, which do not read filter or sort.

A caller with several permissions on the same read

allowFilter is part of what makes a permission match, like its predicate. A read with filter, sort or sort_by is served by the permission with the highest priority among those that allow it as sent. A permission with a higher priority that does not allow these parameters takes no part.

Take a user with the roles contractor and analyst, and these two permissions:

[
  {
    "_id": "contractorsReadPublic",
    "roles": ["contractor"],
    "predicate": "path('/reports') and method(GET)",
    "priority": 200,
    "mongo": {
      "readFilter": {"classification": "public"},
      "projectResponse": {"salary": 0}
    }
  },
  {
    "_id": "analystsQueryInternal",
    "roles": ["analyst"],
    "predicate": "path('/reports') and method(GET)",
    "priority": 100,
    "mongo": {
      "readFilter": {"classification": "internal"},
      "allowFilter": true
    }
  }
]
  • GET /reports matches both, and contractorsReadPublic serves it: public documents, without salary.

  • GET /reports?sort=_id matches analystsQueryInternal only, which serves it: internal documents, with salary.

The user is an analyst, and the second request is one the analysts' permission allows. A user with the single role contractor gets 403 on it.

Warning
projectResponse and readFilter restrict the requests their own permission serves. A field stays hidden from a caller, and a document out of reach, only when no permission of the caller’s roles allows filter on the same reads without the same restrictions. When you set allowFilter on a permission, check the other permissions of the users who hold its role.
sort

Since v9.16, sort sets the order of the reads a permission authorizes. The server applies it to a GET on a collection, the way readFilter adds its condition:

{
  "roles": ["$unauthenticated"],
  "predicate": "path('/products') and method(GET)",
  "mongo": {
    "readFilter": { "published": true },
    "sort": { "name": 1 }
  }
}

The order applies when the client sends no sort of its own. With allowFilter off the client cannot send one, so the permission’s order is the only one.

When the order does not name _id, the server appends _id. A page is then the same page every time.

Sorting on a field that projectResponse hides tells the order of its values: it is a choice of whoever writes the permission. Without an index on the sort fields, a large collection can exceed the memory MongoDB allows for a sort.

The alternatives a permission declares

Since v9.16 a permission can offer the client a few alternatives, which it picks by name or by value. The client never writes a query or names a field. Two forms do it, the same as in aggregations, and they work in sort, readFilter and writeFilter.

{"$ifvar": [variable, then, else]} applies then when the variable is bound for the request, and the optional else when it is not. In sort it picks one of the orders the permission names:

"sort": {
  "$ifvar": ["@qparams['order']",
    { "by-name": { "name": 1 }, "newest": { "createdAt": -1 } },
    { "createdAt": -1 }
  ]
}

With ?order=by-name the read is sorted by name. Without order it uses the third element. A name the permission does not declare gets 400.

In readFilter it adds an optional condition. The mandatory part stays outside the $ifvar, so the client can only narrow what the permission allows:

"readFilter": {
  "$and": [
    { "published": true },
    { "$ifvar": ["@qparams['category']", { "category": "@qparams['category']" }] }
  ]
}

With ?category=desk the read is limited to that category. Without it the element is removed, and only { "published": true } applies.

{"$var": [variable, default]} is the value of the variable, or the default when it is not bound:

"sort": { "createdAt": { "$var": ["@qparams['dir']", -1] } }

With no dir the read is newest first. In sort a direction must be 1 or -1, otherwise the request gets 400.

A variable is written in one of two ways:

  • "@qparams['dir']", an ACL variable: the value of ?dir= as a string, exactly as the client wrote it;

  • "dir", a plain name, as in aggregations: the value of ?dir= read as JSON, so ?dir=1 is the number 1. A value that carries an operator, a key starting with $, gets 400.

Either way an operator never reaches the query: ?category={"$ne":null} is the string itself with @qparams, and a 400 with a plain name.

A permission whose mongo block is not valid is refused when it is written to the ACL, with 400 and the reason. One already stored allows nothing: the request gets 403, and the log says, at WARN, which permission and why. The 403 comes also when a permission with a lower priority would allow the request.

Permission Priority

A request is authorized when at least one permission allows it and no vetoer refuses it. A permission allows a request when its predicate resolves to true and its mongo switches (allowFilter, allowBulkPatch, allowBulkDelete, allowWriteMode, allowManagementRequests) admit it.

Priority decides which permission serves the request when more than one allows it: the one with the highest number, with its mongo options. A permission without priority comes last.

[
  {
    "_id": "adminFullAccess",
    "roles": ["admin"],
    "predicate": "path-prefix('/')",
    "priority": 0,
    "mongo": {
      "allowManagementRequests": true,
      "allowBulkPatch": true,
      "allowBulkDelete": true,
      "allowWriteMode": true
    }
  },
  {
    "_id": "userLimitedAccess",
    "roles": ["user"],
    "predicate": "path-prefix('/')",
    "priority": 100,
    "mongo": {
      "readFilter": {"author": "@user._id"}
    }
  }
]

In this example: - userLimitedAccess (priority 100) is evaluated before adminFullAccess (priority 0) - A user with both roles who reads a collection is served by userLimitedAccess, with its readFilter - The same user sending a bulk PATCH is served by adminFullAccess: userLimitedAccess does not set allowBulkPatch, so it does not allow that request

Important
A permission with a higher priority does not stop one with a lower priority from serving a request the first does not allow. To keep a request from being served, make sure that no permission of the caller’s roles allows it, or refuse it with a vetoer.

A user with more than one role

The permissions of all the user’s roles are compared together: among those that match the request, the one with the highest priority applies, with its mongo options. The order in which the account lists its roles plays no part.

[
  {
    "_id": "editorsWriteAll",
    "roles": ["editor"],
    "predicate": "path-prefix('/articles') and method(PATCH)",
    "priority": 200,
    "mongo": { "allowWriteMode": true }
  },
  {
    "_id": "authorsWriteOwn",
    "roles": ["author"],
    "predicate": "path-prefix('/articles') and method(PATCH)",
    "priority": 100,
    "mongo": { "writeFilter": { "author": "@user._id" } }
  }
]

A user with roles [author, editor] patching an article gets editorsWriteAll (200 beats 100), so no writeFilter: they can edit any article. A user with the single role author gets authorsWriteOwn, and edits their own articles only. The same holds with roles [editor, author].

Now suppose the two permissions had the same priority, 100 both. The user with roles [author, editor] matches both, and the tie-break decides (see Permissions with the same priority):

  • with mongoAclAuthorizer the greatest _id wins: "editorsWriteAll" sorts after "authorsWriteOwn", so the user gets editorsWriteAll and can edit any article;

  • with fileAclAuthorizer the permission written first in the configuration wins: in the order above, again editorsWriteAll; swap the two entries in the file and the user gets authorsWriteOwn.

In both cases the order of the roles, [author, editor] or [editor, author], does not change the outcome. What does change it, the _id or the position in a file, is not something to choose an outcome by: give the permission that must win the higher priority.

Caution
Before 9.12.0 the first role of the account decided: with [author, editor] the request got authorsWriteOwn, with [editor, author] it got editorsWriteAll. Accounts with more than one role whose permissions match the same request may see a different permission applied after the upgrade, and with it different mongo options: review those rules.

Permissions with the same priority

Two permissions that match the same request with the same priority are resolved by a fixed rule, the same within a role and across roles, never by the order of the user’s roles:

  • mongoAclAuthorizer: the permission with the greatest _id wins. With ObjectIds, that is the most recently created one.

  • fileAclAuthorizer: the permission that comes first in the configuration wins.

For example, in an acl.yml with these two permissions for the role user:

- roles: [ user ]
  predicate: method(GET) and path-prefix('/articles')
  priority: 100
  mongo:
    projectResponse: { "draftNotes": 0 }

- roles: [ user ]
  predicate: method(GET) and path-template('/articles/{id}')
  priority: 100

GET /articles/abc matches both, and the first one applies: the response hides draftNotes. To let a single article show them, give the second permission a higher priority, for instance 110.

Tip
Do not rely on the tie-break. Two permissions that can match the same request should have different priorities: the one meant as the exception gets the higher number.
Caution
Before 9.12.0 fileAclAuthorizer resolved a tie in favour of the permission that came last in the file, and across roles a tie went to the role the account listed first. A configuration that relied on either may apply a different permission after the upgrade.

Complete Permission Examples

Example 1: User Can Read Own Documents

{
  "_id": "userCanGetOwnCollection",
  "description": "Users can read their own collection with pagination",
  "roles": ["user"],
  "predicate": "method(GET) and path-template('/{userid}') and equals(@user._id, ${userid}) and qparams-contain(page) and qparams-blacklist(filter, sort)",
  "priority": 100,
  "mongo": {
    "readFilter": {
      "$or": [
        {"status": "public"},
        {"author": "@user._id"}
      ]
    },
    "projectResponse": {"log": 0}
  }
}

This permission: - Allows users to GET their own collection (e.g., /john123) - Requires the page query parameter - Blocks filter and sort query parameters - Only returns documents that are public OR authored by the user - Hides the log field from responses

Example 2: User Can Create Documents in Own Collection

{
  "_id": "userCanCreateDocumentsInOwnCollection",
  "description": "Users can create documents in their collection",
  "roles": ["user"],
  "predicate": "method(POST) and path-template('/{userid}') and equals(@user._id, ${userid})",
  "priority": 100,
  "mongo": {
    "mergeRequest": {
      "author": "@user._id",
      "status": "draft",
      "createdAt": "@now"
    }
  }
}

This permission: - Allows users to POST to their own collection - Automatically sets author, status, and createdAt fields - Prevents users from setting these fields to arbitrary values

Example 3: User Can Update Own Documents

{
  "_id": "userCanUpdateOwnDocuments",
  "description": "Users can update their own documents",
  "roles": ["user"],
  "predicate": "method(PATCH) and path-template('/{userid}/*') and equals(@user._id, ${userid})",
  "priority": 100,
  "mongo": {
    "writeFilter": {"author": "@user._id"},
    "mergeRequest": {
      "modifiedAt": "@now",
      "modifiedBy": "@user._id"
    }
  }
}

This permission: - Allows users to PATCH documents in their collection - Only allows updating documents where author matches the user’s ID - Automatically sets modifiedAt and modifiedBy on updates

Example 4: Admin Full Access

{
  "_id": "adminCanDoEverything",
  "description": ["Admin role can do everything"],
  "roles": ["admin"],
  "predicate": "path-prefix('/')",
  "priority": 0,
  "mongo": {
    "allowManagementRequests": true,
    "allowBulkPatch": true,
    "allowBulkDelete": true,
    "allowWriteMode": true
  }
}

Example 5: Public Read-Only Access

{
  "_id": "publicCanReadProducts",
  "description": "Unauthenticated users can read public products",
  "roles": ["$unauthenticated"],
  "predicate": "method(GET) and path('/products')",
  "priority": 100,
  "mongo": {
    "readFilter": {"published": true, "visibility": "public"},
    "projectResponse": {"internalNotes": 0, "cost": 0}
  }
}

Example 6: JWT-based Multi-tenant Access

- _id: jwtTenantAccess
  roles: [ jwt-user ]
  predicate: >
    path-template('/{tenant}/data')
    and in(value=${tenant}, array=@user.tenants)
  priority: 100
  mongo:
    readFilter: >
      {"tenantId": "${tenant}"}
    mergeRequest: >
      {"tenantId": "${tenant}", "userId": "@user.sub"}

This permission (YAML format): - Extracts {tenant} from path like /acme/data - Checks if user’s JWT contains tenant in their tenants array - Filters data by tenantId - Automatically adds tenantId and userId to write requests

Managing Permissions

With mongoAclAuthorizer (MongoDB Storage)

List All Permissions
cURL
curl -i -X GET [RESTHEART-URL]/acl \
  -H "Authorization: Basic [BASIC-AUTH]"
HTTPie
http GET [RESTHEART-URL]/acl \
  Authorization:"Basic [BASIC-AUTH]"
JavaScript
const credentials = btoa(`${username}:${password}`);

fetch('[RESTHEART-URL]/acl', {
  method: 'GET',
  headers: { 'Authorization': `Basic ${credentials}` }
})
.then(response => response.json())
.then(data => console.log('Permissions:', data));
Create a Permission
cURL
curl -i -X POST [RESTHEART-URL]/acl \
  -H "Authorization: Basic [BASIC-AUTH]" \
  -H "Content-Type: application/json" \
  -d '{
    "_id": "userCanReadInventory",
    "roles": ["user"],
    "predicate": "method(GET) and path-prefix(\"/inventory\")",
    "priority": 100
  }'
HTTPie
http POST [RESTHEART-URL]/acl \
  Authorization:"Basic [BASIC-AUTH]" \
  Content-Type:application/json \
  _id="userCanReadInventory" \
  roles:='["user"]' \
  predicate="method(GET) and path-prefix(\"/inventory\")" \
  priority:=100
JavaScript
const credentials = btoa(`${username}:${password}`);

fetch('[RESTHEART-URL]/acl', {
  method: 'POST',
  headers: {
    'Authorization': `Basic ${credentials}`,
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    "_id": "userCanReadInventory",
    "roles": ["user"],
    "predicate": "method(GET) and path-prefix(\"/inventory\")",
    "priority": 100
  })
})
.then(response => {
  if (response.ok) console.log('Permission created');
});
Update a Permission
cURL
curl -i -X PATCH [RESTHEART-URL]/acl/userCanReadInventory \
  -H "Authorization: Basic [BASIC-AUTH]" \
  -H "Content-Type: application/json" \
  -d '{
    "priority": 200
  }'
HTTPie
http PATCH [RESTHEART-URL]/acl/userCanReadInventory \
  Authorization:"Basic [BASIC-AUTH]" \
  Content-Type:application/json \
  priority:=200
Delete a Permission
cURL
curl -i -X DELETE [RESTHEART-URL]/acl/userCanReadInventory \
  -H "Authorization: Basic [BASIC-AUTH]"
HTTPie
http DELETE [RESTHEART-URL]/acl/userCanReadInventory \
  Authorization:"Basic [BASIC-AUTH]"

With fileAclAuthorizer (Configuration File)

You can configure ACL permissions in two ways with fileAclAuthorizer:

Option 1: Inline Permissions (in main configuration file)

Define permissions directly in your main RESTHeart configuration file:

fileAclAuthorizer:
  permissions:
    - _id: adminFullAccess
      roles: [ admin ]
      predicate: path-prefix('/')
      priority: 0
      mongo:
        allowManagementRequests: true
        allowBulkPatch: true
        allowBulkDelete: true

    - _id: userCanReadInventory
      roles: [ user ]
      predicate: method(GET) and path-prefix('/inventory')
      priority: 100

    - _id: userCanCreateOwnData
      roles: [ user ]
      predicate: >
        method(POST)
        and path-template('/{userid}')
        and equals(@user._id, ${userid})
      priority: 100
      mongo:
        mergeRequest: >
          {"author": "@user._id", "createdAt": "@now"}
Option 2: Separate ACL Configuration File

Define permissions in a separate configuration file:

fileAclAuthorizer:
  conf-file: ./acl.yml

Then create acl.yml:

- _id: adminFullAccess
  roles: [ admin ]
  predicate: path-prefix('/')
  priority: 0
  mongo:
    allowManagementRequests: true
    allowBulkPatch: true
    allowBulkDelete: true

- _id: userCanReadInventory
  roles: [ user ]
  predicate: method(GET) and path-prefix('/inventory')
  priority: 100

- _id: userCanCreateOwnData
  roles: [ user ]
  predicate: >
    method(POST)
    and path-template('/{userid}')
    and equals(@user._id, ${userid})
  priority: 100
  mongo:
    mergeRequest: >
      {"author": "@user._id", "createdAt": "@now"}

After editing the configuration, restart RESTHeart to apply changes.

Configuration

mongoAclAuthorizer Configuration

mongoAclAuthorizer:
  acl-db: restheart
  acl-collection: acl
  # Users with root-role bypass all ACL checks
  root-role: admin
  cache-enabled: true
  cache-size: 1000
  cache-ttl: 5000
  cache-expire-policy: AFTER_WRITE

fileAclAuthorizer Configuration

fileAclAuthorizer:
  # Path to ACL configuration file (absolute or relative to restheart config)
  conf-file: ./acl.yml
  # Or define permissions inline:
  permissions:
    - role: admin
      predicate: path-prefix('/')
      priority: 0

Best Practices

1. Use Descriptive IDs and Descriptions

{
  "_id": "userCanReadOwnPosts",
  "description": "Users with 'user' role can read posts they authored or public posts",
  ...
}

2. Leverage Priority for Exception Handling

Use high priority for specific rules, low priority for general rules:

[
  {
    "_id": "blockSensitiveEndpoint",
    "roles": ["user"],
    "predicate": "path('/admin/secrets')",
    "priority": 1000,
    "mongo": null
  },
  {
    "_id": "allowGeneralAccess",
    "roles": ["user"],
    "predicate": "path-prefix('/admin')",
    "priority": 100
  }
]

3. Combine writeFilter and mergeRequest

Always use both together to ensure data integrity:

{
  "mongo": {
    "writeFilter": {"author": "@user._id"},
    "mergeRequest": {"author": "@user._id"}
  }
}

4. Test Permissions Thoroughly

Start with restrictive permissions and gradually add more access. Test with different user roles and edge cases.

5. Use projectResponse to Hide Sensitive Data

{
  "mongo": {
    "projectResponse": {
      "password": 0,
      "ssn": 0,
      "creditCard": 0
    }
  }
}

6. Whitelist Instead of Blacklist When Possible

Prefer bson-request-whitelist and qparams-whitelist over blacklists for better security:

bson-request-whitelist(name, email, age)  // Only these fields allowed

7. Use Path Templates for User-Scoped Resources

path-template('/{userid}/documents') and equals(@user._id, ${userid})

8. Document Your Permission Strategy

Maintain a clear permission hierarchy and document the roles and their intended access levels.

Common Patterns

Pattern 1: User-Owned Resources

{
  "_id": "userCRUDOwnResources",
  "roles": ["user"],
  "predicate": "path-template('/{userid}/*') and equals(@user._id, ${userid})",
  "priority": 100,
  "mongo": {
    "writeFilter": {"author": "@user._id"},
    "readFilter": {"author": "@user._id"},
    "mergeRequest": {"author": "@user._id"}
  }
}

Pattern 2: Public Read, Authenticated Write

[
  {
    "_id": "publicCanRead",
    "roles": ["$unauthenticated"],
    "predicate": "method(GET) and path-prefix('/posts')",
    "priority": 100,
    "mongo": {
      "readFilter": {"status": "published"}
    }
  },
  {
    "_id": "userCanWrite",
    "roles": ["user"],
    "predicate": "(method(POST) or method(PATCH)) and path-prefix('/posts')",
    "priority": 100,
    "mongo": {
      "mergeRequest": {"author": "@user._id"}
    }
  }
]

Pattern 3: Multi-Tenant with JWT

- _id: tenantDataAccess
  roles: [ tenant-user ]
  predicate: >
    path-template('/{tenantId}/data')
    and in(value=${tenantId}, array=@user.tenants)
  priority: 100
  mongo:
    readFilter: >
      {"tenantId": "${tenantId}"}
    writeFilter: >
      {"tenantId": "${tenantId}"}
    mergeRequest: >
      {"tenantId": "${tenantId}"}

Pattern 4: Time-Based Access

{
  "_id": "timeLimitedAccess",
  "roles": ["premium"],
  "predicate": "path-prefix('/premium-content')",
  "priority": 100,
  "mongo": {
    "readFilter": {
      "$or": [
        {"expiresAt": {"$gt": "@now"}},
        {"expiresAt": {"$exists": false}}
      ]
    }
  }
}

Troubleshooting

Permission Not Applied

  1. Check if the predicate matches your request

  2. Verify the user has the specified roles

  3. Check if a higher priority permission is overriding it

  4. Ensure the collection/file is correctly configured in the authorizer settings

writeFilter Not Preventing Creation

writeFilter only restricts updates to existing documents. Use mergeRequest to enforce fields on creation and bson-request-whitelist to limit allowed fields.

Variables Not Resolving

Ensure you’re using the correct syntax: - @user._id for user properties - ${variable} for path template variables - Quotes around strings: value='"draft"'