RolebookDocs

Decisions, enforce, and explain

Decision codes, check versus enforce, explanation traces, and fault reporting.

Every check returns a frozen decision object, never a bare boolean:

interface AuthorizationDecision {
  readonly allowed: boolean;
  readonly code: DecisionCode;
  readonly reason: string;
  readonly permission: string;
  readonly policyVersion?: string;
  readonly matched?: MatchedRule;
}
  • reason is a short, stable English sentence for logs, such as "A deny rule matched.".
  • permission is the requested permission, or an empty string when the request’s permission was not a string of at most 257 characters, so a decision never reflects unbounded caller input.
  • policyVersion is the policy’s version label, when it has one.
  • matched is present on ALLOWED and EXPLICIT_DENY: the effect, the role that defines the matched rule, the rule’s permission (which may be a wildcard such as project:*), and via when a group principal contributed it.

Decision codes

CodeallowedMeaning
ALLOWEDtrueAn allow rule matched and no deny did.
EXPLICIT_DENYfalseA deny rule matched (or its condition was unknown).
NOT_GRANTEDfalseNo applicable allow rule matched.
UNKNOWN_ROLEfalseAn assignment names a role the policy does not define.
INVALID_ASSIGNMENTfalseThe assignments are malformed, or one’s scope type does not match its role.
INVALID_SUBJECTfalseThe subject or the principals are malformed.
RESOURCE_MISMATCHfalseThe resource is malformed, the wrong type for the permission, or its ancestry does not follow the policy.
INVALID_REQUESTfalseThe binding or request is malformed, the permission is not declared, or evaluation itself faulted.

The order in which these are decided is described in evaluation order.

check

check(request) returns a decision and never throws for malformed runtime input. Use it when the caller decides what a denial means, for example to hide a button or filter a list.

enforce

enforce(request) returns the decision when it allows, and throws AuthorizationError on any denial. The error’s message is the decision’s reason, and error.decision is the full decision.

import { AuthorizationError } from "rolebook";

try {
  authorization.enforce({ permission: "project:delete", resource: project });
} catch (error) {
  if (error instanceof AuthorizationError) {
    console.log(error.decision.code); // "NOT_GRANTED"
  } else {
    throw error;
  }
}

Map AuthorizationError deliberately at your framework boundary (the Hono middleware maps it to 403). Do not use exceptions, reasons, or traces as an audit log.

explain

explain(request) runs the same evaluation and returns the decision plus a trace of the rules it evaluated, in evaluation order: every applicable deny first, then allows, stopping at the first match.

const explanation = authorization.explain({ permission: "project:update", resource: project });

for (const entry of explanation.trace) {
  // entry.outcome: "matched" | "not_matched"
  // entry.effect, entry.role, entry.permission, entry.reason, and entry.via for group rules
  console.log(entry.outcome, entry.effect, entry.role, entry.permission);
}
if (explanation.traceTruncated) console.log("More rules were evaluated than the trace holds");

The trace holds at most 64 entries; traceTruncated is true when evaluated rules were left out. Explanation never changes the decision. A request denied before rules are evaluated (a malformed binding, an unknown role) has an empty trace.

const detailed = authorization.explain(
  { permission: "project:update", resource: project },
  { detail: "conditions" },
);
if (detailed.conditionTraceTruncated) console.log("A condition tree was shortened");

{ detail: "conditions" } is the only options value that adds detail. Each retained rule then includes details: the compiled ruleId (the defining role and rule index in this policy snapshot), a reasonCode, and the condition outcome. A rule with no where has condition.status "absent". A where that was not reached because the permission or field did not match is "not_evaluated". An evaluated condition has its result (true, false, or "unknown") and, while the budget allows, a tree of nodes addressed by JSON Pointer from /where. The tree omits runtime values and policy literals. The rule that decided the request always keeps its whole tree. The other retained rules share a budget of 256 condition nodes in evaluation order, so one explanation holds at most 512; conditionTraceTruncated is true only when a retained rule actually dropped an evaluated node. Rules past the 64-entry cap are described only by traceTruncated. {} and { detail: undefined } give the rule-only trace. Any other options value, including one that cannot be inspected, also gives the rule-only trace and sets optionsRejected: true on the explanation; it does not report an internal fault. Keep detailed explanations on the server: fact names and rule ids are diagnostic metadata.

One-shot forms

check(policy, request), enforce(policy, request), and explain(policy, request) take the binding and the check fields together, for a single decision:

import { check } from "rolebook";

const decision = check(policy, {
  subject: { type: "user", id: "user_123" },
  assignments: [
    {
      subject: { type: "user", id: "user_123" },
      role: "workspace_editor",
      scope: { resource: { type: "workspace", id: "ws_456" }, appliesTo: "descendants" },
    },
  ],
  permission: "project:read",
  resource: project,
});

They use the policy’s shared authorizer, so they are as cheap as createAuthorizer(policy).bind(...). A one-shot request accepts exactly the binding keys plus permission, resource, and field.

Faults fail closed, and can be reported

If evaluation itself throws, Rolebook returns INVALID_REQUEST: a fault must not tell a caller more than a malformed request does. That also makes an evaluator regression look like client error, so pass a reporter to tell them apart:

import { createAuthorizer } from "rolebook";

declare const logger: { error(fields: Record<string, unknown>): void };

const observed = createAuthorizer(policy, {
  onInternalError: (error, { permission }) => logger.error({ err: error, permission }),
});

The reporter is diagnostics only. It never changes the decision, is never called for ordinary malformed input, runs synchronously on the decision path (hand the error off rather than doing work inline), and is ignored if it throws or returns a rejected promise. An authorizer created with a reporter is not the shared per-policy authorizer, though compilation is still reused.

Decisions from the decision service and offline snapshots

The decision service and the offline verifier run this same decision path, on facts they load or receive on the caller’s behalf. They report a narrower set of results:

Engine resultDecision serviceOffline verifier
ALLOWED, EXPLICIT_DENY, NOT_GRANTEDA decision with that code, HTTP 200A decision with that code
UNKNOWN_ROLE, INVALID_ASSIGNMENT, INVALID_SUBJECT, RESOURCE_MISMATCH, INVALID_REQUESTNo-decision authority_invalidNo-decision incomplete_snapshot
An onInternalError notificationNo-decision internal_faultNo-decision internal_fault

In-process, a validation code is a denial because the caller supplied the malformed input. Behind the service or in a signed snapshot, the caller supplied only the question; malformed authority is a fault of the provider or the issuer, so it is reported as a no-decision and not as a denial of the subject.

A decision from either component carries allowed and code, without the engine’s human-readable reason, the matched rule, or a trace. A no-decision names its cause in a closed set: the service returns it as error, and the offline verifier as reason. See decisions and no-decisions.