@cerbos/orm-mongoose

中文文档
3.0.0发布于 2026/08/04Apache-2.0TypeScriptCommonJS构建来源已验证近 30 天下载 3266

An adapter library that takes a Cerbos Query Plan (PlanResources API) response and converts it into a Mongoose filter. It is desi

原始使用文档
文档目录11 节
  1. How it works
  2. Supported operators
  3. Conformance contract
  4. Requirements
  5. System Requirements
  6. Installation
  7. API
  8. Mapper configuration
  9. Usage example
  10. Error handling
  11. Limitations

Cerbos + Mongoose ORM Adapter

An adapter library that takes a Cerbos Query Plan (PlanResources API) response and converts it into a Mongoose filter. It is designed to run alongside a project that is already using the Cerbos JavaScript SDK to fetch query plans so that authorization logic can be pushed down to MongoDB.

How it works

  1. Use a Cerbos client (@cerbos/http or @cerbos/grpc) to call planResources and obtain a PlanResourcesResponse.
  2. Provide queryPlanToMongoose with that plan and an optional mapper that describes how Cerbos attribute paths relate to your document schema.
  3. The adapter walks the Cerbos expression tree, translates supported operators to MongoDB syntax, and returns { kind, filters? }.
  4. Inspect result.kind:
    • ALWAYS_ALLOWED: the caller can query without any additional filters.
    • ALWAYS_DENIED: short-circuit and return an empty result set.
    • CONDITIONAL: execute the query with result.filters.

You can merge the adapter output with existing application filters (for example, via $and) before issuing the Mongoose query.

Supported operators

CategoryOperatorsBehavior
Logicaland, or, notBuilds $and, $or, and $nor groups.
Comparisonseq, ne, lt, le, gt, geEmits $eq, $ne, $lt, $lte, $gt, $gte checks against the mapped field.
Membershipin, hasIntersection$in on simple lists, or $elemMatch when targeting array relations; hasIntersection supports either a direct array field or a map projection inside the plan.
String helperscontains, startsWith, endsWithGenerates escaped regular expressions that target substrings, prefixes, or suffixes.
Existence helpersisSet, existsUses $exists/$ne: null for scalars and $elemMatch for collections.
Collection helpersfilter, lambda, map, allTranslates Cerbos collection expressions into scoped $elemMatch filters and maps lambda variables to the correct nested paths. all requires the stored field to be an array.
Arithmetic and valuesadd, sub, mult, div, mod, if, size, index, get-fieldUses document-level MongoDB $expr expressions. Division requires a non-zero constant denominator; indexing requires a non-negative integer constant and adds a per-document bounds check.
Conversions and matchingstring, double, int, timestamp, matchesUses guarded MongoDB conversion and regular-expression expressions. Timestamps accept BSON dates or millisecond-exact RFC 3339 strings in the CEL instant range. Regex matching accepts a validated common RE2/PCRE2 subset.
Hierarchieshierarchy, ancestorOf, descendentOf, overlapsTranslates a mapped scalar hierarchy path using literal prefix and ancestor-list filters.

Any operator not listed above causes queryPlanToMongoose to throw Unsupported operator: <name>.

exists_one fails loudly because a normal match filter cannot preserve exact-match cardinality and CEL error semantics for nullable elements.

Conversions fail closed when the stored BSON type is outside CEL's compatible source types or when parsing fails. double and int accept strings and numeric BSON values, but not booleans; int also rejects BSON dates rather than interpreting them as milliseconds. string accepts strings, booleans, and numeric BSON values. A failed conversion remains denied under negation.

Timestamp values must fall in CEL's UTC instant range (0001-01-01T00:00:00Z through 9999-12-31T23:59:59.999Z). Strings must use RFC 3339 syntax with no more than three fractional-second digits, matching BSON Date's millisecond precision. Higher-precision or out-of-range strings and BSON dates fail closed instead of being silently truncated into a different CEL instant.

matches supports literals, ., the *, +, and ? quantifiers, leading ^, terminal $, and escaped regex metacharacters. Other constructs fail closed. A terminal $ is translated to PCRE2's absolute end-of-text anchor so MongoDB cannot match before a final newline, preserving RE2 semantics.

Conformance contract

The adapter is differentially tested against Cerbos PDP 0.54.0 checkResource decisions using 20 hostile seed documents and real MongoDB 7 and 8 queries. The Spring Data adapter defines the reference semantics for this compatibility snapshot.

ClassificationCoverage
Oracle-tested85 reference conformance actions plus regex, ordered indexing/get-field, and timestamp probes (88 actions)
Fail-closed29 reference actions
Known planner divergencehas() on a missing attribute is folded by the Cerbos planner to ALWAYS_ALLOWED, while checkResource denies the missing-attribute documents. Until the planner is fixed, use R.attr.x != null for database-backed attributes instead of has(R.attr.x)

The fail-closed set covers exact-one cardinality, aggregation expressions or outer-document references inside $elemMatch, nested collection counts, correlated variable-in-variable membership, unsafe division/non-finite arithmetic, and negated nullable collection predicates that cannot preserve CEL's three-valued error semantics. These plans throw instead of silently degrading to a weaker MongoDB filter.

