RolebookDocs

Migrating from Casbin and role tables

@rolebook/migrate: a strict Casbin-subset checker, import planners, plan diffs, and a read-only shadow comparison.

@rolebook/migrate plans a move to Rolebook without changing what your application enforces. It checks a Casbin source against one exact, versioned subset, plans a Rolebook policy and assignments from it (or from an application role table), diffs plans so an import can be applied idempotently and rolled back, and compares Rolebook’s decisions with your legacy system’s in shadow. Every export is pure: nothing reads files, opens a connection, writes to a store, evaluates model text, or switches enforcement. Unsupported input is refused with a precise reason, never approximated. The importer and its development/test dependency graph contain no Casbin engine; its only package dependency is the Rolebook peer.

Applying a plan is your application’s code, because only it owns the store and its transactions. The tested SQLite recipe in the package’s examples shows one way: it applies a plan atomically and rolls assignments back, and it refuses stale revisions, receipt drift, and a policy replacement that would invalidate unrelated assignments.

A typical migration has four steps, and enforcement changes only in the last one:

  1. Check. Run the planner on your Casbin model and policy, or on your role table. Fix or scope out every issue it reports; nothing is approximated.
  2. Plan and review. Read the planned Rolebook policy and assignments, and diff the plan against the previous one to see exactly what an import would add or remove.
  3. Shadow. Keep enforcing with your legacy system, evaluate the same requests with Rolebook, and compare the two decisions. Investigate every disagreement.
  4. Apply and switch. Apply the plan in your own transaction, then move enforcement to Rolebook in your application.
import { planCasbinImport } from "@rolebook/migrate";
import { createAuthorizer, trustedResource } from "rolebook";

declare const model: string; // the Casbin model text
declare const policy: string; // the Casbin policy lines

const result = planCasbinImport({
  model,
  policy,
  roles: ["editor"], // declared, never inferred
  importId: "casbin-2026-11",
  subjectType: "user",
  objects: {
    "doc-1": { type: "document", id: "1" },
    "doc-2": { type: "document", id: "2" },
  },
});
if (!result.ok) throw new Error(result.issues.map((issue) => issue.code).join(", "));

const decision = createAuthorizer(result.plan.policy).check({
  subject: { type: "user", id: "alice" },
  assignments: result.plan.assignments.map((record) => record.assignment),
  permission: "document:read",
  resource: trustedResource({ type: "document", id: "1" }),
});

The accepted Casbin subset

Version rolebook/casbin-rbac-equality/v1 accepts exactly one model, five sections in any order, each once:

[request_definition]
r = sub, obj, act
[policy_definition]
p = sub, obj, act
[role_definition]
g = _, _
[policy_effect]
e = some(where (p.eft == allow))
[matchers]
m = g(r.sub, p.sub) && r.obj == p.obj && r.act == p.act

The definitions are read with a fixed, token-preserving grammar and never evaluated. Spaces and tabs are allowed around headers, keys and values and between tokens, but never inside one: s ub, r . sub, & & and a split section name are refused, and the effect must be exactly some(where (p.eft == allow)), as Casbin itself requires. Accepted formatting fixtures are checked against committed observations from Casbin 5.43.0 and evaluated through the real Rolebook Core. The tests retain 200 differential worlds (105,600 requests) and a separate 300-world reference suite without installing or executing Casbin. The observations bind exact inputs to recorded decisions; a new input requires separately captured and reviewed evidence. This verifies the recorded cases against that fixed version, not compatibility with every Casbin release.

Domains, deny or priority effects, custom matchers, matcher functions, extra definitions such as p2 or g2, and unknown, duplicate, or missing sections are each refused with their own code and section.

Policy lines are exactly p, role, object, action and g, user, role, compared exactly. A wrong field count, an empty field, a *, a quote, a control or format character, unbalanced parentheses, or a field over 256 characters is refused with its line number. Repeated roles and lines are sets and change nothing. Roles are declared by you: a p line naming an individual user, a g line to an undeclared role, a g line whose user is itself a role, and a declared role nothing uses are all refused. Issues never carry source text.

Users and roles share one namespace, as in Casbin: a request is allowed when some role holds the permission on the object and the subject is either a member of that role through a g line or is the role’s own name. Casbin links every name to itself, so the planner gives each role that holds anything a subject with its own name.

How a Casbin import is planned

A Rolebook role’s rules apply to a resource type, and its assignment decides where. A Casbin role can hold read on one document and write on another, so one Rolebook role per Casbin role would widen access. The planner generates one role per Casbin role, resource type, and exact action set held on one object, and assigns it only at that object with appliesTo: "self". Generated names are the Casbin role, the type, and a SHA-256 of both with the action set, and must fit Rolebook’s role-name grammar; otherwise the import is refused, never renamed.

