aladov3.13.0

Docs/Features

Access Control

The @accessControl decorator provides a flexible and intuitive way to implement permission checking on your route handlers. It allows you to validate that requests meet specific authorization requirements by comparing values from the incoming request against expected values.

Configuration

TypeScript
export type AccessControlConfig<T> = {
  /**
   * The property path to extract from the request.
   * Examples: 'auth.user.id'
   */
  inputProperty: string;

  /**
   * Optional transformation function to process the extracted value.
   * Useful for normalizing or converting data types before comparison.
   */
  transformInputProperty?: (inputPropertyValue: unknown) => T | Promise<T>;

  /**
   * Property path to compare against in the request.
   * Examples: 'path.id' (URL parameter), 'body.user.id' (request body)
   */
  compareWithProperty?: string;

  /**
   * The expected value to compare against.
   * Use this if you have a fixed value rather than a dynamic property path.
   */
  expectedValue?: T;

  /**
   * Custom access control handler for complex permission logic.
   * Receives the extracted input value and should return true if access is granted.
   */
  accessControlHandler?: (inputPropertyValue: unknown) => Promise<boolean>;

  /**
   * HTTP status code to return when access is denied.
   * Commonly 403 (Forbidden) or 401 (Unauthorized).
   */
  statusCode: number;

  /**
   * User-friendly error message displayed when access is denied.
   */
  message: string;
};

Either provide compareWithProperty to compare two request values, or expectedValue to check against a fixed value or accessControlHandler to implement complex logic.

Rules are checked at startup. A broken rule would let every request through, so registration fails with an error naming it (Context.accessControl[0]...) when accessControl is neither an array nor { anyOf: [...] }, a rule has an unknown property (a typo such as expectedValu), inputProperty or compareWithProperty does not start with a request property (headers, query, path, body, rawBody, files, auth, ip, origin, method, url), statusCode or message is missing, or the rule has none of expectedValue, compareWithProperty and accessControlHandler.

String values are compared in constant time, so a rule that checks a secret (headers.x-api-key against expectedValue) does not tell how much of a guess was right.

Header names in inputProperty and compareWithProperty are case-insensitive (headers.X-Tenant-Id reads the x-tenant-id header).

A path can be written with brackets: body[ownerId] is body.ownerId, query[role] is query.role, and headers[X-Api-Key] matches the header in any letter case. Both forms are read and checked the same way (3.9.9).

With compareWithProperty, access is denied when either value is missing (undefined or null), before or after transformInputProperty: two missing values never count as a match. On a route with optional auth, an anonymous request therefore fails a rule such as headers.x-tenant-id = auth.tenantId instead of passing it.

Usage Example

TypeScript
@patch('/user/:id', { tags: ['User'] })
@accessControl([{
  inputProperty: 'auth.user.id',
  transformInputProperty: async (v: unknown) => v.toString(),
  compareWithProperty: 'path.id',
  statusCode: 403,
  message: 'Access Denied'
}])
@withAuth(bearerAuth)
public async update(req: Request) {
  // Only allow users to update their own profile
  const { path, body } = req;
  const user = DataStore.getUser(path.id);
  if (user) {
    DataStore.setUser(path.id, body as UserDto);
  }
  return { statusCode: user ? 200 : 404, body: user || { message: 'Not Found' } };
}

In this example, the decorator ensures auth.user.id matches path.id before the handler executes. If access is denied, a 403 response is returned.

Rules run before DTO validation and transforms. If a rule reads body.*, the body is parsed before access control runs; otherwise it is parsed only after every rule has passed.

An inputProperty that reads the request itself (headers.*, query.*, path.*, body.*) is checked before the rule runs, as the auth input is:

  • A field with a declared validator (for example ownerId in the body DTO for body.ownerId) is checked by that validator, once for the request.
  • Any other request value must be a string, number, boolean or bigint.

An object or an array, such as { "$ne": null } from a JSON body, denies access with the rule's statusCode and message before transformInputProperty or accessControlHandler see it. Values the application set, such as auth.*, are not checked.

Multiple Rules

@accessControl combines rules the same way @withAuth combines strategies (3.9.11):

  • an array is a group whose rules must all pass: @accessControl([isMember, isOwner]), as before; allOf(isMember, isOwner) is the same;
  • separate arguments are alternatives, any one of which is enough: @accessControl(isAdmin, isEditor);
  • both together: @accessControl([isMember, isOwner], isAdmin) lets in a member who owns the resource, or an admin.
TypeScript
import { accessControl, allOf } from 'alado';

@patch('/posts/:id')
@accessControl(allOf(isMember, isPostOwner), isAdmin)
@withAuth(bearerAuth)
public async update(req: Request) {}

Alternatives are tried in order and the first whose rules all pass allows the request; the rules of later alternatives are not run. When none passes, the response is the error of the first alternative (its first refusing rule), so put the alternative most clients are expected to meet first. @accessControl() without a rule throws.

Arrays and spreading. As with @withAuth, @accessControl(...rules) passes the rules as alternatives and allows a request any one of them accepts. Pass the list itself (@accessControl(rules)) or allOf(...rules) when all must pass.

Keep all rules in one @accessControl: a second one on the same method would replace the first one's rules, so it throws AladoConfigurationError with code: 'DECORATOR_REPEATED' (3.9.7).

Without decorators

Context.accessControl (type ContextAccessControl) takes a list of rules that must all pass ([isMember, isOwner]), or { anyOf: [...] } for alternatives, each a rule or an array of rules (type AccessControlAlternative):

TypeScript
app.patch('/posts/:id', {
  // ...
  accessControl: { anyOf: [[isMember, isPostOwner], isAdmin] },
}, handler);

A list is AND here, unlike Context.auth where a list is OR, because that is what it has always meant. An empty anyOf, an empty group (it would allow every request) or a group inside a group throws when the route is registered, with the position of the rule in the message (Context.accessControl.anyOf[0][1]...).