RolebookDocs

Policy versions and custom roles

createVersionedSharing(), the policy store, publishing, staleness bounds, impact previews, and tenant custom roles.

createSharing() evaluates the policy in its definition. createVersionedSharing() instead loads the active policy from a policy store in your own database, lets operators publish new versions at runtime, and lets each tenant define custom roles within bounds you set. It returns the same tenant API plus policies, customRoles, current(), refresh(), and the same diagnostics() snapshot as createSharing().

import { createVersionedSharing, type PolicyStore } from "@rolebook/sharing";

// createPostgresPolicyStore(), createSqlitePolicyStore(), or createMemoryPolicyStore().
declare const policyStore: PolicyStore;

// Every adapter in `definition` must be built with a policy fence (fencePolicy).
const versioned = await createVersionedSharing({
  definition,
  identity,
  invitationTokens,
  policyStore,
  refreshIntervalMs: 5_000,
  maxStalenessMs: 30_000,
});

const state = versioned.current(); // { generation, digest, label?, confirmedAt, seedMatchesActive }
const decision = await versioned
  .forTenant({ tenantId, actor })
  .authorize({ resource: { type: "project", id: projectId }, action: "read" });

It is async: it reads the active pointer (and seeds the store) before it returns.

Options

All of createSharing’s options, plus:

OptionDefaultMeaning
policyStorerequiredThe PolicyStore.
refreshIntervalMs5000How old a confirmed pointer may be before an operation re-reads it. Integer, 100 to 60,000.
maxStalenessMs30000How long a cached pointer may serve while the store is unreachable. Clamped up to the refresh interval, at most 300,000.
seed"activate-if-empty"With an empty store, save and activate the code policy. "require-active" refuses to start instead (NO_ACTIVE_POLICY).
requiredPolicyRoles[]Policy roles every published version must declare.
tenantCacheSize1024Tenant runtimes kept, least recently used first out. Integer, 1 to 65,536.
monotonicNowperformance.now()Elapsed-time source for freshness only, never for stored timestamps.
onSeedDriftnoneCalled once, synchronously, the first time the active digest differs from the code seed.

Construction throws PolicyStoreError: INVALID_OPTIONS, ADAPTER_NOT_FENCED (an adapter does not report policyFence: "enforced"), SEED_INVALID, NO_ACTIVE_POLICY, or ACTIVE_VERSION_INVALID.

Versions and generations

A version’s identity is a digest: sha256: plus 64 lowercase hex digits of the policy’s canonical JSON, which excludes the version label. Activations are numbered by generation, a decimal string starting at "1"; an empty store is generation "0" with a null digest. Counters are compared as BigInt and stop at 9223372036854775807.

The code-defined policy is a seed. Once a version is active, the store wins: a later code change takes effect only through policies.saveDraft() and policies.publish(). current().seedMatchesActive reports drift.

The evaluation version string is "<generation>:<digest>", or "<generation>:<digest>;tenant-roles:<revision>" when the tenant has an available custom role. Decisions, mutation results, listings, access descriptions, and inspection explanations report it as policyVersion.

Publishing

import { createVersionedSharing, type PolicyStore } from "@rolebook/sharing";

declare const versioned: Awaited<ReturnType<typeof createVersionedSharing<typeof definition.resources>>>;
const operator = { type: "user", id: "operator_1" };

const draft = await versioned.policies.saveDraft({ policy, label: "add archive", actor: operator });
if (draft.ok) {
  const diff = await versioned.policies.diff({ from: "active", to: draft.digest });
  const { generation } = versioned.current();
  const published = await versioned.policies.publish({
    digest: draft.digest,
    expectedGeneration: generation,
    actor: operator,
  });
  // published.code: "ACTIVATED" | "GENERATION_CONFLICT" | "ALREADY_ACTIVE" | ...
}
MethodDoes
saveDraft({ policy, label?, actor })Validates and stores a canonical version under its digest. SAVED or EXISTS; refusals POLICY_TOO_LARGE (over 1 MiB), POLICY_INVALID, RESERVED_ROLE_NAME (a role starting rolebook.custom.), DEFINITION_INCOMPATIBLE, INVALID_ACTOR, INVALID_LABEL.
readVersion({ digest })The stored version, its policy, and whether it is active.
listVersions({ limit, cursor? }), listActivations(...)Paged history, newest first.
diff({ from, to })A PolicyDiff between two digests or "active".
previewImpact(input)Decisions that would change for given subject and resource pairs.
previewCustomRoles({ candidate, limit, cursor? })Which stored custom roles a draft would make unavailable.
publish({ digest, expectedGeneration, actor })Activates a version if the generation still matches: ACTIVATED, GENERATION_CONFLICT, ALREADY_ACTIVE, or a refusal.

previewImpact evaluates explicit pairs of subject and resource (at most 200), or a sample of up to 20 subjects and 50 candidate resources each, under both the active policy and the candidate, and reports the decisions that change, a summary, and custom roles that would lose availability.

Who may call these

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 expose them to tenant users.

Writes are fenced, reads are bounded

Writes never commit under a generation that is no longer active. An adapter built with fencePolicy reports policyFence: "enforced" and, inside every mutation transaction, after the resource-revision compare, reads the active generation and the tenant’s custom-role revision. When either differs from the values the command started with, the mutation returns POLICY_GENERATION_CHANGED or TENANT_ROLES_CHANGED. Requirements:

  • The policy-store tables live in the same database as the sharing tables of every fenced adapter.
  • The store and every fence use the same tablePrefix.
  • The fence reads only through the mutation transaction’s executor.
  • Before the first publish (or custom-role define), every process that writes sharing state runs fenced adapters. A process left on an unfenced adapter can commit under a superseded policy, and Rolebook cannot detect it.

