RolebookDocs

Security model

What Rolebook guarantees, and what your application must establish.

Rolebook is an embedded authorization decision library. An application binds a subject, scoped role assignments, and trusted request context to a policy, then checks a concrete action against a concrete resource. Rolebook evaluates those supplied facts locally and returns an allow or a coded denial.

Rolebook is not an identity system, a resource database, or evidence that the supplied facts are true. This page defines the boundary your application must preserve. It is not an external security audit or certification.

The engine is the only evaluator. The sharing packages, the decision service, and offline snapshots each bring facts to it from a different place, and each adds its own boundary, described below. Choose how decisions run compares them.

Your application establishes

Before binding or checking:

  • The subject’s canonical type and id, from an authenticated identity.
  • Role assignments, including their subject, scoped resource, and descendant applicability, from an authoritative store.
  • The requested resource and its ordered ancestry, loaded through an authoritative, tenant-scoped path.
  • Context facts, including their freshness and whether a client may influence them.
  • The policy version selected for the request. With the sharing package’s versioned constructor, the sharing layer selects it from the policy store and reports it on the decision.

A decision says only that the supplied policy and facts matched. It does not prove identity, tenancy, membership, ownership, resource existence, or the freshness of a policy or context value.

Resource provenance

trustedResource(ref, ancestors, attributes) makes an immutable, caller-attested snapshot. Its type and structural validation do not represent a database row, an external signature, or tenant proof, and a type-correct ancestor ID is only caller-supplied data. Load a resource through a query scoped to the authenticated tenant, build the snapshot from that result, and pass immediate-parent-to-root ancestry in the policy’s declared type order. Never treat a client-provided resource ID, attribute, active-workspace selection, or claimed role as authorization proof. A structurally valid resource from another tenant is still the wrong input.

Who may change policy

With versioned sharing, whoever can call policies.* or customRoles.* can change every tenant’s access. Rolebook records the actor in the policy audit but does not authorize it: authenticate and authorize operators before calling these APIs, and never let tenant users reach them. The policy store is authority data with the same standing as membership rows, in your database: write access to its tables is write access to policy. Before the first publish, every process that writes sharing state must run policy-fenced adapters.

Core invariants

For a policy that compiles, Rolebook enforces:

  1. A check names a concrete resource:action; wildcards are accepted only in policy rules.
  2. An assignment applies only when its subject is the bound subject or one of the binding’s flat group principals, and its scope is the checked resource or an allowed ancestor. appliesTo: "descendants" covers the scope resource itself and its descendants; "self" covers only the scope resource.
  3. Resource ancestry is bounded, ordered, and consistent with the policy’s declared parent types. A recursive: true type may repeat as a contiguous run of distinct same-type ancestors, still within the 16-ancestor limit and continuing to the root. Repeated references are refused. Core cannot detect an omitted ancestor within a same-type run; the caller must supply the complete authoritative chain, just as it must supply authentic resource IDs.
  4. A role’s rules target its scope type or declared descendants; rules for an ancestor or unrelated type fail compilation because they could never apply.
  5. A rule matches only when its permission, condition, and field constraint all match. A known false condition matches neither effect; an unknown condition never matches an allow and conservatively matches a deny. A field-restricted allow matches only a requested field one of its patterns matches exactly, so it never authorizes a request without a field; a field-restricted deny matches a request without a field and any field that equals, contains, or lies inside a denied path.
  6. Matching denies are evaluated before matching allows. Inherited rules keep their effects; there is no implicit bypass role or action implication.
  7. Subject and resource identity come from reserved canonical fields; attribute bags cannot replace type or id.
  8. Dynamic map access uses own properties. Unsafe prototype keys and accessor properties are rejected.
  9. Policy, binding, request, resource, context, and condition values are copied into immutable, JSON-like snapshots with finite numbers. Cycles, sparse arrays, accessors, and unsupported object shapes are rejected or denied. An explicit undefined inside a snapshot is rejected; only the optional top-level context, principals, and field slots treat undefined as omitted.
  10. check(), enforce(), and explain() run one decision path; explaining only observes it, is bounded, and does not change the decision. check() and enforce() build no trace. { detail: "conditions" } adds condition trees, read only after the request snapshot is fixed. They record fact paths and rule identifiers, not runtime values or policy literals. The rules that do not decide the request share a budget of 256 condition-tree nodes in evaluation order; the deciding rule’s tree, itself at most 256 nodes, is always retained whole beside them, so one explanation holds at most 512 nodes. A deciding rule beyond the 64-entry trace cap is still omitted, as traceTruncated reports. Options are inspected without invoking accessors. Only a plain object whose single own enumerable data property is detail: "conditions" selects condition detail; {} and { detail: undefined } select the rule-only trace. Every other value, including one with an extra key, a non-plain prototype, an accessor, or one whose inspection throws, also yields the rule-only trace and sets optionsRejected: true on the explanation, and is never treated as an evaluator fault. Do not return a detailed explanation to an unauthorized caller.
  11. The complete assignment collection is validated before entries are filtered. A malformed assignment, unknown role, or role/scope mismatch denies the binding even if that entry would not otherwise apply.
  12. Group principals are flat and bounded: at most 64 distinct principals, none equal to the subject. They are never expanded, so nesting and membership graphs cannot be expressed. Deny precedence spans every principal; decisions and traces name the contributing group in via.
  13. A binding may reuse a copy Rolebook itself produced with prepareAssignments(). Reuse skips only the copy: every reused entry is validated on every bind, and budgets apply across reused and fresh entries together. A caller cannot register a value.