Requirements

  • Cerbos > v0.16 plus either the @cerbos/http or @cerbos/grpc client

System Requirements

  • Node.js >= 22.0.0
  • Mongoose 9.x
  • MongoDB 7.0 or newer

Installation

npm install @cerbos/orm-mongoose

API

import {
  queryPlanToMongoose,
  PlanKind,
  type Mapper,
} from "@cerbos/orm-mongoose";

const result = queryPlanToMongoose({
  queryPlan, // PlanResourcesResponse from Cerbos
  mapper, // optional Mapper - see below
});

if (result.kind === PlanKind.CONDITIONAL) {
  await MyModel.find(result.filters);
}

PlanKind is re-exported from @cerbos/core:

export enum PlanKind {
  ALWAYS_ALLOWED = "KIND_ALWAYS_ALLOWED",
  ALWAYS_DENIED = "KIND_ALWAYS_DENIED",
  CONDITIONAL = "KIND_CONDITIONAL",
}

Mapper configuration

The Cerbos query plan references fields using paths such as request.resource.attr.title. Use a mapper to translate those names to the paths in your Mongoose models and to describe relations/collections so the adapter can generate $elemMatch filters when needed.

export type MapperConfig = {
  field?: string;
  nullable?: boolean;
  valueParser?: (value: any) => any;
  relation?: {
    name: string;
    type: "one" | "many";
    field?: string;
    fields?: Record<string, MapperConfig>;
  };
};

export type Mapper =
  | Record<string, MapperConfig>
  | ((key: string) => MapperConfig);
  • field rewrites a single Cerbos path to a different field in MongoDB.
  • nullable declares that a stored null represents a missing Cerbos attribute. Comparisons add a non-null guard so MongoDB does not turn a CEL evaluation error into an authorized match. Do not set it for fields where null is an explicit Cerbos value.
  • valueParser transforms leaf values during filter construction. This is useful when the Cerbos plan contains string representations that need to be converted to MongoDB-specific types (for example, converting a string to an ObjectId). The parser is applied to each value in eq, ne, lt, le, gt, ge, and in operators. It also works on nested relation fields via the fields map.
  • relation describes embedded documents (type: "one") or arrays (type: "many"). When field is provided on a relation it identifies the property inside that relation that should be used for comparisons (for example, matching createdBy.id without an $elemMatch).
  • fields supplies nested overrides so lambda expressions such as tag.name can be mapped to the correct property.

If you omit the mapper the adapter will use the query plan paths verbatim, which only works when your Mongo documents follow the Cerbos naming convention.

Direct fields

const mapper: Mapper = {
  "request.resource.attr.aBool": { field: "aBool" },
  "request.resource.attr.aString": { field: "title" },
  "request.principal.attr.department": { field: "principalDepartment" },
};

Relations and collections

Use relation when mapping nested objects or arrays. type: "one" maps to embedded/single relations and results in dotted field paths, while type: "many" maps to arrays and lets the adapter emit $elemMatch conditions. The optional fields map lets you rename nested properties referenced in lambda expressions.

const mapper: Mapper = {
  "request.resource.attr.createdBy": {
    relation: {
      name: "createdBy",
      type: "one",
      field: "id",
    },
  },
  "request.resource.attr.tags": {
    relation: {
      name: "tags",
      type: "many",
      fields: {
        id: { field: "id" },
        name: { field: "name" },
      },
    },
  },
};

Collection operators in practice

Collection-aware operators (filter, exists, hasIntersection, map, and all) require the mapper to declare the relation with type: "many". The adapter automatically scopes lambda variables and uses the fields map when translating expressions such as tag.name:

const mapper: Mapper = {
  "request.resource.attr.tags": {
    relation: {
      name: "tags",
      type: "many",
      fields: {
        name: { field: "name", nullable: true },
      },
    },
  },
};
  • exists and filter wrap the translated condition in $elemMatch.
  • hasIntersection works for both scalar arrays and arrays of objects; when the plan uses map(lambda(tag.name)) the adapter projects tag.name to tags.$elemMatch.name.
  • all converts the lambda condition into a negated $elemMatch so that all elements must satisfy the predicate.
  • A bare map expression verifies that the referenced nested path exists inside each element.

Mapper functions

You can also supply a function if your mappings follow a predictable pattern:

const mapper: Mapper = (path) => {
  if (path.startsWith("request.resource.attr.")) {
    return { field: path.replace("request.resource.attr.", "") };
  }
  if (path.startsWith("request.principal.attr.")) {
    return { field: `principal.${path.replace("request.principal.attr.", "")}` };
  }
  return { field: path };
};

Value parsing

Use valueParser to convert values from the Cerbos plan into types that MongoDB expects. A common use case is converting string IDs to ObjectId:

import { Types } from "mongoose";

const mapper: Mapper = {
  "request.resource.attr.id": {
    field: "_id",
    valueParser: (value) => new Types.ObjectId(value),
  },
};

