Aviary

External policy engines

Delegate decisions to Cerbos, OPA or any policy decision point. The DecisionProvider seam can allow, deny or abstain, batches checks, and maps query plans onto gate.scope().

Official policies and RBAC cover most apps. Some organizations, though, already run a policy decision point (PDP), such as Cerbos, OPA or OpenFGA, and want authz to defer to it. The DecisionProvider seam does that.

Unlike the grant-only permission seam, a decision provider is authoritative and resource-aware:

import type { DecisionProvider } from '@dudousxd/nestjs-authz';

const provider: DecisionProvider = {
  // true / { allowed: true } → allow · false / { allowed: false } → deny · undefined → abstain
  decide(user, ability, resource) { /* ... */ },
  // optional: one round-trip for a whole gate.allowsMany(...) batch
  async decideMany(user, requests) { /* ... */ },
  // optional: gate.scope(Entity, ability) → a ScopeConstraint (undefined abstains)
  planScope(user, entity, ability) { /* ... */ },
};

Register it under the DECISION_PROVIDER token: { provide: DECISION_PROVIDER, useValue: provider }.

A deny has no reason. The message of { allowed: false, message } is accepted but dropped: a route denial is always the official { statusCode: 403, message: 'Forbidden' }. To send a reason, throw your own ForbiddenException(reason). The route then returns your body, but no denied event is emitted and AuthorizationService.can() throws instead of returning false.

Where it is asked

Right after the global superAdmin hook (which receives the resource too), everywhere a decision is made:

  • On routes — in the before() of every policy that extends AuthzPolicy, as decide(user, ability, firstArg) (byId(Post)'s record). Its allow or deny is final; undefined lets the ability decide. A policy that cannot extend AuthzPolicy calls decisionProviderBefore(user, ability, resource) from its own before(). RolePolicy and PermissionPolicy do not ask it: their abilities name roles and permissions, not resources.
  • gate.allows(ability, resource) — before the linked policy, the persisted permissions and the ad-hoc gate. gate.allows(PostPolicy, 'update', post) reaches it through the policy's before(), as on routes.
  • gate.allowsMany(...) — one decideMany call for the batch's string abilities when implemented, else decide per item (also when the batch call fails).
  • gate.scope(Entity, ability) — planScope, right after superAdmin; undefined abstains and the policy's scope decides.

A guest reaches the provider as null, so the engine can allow public access; abstain to keep the default guest denial. A denial is the official AuthorizationError (401/403); the decision event carries reason: 'decision-provider'. Errors the provider throws propagate.

Cerbos

The Cerbos adapter ships inside the core package as the @dudousxd/nestjs-authz/cerbos subpath. Its client types are structural, so you bring your own @cerbos/http or @cerbos/grpc client and nothing extra gets installed:

import { DECISION_PROVIDER } from '@dudousxd/nestjs-authz';
import { CerbosDecisionProvider } from '@dudousxd/nestjs-authz/cerbos';
import { HTTP } from '@cerbos/http';

@Module({
  providers: [
    {
      provide: DECISION_PROVIDER,
      useValue: new CerbosDecisionProvider({
        // A client, or (user) => per-tenant client. Resolving undefined abstains for that user.
        client: new HTTP(process.env.CERBOS_URL!),
        principal: (u) => u && { id: u.id, roles: u.roles, attr: { tenantId: u.tenantId } },
        // Which checks Cerbos governs. undefined abstains, so policies and RBAC decide.
        resource: (ability, r) =>
          r instanceof Post ? { kind: 'app:post', id: r.id, attr: { ownerId: r.ownerId } } : undefined,
        // Query plans for gate.scope(Post, 'read').
        scope: { resource: (entity) => (entity === Post ? { kind: 'app:post' } : undefined) },
      }),
    },
  ],
})
export class AppModule {}
  • Policy before() checks, gate.allows and gate.authorize map to CheckResources. gate.allowsMany sends one request: resources are de-duplicated, their actions merged, and large batches split into chunks of maxBatchSize (default 50).
  • gate.scope(Post, 'read') maps to PlanResources, translated to the scope AST that every ORM adapter compiles into a WHERE:
    • ALWAYS_ALLOWED becomes allow-all and ALWAYS_DENIED becomes deny-all.
    • and/or become groups, and not is pushed down to the leaves.
    • eq ne lt gt le ge in comparisons on request.resource.attr.* (or request.resource.id) become leaf conditions.
    • To rename attributes to columns, use scope.field.

The adapter fails closed: an unreachable PDP denies, and a plan that uses something the scope AST can't express (arithmetic, lambdas, membership in an attribute's array) scopes to no rows. Set onFailure: 'abstain' to fall back to your own policies instead, and use onError to log.

On this page