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
- Use a Cerbos client (
@cerbos/httpor@cerbos/grpc) to callplanResourcesand obtain aPlanResourcesResponse. - Provide
queryPlanToMongoosewith that plan and an optional mapper that describes how Cerbos attribute paths relate to your document schema. - The adapter walks the Cerbos expression tree, translates supported operators to MongoDB syntax, and returns
{ kind, filters? }. - 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 withresult.filters.
You can merge the adapter output with existing application filters (for example, via $and) before issuing the Mongoose query.
Supported operators
| Category | Operators | Behavior |
|---|---|---|
| Logical | and, or, not | Builds $and, $or, and $nor groups. |
| Comparisons | eq, ne, lt, le, gt, ge | Emits $eq, $ne, $lt, $lte, $gt, $gte checks against the mapped field. |
| Membership | in, 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 helpers | contains, startsWith, endsWith | Generates escaped regular expressions that target substrings, prefixes, or suffixes. |
| Existence helpers | isSet, exists | Uses $exists/$ne: null for scalars and $elemMatch for collections. |
| Collection helpers | filter, lambda, map, all | Translates 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 values | add, sub, mult, div, mod, if, size, index, get-field | Uses 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 matching | string, double, int, timestamp, matches | Uses 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. |
| Hierarchies | hierarchy, ancestorOf, descendentOf, overlaps | Translates 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.
| Classification | Coverage |
|---|---|
| Oracle-tested | 85 reference conformance actions plus regex, ordered indexing/get-field, and timestamp probes (88 actions) |
| Fail-closed | 29 reference actions |
| Known planner divergence | has() 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/httpor@cerbos/grpcclient
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);
fieldrewrites a single Cerbos path to a different field in MongoDB.nullabledeclares that a storednullrepresents 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 wherenullis an explicit Cerbos value.valueParsertransforms 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 anObjectId). The parser is applied to each value ineq,ne,lt,le,gt,ge, andinoperators. It also works on nested relation fields via thefieldsmap.relationdescribes embedded documents (type: "one") or arrays (type: "many"). Whenfieldis provided on a relation it identifies the property inside that relation that should be used for comparisons (for example, matchingcreatedBy.idwithout an$elemMatch).fieldssupplies nested overrides so lambda expressions such astag.namecan 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 },
},
},
},
};
existsandfilterwrap the translated condition in$elemMatch.hasIntersectionworks for both scalar arrays and arrays of objects; when the plan usesmap(lambda(tag.name))the adapter projectstag.nametotags.$elemMatch.name.allconverts the lambda condition into a negated$elemMatchso that all elements must satisfy the predicate.- A bare
mapexpression 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
PlanKindvalues (Invalid query plan.). - A conditional plan omits the
operator/operandsstructure (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 arelationmapper, or with a mapper that declarestype: "one"wheretype: "many"is required (errors such asmap 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.,
hasIntersectionsupplies a non-array value.
Surfacing these errors early helps keep the adapter and your Cerbos policies in sync.
Limitations
exists_onethrows rather than silently degrading toexists.- Aggregation expressions inside collection predicates, outer-document references from lambdas, and negation of nullable collection macros fail closed because
$elemMatchcannot 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.