valueParser also works on nested relation fields via the fields map:

const mapper: Mapper = {
  "request.resource.attr.createdBy": {
    relation: {
      name: "createdBy",
      type: "one",
      field: "id",
      fields: {
        id: {
          field: "id",
          valueParser: (value) => new Types.ObjectId(value),
        },
      },
    },
  },
};

Usage example

import { GRPC as Cerbos } from "@cerbos/grpc";
import mongoose from "mongoose";
import {
  queryPlanToMongoose,
  PlanKind,
  type Mapper,
} from "@cerbos/orm-mongoose";

await mongoose.connect("mongodb://127.0.0.1:27017/test");
const cerbos = new Cerbos("localhost:3592", { tls: false });
const MyModel = mongoose.model("MyModel", /* ... schema ... */);

const mapper: Mapper = {
  "request.resource.attr.title": { field: "title" },
  "request.resource.attr.owner": {
    relation: { name: "owner", type: "one", field: "id" },
  },
  "request.resource.attr.tags": {
    relation: {
      name: "tags",
      type: "many",
      fields: { name: { field: "name" } },
    },
  },
};

const queryPlan = await cerbos.planResources({
  principal: { id: "user1", roles: ["USER"] },
  resource: { kind: "document" },
  action: "view",
});

const result = queryPlanToMongoose({ queryPlan, mapper });

if (result.kind === PlanKind.ALWAYS_DENIED) {
  return [];
}

const filters = result.kind === PlanKind.CONDITIONAL ? result.filters : {};
const records = await MyModel.find(filters);

If you already have application-specific criteria you can combine them using $and:

const filters = result.kind === PlanKind.CONDITIONAL ? result.filters : {};
await MyModel.find({ $and: [filters ?? {}, { archived: false }] });

Error handling

queryPlanToMongoose throws descriptive errors in the following scenarios:

  • The plan kind is not one of the Cerbos PlanKind values (Invalid query plan.).
  • A conditional plan omits the operator/operands structure (Invalid Cerbos expression structure).
  • An operator listed in the plan is not implemented (Unsupported operator: <name>).
  • Collection-oriented operators (map, filter, exists, all, etc.) are used without a relation mapper, or with a mapper that declares type: "one" where type: "many" is required (errors such as map operator requires a relation mapping).
  • Lambda expressions in the plan are malformed (for example, missing a variable operand results in Lambda variable must have a name).
  • Value operands do not match the expected type, e.g., hasIntersection supplies a non-array value.

Surfacing these errors early helps keep the adapter and your Cerbos policies in sync.

Limitations

  • exists_one throws rather than silently degrading to exists.
  • Aggregation expressions inside collection predicates, outer-document references from lambdas, and negation of nullable collection macros fail closed because $elemMatch cannot preserve their CEL scoping and three-valued error semantics.
  • Operators not enumerated in Supported operators (such as search, mode, scalar math helpers, atomic number operations, composite keys, etc.) are not implemented and will throw Unsupported operator.
  • Translations may use document-level $expr, but never require a multi-stage aggregation pipeline.

版本与发布记录

@cerbos/orm-mongoose 共发布 9 个版本,首次发布于 2023/06/28;过去 12 个月发布了 3 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
3.0.0latest2026/08/043 个月前
2.1.02026/02/029 个月前
2.0.22025/11/1811 个月前
0.1.22023/07/193 年前
0.1.12023/07/193 年前
0.1.02023/07/193 年前

关于 @cerbos/orm-mongoose 的常见问题

@cerbos/orm-mongoose 是什么?

An adapter library that takes a Cerbos Query Plan (PlanResources API) response and converts it into a Mongoose filter. It is desi

如何安装 @cerbos/orm-mongoose?

在项目目录运行 npm install @cerbos/orm-mongoose,或使用 pnpm add / yarn add / bun add。

@cerbos/orm-mongoose 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@cerbos/orm-mongoose 支持 ESM 还是 CommonJS?

以 CommonJS 形式发布,可以直接 require();在 ES Module 项目中也可以用 import 引入(Node.js 会把 module.exports 作为默认导出)。

@cerbos/orm-mongoose 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=22.0.0。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@cerbos/orm-mongoose 可以商用吗?

@cerbos/orm-mongoose 使用 Apache-2.0 许可。宽松许可:允许商业使用、修改和再分发,并附带明确的专利授权;分发时需保留许可与 NOTICE 文件,修改过的文件要注明改动。以上为概括,不构成法律意见,请以许可原文为准。

@cerbos/orm-mongoose 的下载量有多少?

根据 npm 官方下载统计,@cerbos/orm-mongoose 在 2026/10/10 – 2026/11/08 这 30 天内被下载 3,266 次,日均约 109 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@cerbos/orm-mongoose 还在维护吗?

最新版本 3.0.0 发布于 2026/08/04(3 个月前);至今共发布 9 个版本,其中过去 12 个月发布了 3 个;首次发布于 2023/06/28。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。