Reads are pull-based with no timer. Each operation checks how long ago its runtime confirmed the active pointer, using monotonicNow. Older than refreshIntervalMs, it re-reads the pointer. While the store is unreachable, a cached pointer serves until maxStalenessMs; past that, authorize() and the other reads reject with PolicyUnavailableError and execute() returns POLICY_UNAVAILABLE, before any identity or storage callback. A read on another instance may therefore decide under the previous generation for at most the refresh interval plus its own duration. There is no strong-read mode.

Once the store has told an instance that its active generation is no longer active (a publish GENERATION_CONFLICT naming a later generation, a custom-role generation conflict, or POLICY_GENERATION_CHANGED), that instance decides nothing under that generation, or any older one, until a pointer read that started after the report confirms it or installs a later one. A read already in flight at the report does not count and the refresh interval does not apply. While the store is unreachable in that state, operations fail with STORE_UNREACHABLE; when every refresh (at most three) is overtaken by a further report, the operation fails with STALE.

A running instance never accepts a pointer that goes backwards, changes digest at the same generation, or fails to decode. Those failures are sticky (POINTER_REGRESSED, POINTER_DIGEST_MISMATCH, POINTER_INVALID, VERSION_INVALID) until the process constructs a new instance: restoring an older generation requires restarting every instance. A tenant whose custom-role rows are corrupt sticks at TENANT_ROLES_INVALID for that tenant only. Other PolicyUnavailableError reasons are STORE_UNREACHABLE, STALE, INTERNAL_ERROR, CLOCK_FAULT, and REVISION_REGRESSED. INTERNAL_ERROR is a fault that did not come from the store; it is never tolerated as staleness. After a custom-role define or remove applies, or an execute returns TENANT_ROLES_CHANGED, the instance never serves that tenant’s earlier custom roles, not even while the store is unreachable; if every reload is overtaken by a further invalidation on the same instance, the operation fails closed with STALE. The original error is kept as the cause and passed to onInternalError when that option is set.

Custom roles

A custom role is a tenant-local member-role label custom:<name>, matching custom:[a-z][a-z0-9_]{0,47} (CUSTOM_ROLE_LABEL). It is stored in the membership role column, disjoint from static labels. It names a template: one of the type’s static member-role labels. The stored role carries every effective deny of the template’s policy role, plus operator rules, and every operator allow must be held by the template for every concrete permission it names.

import type { createVersionedSharing } from "@rolebook/sharing";

declare const versioned: Awaited<ReturnType<typeof createVersionedSharing<typeof definition.resources>>>;

const listed = await versioned.customRoles.list({ tenantId });
if (listed.ok) {
  const defined = await versioned.customRoles.define({
    tenantId,
    resourceType: "project",
    name: "custom:reviewer",
    template: "editor",
    rules: [{ effect: "allow", permission: "project:read" }],
    expectedRevision: listed.revision,
    actor: { type: "user", id: "operator_1" },
  });
}

define and remove compare-and-swap on the tenant’s revision (REVISION_CONFLICT otherwise). define refuses with CEILING_EXCEEDED (with the permissions above the template), CUSTOM_ROLE_INVALID (name, rules, or limits), UNKNOWN_RESOURCE_TYPE, TEMPLATE_UNKNOWN, TOO_MANY_CUSTOM_ROLES, CUSTOM_ROLE_NAME_RETIRED, GENERATION_CONFLICT, or REVISION_EXHAUSTED. Limits: 32 custom roles per tenant, 256 records including tombstones, 64 operator rules per role.

set({ tenantId, roles, expectedRevision, actor }) makes roles the tenant’s complete set of live custom roles in one write: every role gets define’s checks, the limits are counted on the result, a live role the set does not name is removed, and every change, one revision bump and the audit events commit together, fenced on expectedRevision and the active generation, or nothing is written. A concurrent define, remove, set or publish makes it answer REVISION_CONFLICT or GENERATION_CONFLICT. A set already in place answers UNCHANGED and writes nothing. It exists when the policy store implements writeTenantRoleSet, as the first-party stores do; see CustomRoleAdministration.

A tenant with at least one available custom role is evaluated under a tenant policy: the active policy plus one derived role per available custom role. Grants, invitations, and evaluation then accept the label.

SituationStatusResult
Live role within its templateavailableGrants and evaluation use it.
TombstoneretiredThe name cannot be reused (CUSTOM_ROLE_NAME_RETIRED).
Template label gonetemplate_missingThe role is unavailable.
Rules no longer within the templateexceeds_templateThe role is unavailable; Rolebook does not clamp it.
A row that does not decodeinvalidThat role is unavailable.
Tenant-wide corruptionSticky TENANT_ROLES_INVALID for that tenant.
A custom: label the tenant never definedThe binding fails closed; only the owner’s revokeMember removes it.

An unavailable role is absent from evaluation, so a membership that names it fails the binding closed rather than having its denies ignored. New grants, changes, and invitations to it are ROLE_NOT_ALLOWED; accepting an invitation to it is INVITATION_UNAVAILABLE; only the owner’s recovery path can change or revoke such a membership. describeAccess() marks it roleUnavailable: true.

Idempotent replays

A versioned execute() replays the actor’s own committed idempotency key before validation and authorization: the fingerprint binds actor, tenant, and command, and the answer is ALREADY_APPLIED with the policyVersion stored on the original commit. A since-deleted custom role or a lost management permission cannot turn a committed command into a refusal. The replay lasts only as long as the idempotency record; see retention.

Testing without a database

createMemoryPolicyStore() is an in-memory PolicyStore. Pass its fence method as fencePolicy to createMemorySharingAdapter(), then pass the store and that adapter to createVersionedSharing(). It also has test seams: failWith(error), failNextAudit(), setCounters(), and readAudit().