Errors and outcomes

Policy compilation is a deployment-time operation: definePolicy() and createAuthorizer() throw for a malformed policy. Treat that as a failed rollout.

Binding and checking are fail-closed: invalid input returns a denial with a stable code, and runtime inputs are validated as complete envelopes, so an unknown key denies rather than being ignored. Storage adapters treat a fence or fact revalidation as passing only when it returns literally true.

enforce() throws AuthorizationError with the denial; map it deliberately at your framework boundary. Do not use exceptions, reasons, or traces as an audit log. An unexpected evaluator fault returns INVALID_REQUEST, indistinguishable from a malformed call by design; pass onInternalError to createAuthorizer() to observe it.

Policy names use a strict safe grammar; subject and resource IDs are opaque, bounded strings never interpreted as names. Missing or malformed facts never grant access, except that exists: false is a known match when its fact is absent.

The sharing layer

The sharing packages do not change this boundary. A sharing adapter must establish tenant-scoped resource provenance, current identity eligibility, membership, ownership, and ancestry before it creates a Rolebook binding, and sharing decisions are no stronger than those inputs. Beyond that:

  • Workspace membership is eligibility, not access to private resources.
  • Mutations hold the actor’s eligibility (and any authorization facts) in the storage transaction: SERIALIZABLE with FOR SHARE locks on PostgreSQL, the BEGIN IMMEDIATE write lock on SQLite. The in-memory adapter only re-checks, and only when configured; it is not a production adapter.
  • A manager other than the owner can hand out only access it holds itself (the delegation ceiling), denies on groups belong to the owner, and the owner can always remove a deny that reaches them through a group.
  • A denial does not confirm that a resource exists.
  • Teams never act or own resources. Flat teams (withTeams()) are the default: leaving a team ends its access on the next request, and joining one mid-mutation restarts the mutation. Optional bounded nested team lineage (withTeamLineage()) is available on PostgreSQL and SQLite.
  • Versioned reads may use the previous policy generation for at most the refresh interval, or maxStalenessMs while the store is unreachable; writes fence the generation and the tenant’s custom-role revision in the transaction.
  • An idempotency key replays its committed answer only while its record is kept; after pruning, a retry runs as a new command against current state.
  • Each page of listAccessible() and listAccess() is consistent within the page: its candidates, including their absence, the principal, each examined resource, the policy runtime, and one logical instant for every expiry comparison are read at one coherent point. This requires a storage adapter that holds one snapshot for the page, and identity evidence for the same point. The in-memory adapter holds its own snapshot; a SQL adapter needs a supported executor, which on SQLite is the worker-backed executor and not the queued one. A page that cannot be established that way rejects with AccessListingUnavailableError and a non-sensitive reason; it is never a partial page or a weaker read. The guarantee covers one page. Each page takes a fresh snapshot, so a cursor does not freeze a traversal across pages, and a returned page is not kept fresh until your code acts on it.
  • describeAccess() reports the ownership, memberships, and invitations stored on one resource. It is not an enumeration of every subject the policy would allow.

The decision service

@rolebook/decision-service evaluates Core checks for authenticated callers. It adds these guarantees:

  • A request names a subject, a resource, a concrete action, and optionally a field. It cannot carry assignments, principals, context, facts, or a policy; an object with an unknown member is refused.
  • Authentication runs before the body is read. There is no anonymous fallback and no allow-all default.
  • A grant maps one credential and actor to one scope and its operations. An unknown scope, another scope, another actor, and an ungranted operation all answer the same forbidden. A bound grant may check only its own subject.
  • Every item of a batch passes preflight before any authority is loaded.
  • Only ALLOWED, EXPLICIT_DENY, and NOT_GRANTED are decisions. An unavailable provider, an invalid or stale authority document, a timeout, or a registry replacement during the request is a no-decision. It never becomes a denial, an allow, cached facts, or empty authority.
  • Responses carry no reasons, stacks, policies, facts, assignments, or matched roles.
  • Body size, structure, time, and concurrency are bounded, and exceeding a bound fails closed.