Capacity is checked from an exact count before anything is built: at most 256 assignments per subject, at most MAX_PLANNED_ASSIGNMENTS (100,000) in a plan, and Rolebook’s own policy limits (128 roles, 128 resource types, 128 actions per type, 4,096 rules). Each limit has its own code, distinct from the subset codes. The 100,000 limit is a protective starting limit, not a performance guarantee; raising it requires memory and timing measurements. The plan is all or nothing and deterministic, with a sourceDigest, a content-derived policyDigest, and a recordId per assignment.

Role tables

planRoleTableImport turns your existing { subject, role, resource } rows into direct memberships on exactly those resources, under a policy you already have. Each row is validated with the engine’s own assignment validation and against the policy. A role whose rules, inherited ones included, reach another resource type is refused rather than imported in part. Any rejected row refuses the whole import with its row number.

Applying, rolling back, and cutting over

The package writes nothing. Apply the plan’s policy and assignments together, in one transaction of your own store. diffImportPlans(applied, next) returns the records to create and remove and whether the policy changed, with both policy digests, so a widened role with unchanged assignments is never reported as unchanged. rollbackOfImportPlan(applied) lists every record the import owns; it does not restore an earlier policy.

createShadowComparison takes a run id and evaluates each request with the real engine. Each comparison carries an envelope: either your attestation that both systems decided over the same facts at the same logical time, named by opaque snapshot identities, or a reason the request is not comparable. Requests without a valid attestation, or with mismatched identities, are counted by reason and excluded from the comparison. Only ALLOWED, NOT_GRANTED and EXPLICIT_DENY are compared; any other engine code is an error, split by the legacy outcome. Only redacted references and permissions of mismatches are kept. assessCutover checks that every false allow is acknowledged by run, policy digest and sample, that false denies (with errors where the legacy system allowed) are within your budget, and that every mismatch bucket has a disposition. Every counter and every sum of counters must be an exact safe integer, or the evidence is malformed; a comparison stops counting at Number.MAX_SAFE_INTEGER calls and its report is then marked saturated and never ready. It is a report: cutover stays your decision.

The package hashes with node:crypto, so it runs on Node 24 or later and Bun.

API

CASBIN_SUBSET_VERSION

const CASBIN_SUBSET_VERSION: "rolebook/casbin-rbac-equality/v1";

CasbinSubsetReport

type CasbinSubsetReport = {
  readonly supported: true;
  readonly version: typeof CASBIN_SUBSET_VERSION;
  readonly rules: readonly {
    readonly role: string;
    readonly object: string;
    readonly action: string;
  }[];
  readonly memberships: readonly {
    readonly user: string;
    readonly role: string;
  }[];
} | {
  readonly supported: false;
  readonly issues: readonly ImportIssue[];
  readonly truncated: boolean;
};

checkCasbinSubset

function checkCasbinSubset(input: {
  readonly model: string;
  readonly policy: string;
  readonly roles: readonly string[];
}): CasbinSubsetReport;

ImportIssue

interface ImportIssue {
  readonly code: ImportIssueCode;
  readonly line?: number;
  readonly section?: string;
}

ImportIssueCode

type ImportIssueCode = "UNSUPPORTED_MODEL" | "DOMAINS" | "DENY_EFFECT" | "PRIORITY" | "CUSTOM_MATCHER" | "MATCHER_FUNCTION" | "EXTRA_DEFINITION" | "UNKNOWN_SECTION" | "DUPLICATE_SECTION" | "MISSING_SECTION" | "UNKNOWN_LINE_TYPE" | "FIELD_COUNT" | "EMPTY_FIELD" | "WILDCARD" | "QUOTED_FIELD" | "INVALID_FIELD" | "USER_POLICY" | "UNDECLARED_ROLE" | "ROLE_NESTING" | "UNUSED_ROLE" | "TOO_LARGE" | "INVALID_NAME" | "UNMAPPED_OBJECT" | "UNUSED_OBJECT_MAPPING" | "DUPLICATE_OBJECT_MAPPING" | "POLICY_REJECTED" | "ASSIGNMENT_LIMIT" | "TOTAL_ASSIGNMENT_LIMIT" | "GENERATED_ROLE_LIMIT" | "RESOURCE_TYPE_LIMIT" | "ACTION_LIMIT" | "RULE_LIMIT" | "NAME_COLLISION" | "ROW_REJECTED" | "ROW_NOT_SELF_ONLY";

