Skip to content

Access Rules ​

Since 2.10, a declared collection can control who reads, creates, updates and deletes which documents, and who reads or writes which fields. These rules sit on top of what already exists:

  • The grants of the roles (read, write, administrate per collection) still apply first. A rule only narrows what a grant allows; it never widens it.
  • The owner behaviour keeps working unchanged. When both are declared, both apply.
  • Collections without access or fields behave exactly as before.

Collection rules ​

ts
// server/mongocamp/articles.ts
export default defineMongocampCollection({
  name: 'articles',
  schema,
  timestamps: { createdBy: 'author' },
  access: {
    read: ({ user }) => ({ $or: [{ published: true }, { author: user.userId }] }), // a filter
    create: ['editor'], // roles
    update: ({ user }) => ({ author: user.userId }), // only the author
    delete: false, // nobody; administrators bypass the rules
  },
})

A rule takes one of these forms:

RuleMeaning
true or no ruleEverybody with the grant.
falseNobody (403).
['editor', 'hr']Users with at least one of these roles; everybody else gets 403.
({ user, isAdmin, collectionName, operation, document }) => …A function that answers true, false or a filter. It may be async.

Each rule applies as follows:

  • read: a filter is combined with every read: list, find, search, count, get, export, aggregation, distinct, live updates, views and expand. A document outside the filter is answered like a missing one (404), so nobody learns which ids exist. If a reference points into a collection the user may not read, expand sets it to null; the rest of the read goes on.
  • create: checked for every inserted document (insert, insertMany, import, batch). The function gets the document and must answer a boolean.
  • update: a filter narrows the target of replace, partial update and updateMany, and of restore for soft-deleted documents. A document outside the filter gets 404; updateMany changes only the matching documents.
  • delete: like update, for deletes (also soft deletes).

Administrators are not checked unless adminBypass: false is set. Refusals answer 403 with code 4033 (accessDenied).

Field rules ​

ts
defineMongocampCollection({
  name: 'staff',
  schema,
  fields: {
    'salary': { read: ['hr'], write: ['hr'] },
    'address.street': { read: ['hr'] },
    'status': { write: ['hr'] },
  },
})

read hides a field from every answer for callers who fail the rule. This covers reads, expand, export (also the csv columns), aggregation and views (the field is removed before the first stage), live updates, and the stored document of a 409 version conflict.

To stop values being guessed by probing, the following are refused with 403 (code 4033):

  • a filter, sort or projection that uses a hidden field, also through an expression: '$salary', '$$ROOT' or '$$ROOT.salary', $getField (3.0: a computed field name counts as every field);
  • a filter of updateMany / deleteMany on a hidden field (3.0);
  • distinct on a hidden field, and distinct on anything but a field path (3.0: distinct/$ROOT answers 400);
  • q when a field of search is hidden for the caller (3.0).

The history of a document (…/history) answers before and after without the hidden fields (3.0).

Aggregations that read other collections (3.0) ​

$lookup and $unionWith read their collection with the rules of that collection for the caller: its read scope (owner, tenant, access rules, soft delete, drafts) comes first in the stage's pipeline, its hidden fields and the secrets of the users collection are removed. $graphLookup into a collection with a scope or hidden fields answers 403 (it cannot take a pipeline).

Whole-collection routes (3.0) ​

copy and clear of a collection work on every document. For a collection where the caller sees or writes only a part (a scope, hidden fields, owner, tenant, access, softDelete, drafts), they need the administrate grant. Restoring a deleted document from its history (…/history/{auditId}/restore) needs the snapshot to be in the caller's scope, else it answers 404.

write refuses inserts and updates that set the field (403, with the fields in issues).

A replace that leaves out a hidden or unwritable field keeps the stored value, so a document read without the field can be sent back as it is. A replace that changes an unwritable value is refused.

protectedFields keeps its 2.x behaviour: the field is silently removed from writes.

Multi-tenancy ​

The tenant behaviour works like owner, with an organisation instead of a user:

ts
defineMongocampCollection({
  name: 'projects',
  schema,
  tenant: { field: 'orgId', of: ({ user }) => organisationOf(user.userId) },
})

How it works:

  • An insert gets the caller's tenant. A tenant sent by the client is ignored, because the field is a system field.
  • Every read and every write sees the caller's tenant only. Other tenants' documents answer 404.
  • A user without a tenant (of answers null) gets 403.
  • The tenant field gets an index.
  • Administrators see every tenant (adminBypass, default true).

In the declaration answer ​

GET …/collections/{name}/declaration shows each rule as a kind (all, none, roles, custom) and shows the tenant behaviour. The functions stay on the server.

Released under the MIT License.