Your deployment establishes the rest:

  • The credential verifier. Qualify it against its real issuer, audience, expiry, revocation, and key custody. The package ships none.
  • Each authority provider. The service checks that a document names the requested subject and resource, the pinned policy, and a fresh observation time. It cannot check that a document marked complete: true is complete: a provider that omits a deny assignment produces an allow the service cannot detect. Qualify each provider against its real source for scope isolation, complete assignments including denies and flat memberships, complete ordered ancestry, resource existence, the origin of every attribute, and confirmed absence versus unavailability.
  • The HTTP host. It terminates TLS, rejects duplicate headers, normalizes the raw request target before it constructs the Request, and owns rate limiting and connection teardown.
  • Clocks. Freshness compares the provider’s observedAtMs with the service’s wall clock, so the accuracy between the two is a deployment requirement.

A decision is an observation at the decision point. It identifies the policy generation and digest it used, but it is not a transaction fence for a later write and makes no causal-consistency promise.

Offline snapshots

@rolebook/offline verifies a signed bundle that carries one exact check and evaluates it with the engine. It adds these guarantees:

  • The signature covers the exact received bytes. The bundle’s signer cannot supply its own trust lease: the lease is verified under the configured root on every read.
  • A verifier takes no local policy and no caller facts. The carried policy is compiled and its canonical digest compared with the bundle’s and with the lease’s allowed policies.
  • Audience, scope, validity window, fact age, and the stored anti-rollback state are checked before the engine runs. A bundle behind the stored rollback floor for its check, or a lease older than the installed one, is refused.
  • Every failure is a typed no-decision. Missing or lost trust state is never reset and accepted.
  • A ui_only verifier refuses enforcement before parsing, and its results are labelled ui_hint.

It deliberately does not provide:

  • Immediate disconnected revocation. A revoked or compromised signer stays usable until a newer root-signed lease that no longer authorizes its key is durably installed, bounded by the key horizon (at most 7 days), the bundle expiry (at most 24 hours), and fact freshness.
  • Proof of fact completeness. The provider manifest makes a snapshot carry the declared members and fact paths. It cannot prove that the issuer included every assignment, principal, ancestor, or deny. A compromised issuer can falsify facts and timestamps within its trust horizon.
  • Write authorization or one-time use. A decision is reusable while the bundle is valid. A protected side effect needs its own idempotency or use-record protocol.
  • A qualified host. The clock, the state store, the sequence allocator, key custody, and the host qualification record are yours. A wall clock that can be set back, ordinary browser storage, or a restorable file does not meet the adapter contracts, and a TypeScript interface is not a qualification.

Non-goals

The Rolebook engine does not authenticate users, issue sessions, store subjects or memberships, manage invitations, load resources, provide transactional workspace lifecycle, persist audit events, distribute policies, open network connections, or execute accessible-resource queries. The companion packages add some of these as explicit, separately configured layers; none of them hosts a service for you, and each HTTP surface is a handler you mount behind your own authentication.

No Rolebook package supports arbitrary relationship graphs or unbounded cross-resource traversal. The core engine uses flat group principals and a single declared ancestry chain per resource (with optional recursive: true resource types up to 16 ancestors). @rolebook/sharing and @rolebook/teams add opt-in, bounded folder inheritance and nested team lineage on PostgreSQL and SQLite, with strict depth and principal caps. If your access model is dominated by arbitrary relationship graphs and cross-service traversal, use a relationship-based authorization system instead.

Delegated authority is not supported. No Rolebook package lets an actor such as a workload, background job or AI agent act on behalf of another subject, and a caller-supplied onBehalfOf value, grant id or token is never evidence of authority. A workload is checked as an ordinary subject with its own role assignments. The design is a proposal only, recorded in the delegated authority decision record.

See limits for the hard bounds. Adversarial tests for them live in tests/v4-limits-and-closure.test.ts in the repository.

Reporting a vulnerability

Report a suspected vulnerability privately: through the contact page, saying it is a security report, or through GitHub’s private vulnerability-reporting flow where the repository offers it. Never put vulnerability details, proof-of-concept code, credentials, or affected customer data in a public issue, discussion, or pull request.

A useful report names the affected package version or commit, gives a minimal reproduction with the observed and expected authorization result, states the impact and prerequisites, and says whether the issue can cause an unintended allow, a denial, or an availability problem. The maintainers acknowledge a report, assess reproducibility and impact, and coordinate a fix through the private report. No specific response or remediation window is promised, and this page does not represent any version as externally audited or certified.