diffImportPlans

function diffImportPlans(applied: ImportPlan | undefined, next: ImportPlan): {
  readonly create: readonly PlannedAssignment[];
  readonly remove: readonly PlannedAssignment[];
  readonly unchanged: number;
  readonly policyChanged: boolean;
  readonly fromPolicyDigest?: string;
  readonly toPolicyDigest: string;
};

ImportPlan

interface ImportPlan {
  readonly version: 1;
  readonly importId: string;
  readonly sourceDigest: string;
  readonly policyDigest: string;
  readonly policy: RolebookPolicy;
  readonly assignments: readonly PlannedAssignment[];
}

ImportPlanResult

type ImportPlanResult = {
  readonly ok: true;
  readonly plan: ImportPlan;
} | {
  readonly ok: false;
  readonly issues: readonly ImportIssue[];
  readonly truncated: boolean;
};

MAX_PLANNED_ASSIGNMENTS

const MAX_PLANNED_ASSIGNMENTS = 100000;

PlannedAssignment

interface PlannedAssignment {
  readonly recordId: string;
  readonly assignment: RoleAssignment;
}

planCasbinImport

function planCasbinImport(input: {
  readonly model: string;
  readonly policy: string;
  readonly roles: readonly string[];
  readonly importId: string;
  readonly subjectType: string;
  readonly objects: Readonly<Record<string, {
    readonly type: string;
    readonly id: string;
  }>>;
}): ImportPlanResult;

planRoleTableImport

function planRoleTableImport(input: {
  readonly policy: RolebookPolicy;
  readonly importId: string;
  readonly rows: readonly {
    readonly subject: ResourceRef;
    readonly role: string;
    readonly resource: ResourceRef;
  }[];
}): ImportPlanResult;

rollbackOfImportPlan

function rollbackOfImportPlan(applied: ImportPlan): {
  readonly remove: readonly PlannedAssignment[];
};

assessCutover

function assessCutover(input: {
  readonly report: ShadowReport;
  readonly explainedFalseAllows: readonly FalseAllowAcknowledgment[];
  readonly falseDenyBudget: number;
  readonly dispositions: Partial<Record<"false_allow" | "false_deny" | "noncomparable" | "rolebook_error_legacy_allow" | "rolebook_error_legacy_deny", string>>;
}): {
  readonly ready: boolean;
  readonly blockers: readonly string[];
};

createShadowComparison

function createShadowComparison(options: {
  readonly policy: RolebookPolicy;
  readonly maxSamples: number;
  readonly runId: string;
}): ShadowComparison;

FalseAllowAcknowledgment

interface FalseAllowAcknowledgment {
  readonly runId: string;
  readonly policyDigest: string;
  readonly sampleId: number;
}

ShadowBucket

type ShadowBucket = "match_allow" | "match_deny" | "false_allow" | "false_deny" | "rolebook_error_legacy_allow" | "rolebook_error_legacy_deny" | "noncomparable";

ShadowComparability

type ShadowComparability = {
  readonly kind: "attested";
  readonly rolebookSnapshot: string;
  readonly legacySnapshot: string;
  readonly rolebookTime: string;
  readonly legacyTime: string;
} | {
  readonly kind: "noncomparable";
  readonly reason: ShadowDeclaredReason;
};

ShadowComparison

interface ShadowComparison {
  compare(input: {
    readonly request: AuthorizationRequest;
    readonly legacy: "allow" | "deny" | "unknown";
    readonly comparability: ShadowComparability;
  }): void;
  report(): ShadowReport;
}

ShadowDeclaredReason

type ShadowDeclaredReason = "missing_input" | "stale_snapshot" | "unsupported_semantics" | "nonreplayable_facts" | "unknown_legacy_result";

ShadowNoncomparableReason

type ShadowNoncomparableReason = ShadowDeclaredReason | "snapshot_mismatch" | "time_mismatch" | "invalid_provenance" | "invalid_legacy_result";

ShadowReport

interface ShadowReport {
  readonly runId: string;
  readonly policyDigest: string;
  readonly counts: Readonly<Record<ShadowBucket, number>>;
  readonly noncomparable: Readonly<Record<ShadowNoncomparableReason, number>>;
  readonly compared: number;
  readonly dropped: Readonly<Record<ShadowBucket, number>>;
  readonly samples: readonly ShadowSample[];
  readonly saturated: boolean;
}

ShadowSample

interface ShadowSample {
  readonly sampleId: number;
  readonly bucket: ShadowBucket;
  readonly subject: ResourceRef | null;
  readonly permission: string | null;
  readonly resource: ResourceRef | null;
}