Aviary

Enforcement

Routes are guarded by the official deny-by-default AuthorizationGuard. This page covers our helpers for the official @Can, the @Roles / @Permission sugar, the decision channel and the optional can-endpoint.

Route enforcement is the official package's: AuthorizationModule.forRoot() installs a global AuthorizationGuard that runs every @Can(Policy, 'ability', args?) on a handler and its class. See the official docs. What it implies:

  • Deny by default. A handler with no @Can(), @Can.Anyone() or @Public() (from @nestjs/authentication) is denied.
  • Requirements add up. Class-level and method-level @Can() all apply; @Can.Anyone() or @Public() on a method drops the class's.
  • Guests reach policies as null, and a guest denial is a 401; a signed-in one is a 403.

This package adds what goes inside the official @Can(), and a migration mode that defers deny by default.

Unannotated routes: unannotated: 'allow'

AuthorizationModule.forRoot({ globalGuard: false }),
AuthzModule.forRoot({ unannotated: 'allow' }),   // forRootAsync({ unannotated, useFactory })

AuthzModule then registers a global AuthzGuard in place of the official one. A route with @Can() requirements is handed to the official AuthorizationGuard: same getUser, same evaluation, same 401/403 and denied event, Can.Anyone() and @Public() respected. A route with none is let through. The default, 'deny', registers nothing. AuthzGuard is exported, for @UseGuards(AuthzGuard) on part of an app.

The app fails to start when unannotated: 'allow' is on and the official global guard too: the official guard would still deny the unannotated routes, so the option would do nothing. Pass globalGuard: false. unannotated decides what the module registers, so under forRootAsync it goes next to useFactory; a factory that returns it fails the startup. See the step-by-step migration.

In this mode the boot log has one expected ERROR, @Can() is not enforced on …: the official startup check recognizes only its own AuthorizationGuard. AuthzGuard does enforce those handlers, and AuthzModule logs a line right after it naming them.

Argument helpers

The third argument of the official @Can() is a resolver (context) => args. Ours:

import { Can } from '@nestjs/authorization';
import { ability, byId, permission, roles, staticCanArgs } from '@dudousxd/nestjs-authz';

@Can(PostPolicy, 'update', byId(Post))                        // the Post named by :id (403 if not found)
@Can(PostPolicy, 'update', byId(Post, { param: 'postId' }))
@Can(RolePolicy, 'has', roles('admin', 'editor'))             // any of
@Can(PermissionPolicy, 'hasAll', permission('posts.publish', 'posts.delete'))
@Can(GatePolicy, 'allows', ability('access-admin'))           // a gate.define() gate
@Can(FeaturePolicy, 'enabled', staticCanArgs('billing'))      // any constant args

roles(), permission(), ability() and staticCanArgs() return resolvers whose arguments do not depend on the call. They carry them on a non-enumerable Symbol.for('@dudousxd/static-can-args') property (STATIC_CAN_ARGS, read with getStaticCanArgs()), so tools such as the Aviary agent can evaluate a requirement without a request. See Resource resolution for byId.

@Roles and @Permission

Sugar that writes official @Can metadata, nothing else:

@Roles('admin', 'editor')        // = @Can(RolePolicy, 'has', roles('admin', 'editor'))
@Permission('posts.publish')     // = @Can(PermissionPolicy, 'has', permission('posts.publish'))

Both work on methods and classes. Roles come from the user object (user.roles / user.role, or resolveRoles) and from an RBAC adapter; permissions from the adapter.

Reading the requirements

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

routeRequirements(PostsController, PostsController.prototype.update);
// [{ policy: PostPolicy, ability: 'update', args: [Function] }] — what the guard will enforce

readCanRequirements(target) returns those declared on one class or method, and isOfficialPolicy(value) tells an official policy class apart. The testing package's requirementsOf(Controller, 'method') builds on them.

Decision channel

Every requirement the official guard enforced and every Gate check is published, allowed or denied, on the aviary:authz:decision diagnostics channel (authzDecisionChannel), with the ability, reason ('route' for the guard, else 'policy', 'super-admin', 'decision-provider', 'permission-provider', 'gate', 'anonymous'), policy and handler. The official package publishes denials only, on nestjs:authorization:denied. See Ecosystem.

The optional can-endpoint

For abilities not already shipped to the client, mount a fallback endpoint (off by default):

AuthzModule.forRoot({
  canEndpoint: true,                 // POST /authz/can; or a custom path
  resourceLoaders: { Post: (id) => posts.findOne(id) },
});

It answers { ability, resource?: { type, id } } (or an array of them, for a batch) with { allowed }, through gate.allows for the user the official guard reads. Types: CanRequestBody, CanResponseBody, CanBatchRequestBody, CanBatchResultItem; DEFAULT_CAN_ENDPOINT_PATH is 'authz/can'. With a loader for the type, the endpoint loads the real record so the linked policy's instance abilities run; without one, only class-level abilities and ad-hoc gates resolve. Unknown or ambiguous abilities answer { allowed: false }.

The endpoint is open to the official guard (authorization:can-anyone on its class), since it answers guests too (with falses). To put it behind your own guards, or tag it for OpenAPI, pass decorators, applied to every controller the module mounts, after its own:

AuthzModule.forRoot({
  canEndpoint: true,
  decorators: [UseGuards(JwtAuthGuard), ApiTags('authz')],
});

Each registration builds its own controller class, so decorators never leak between two.

Under forRootAsync, set canEndpoint and decorators on the async options themselves: controllers are registered before the factory runs.

Next steps

On this page