Testing your integration
Table-driven policy tests, decision suites as JSON, explain-based debugging, sharing with the in-memory adapter, the adapter contracts, and testing providers for the decision service and offline snapshots.
Test the policy as a table
A policy is data, and a check is a pure function of the policy, the binding, and the request, so policy tests need no database. Write one row per subject, action, and expected code, and assert both sides: who can, and who cannot.
import { describe, expect, test } from "bun:test";
import { createAuthorizer, definePolicy, trustedResource, type DecisionCode } from "rolebook";
const policy = definePolicy({
resources: {
workspace: { actions: ["read"] },
project: { parent: "workspace", actions: ["read", "update", "delete"] },
},
roles: {
editor: {
scope: "workspace",
rules: [
{ effect: "allow", permission: "project:read" },
{ effect: "allow", permission: "project:update" },
{
effect: "deny",
permission: "project:update",
where: { fact: "resource.archived", operator: "equals", value: true },
},
],
},
},
});
const project = (archived: boolean) =>
trustedResource({ type: "project", id: "p1" }, [{ type: "workspace", id: "w1" }], { archived });
const editor = createAuthorizer(policy).bind({
subject: { type: "user", id: "u1" },
assignments: [
{
subject: { type: "user", id: "u1" },
role: "editor",
scope: { resource: { type: "workspace", id: "w1" }, appliesTo: "descendants" },
},
],
});
const cases: readonly [string, "project:read" | "project:update" | "project:delete", boolean, DecisionCode][] = [
["reads a project", "project:read", false, "ALLOWED"],
["updates a live project", "project:update", false, "ALLOWED"],
["cannot update an archived project", "project:update", true, "EXPLICIT_DENY"],
["cannot delete", "project:delete", false, "NOT_GRANTED"],
];
describe("editor", () => {
for (const [name, permission, archived, code] of cases) {
test(name, () => {
expect(editor.check({ permission, resource: project(archived) }).code).toBe(code);
});
}
}); Tips:
- Assert the code, not only
allowed:NOT_GRANTEDandINVALID_ASSIGNMENTare both denials, but only one is the denial you meant. - Add a test for each deny and each condition with the fact present, absent, and of the wrong type. A missing fact makes a conditional deny fire.
- Test that a role assigned on one workspace does not reach another workspace’s resources.
- Run
definePolicy()in a test so a malformed policy fails CI rather than a deploy. - Review policy changes with
diffPolicies()and pin the expected diff in a test.
Keep expected decisions as data
The same table can live in a JSON file that people who do not write TypeScript can read and review. A
suite in the rolebook-core-fixtures format holds policies and cases; each case names a policy, a
binding, a resource, a request, and the decision you expect:
{
"format": "rolebook-core-fixtures",
"version": 1,
"suiteId": "projects",
"policies": [
{
"id": "projects",
"policy": {
"resources": { "project": { "actions": ["read", "delete"] } },
"roles": {
"viewer": {
"scope": "project",
"rules": [{ "effect": "allow", "permission": "project:read" }]
}
}
}
}
],
"cases": [
{
"id": "viewer-cannot-delete",
"policyId": "projects",
"binding": {
"subject": { "type": "user", "id": "ada" },
"assignments": [
{
"subject": { "type": "user", "id": "ada" },
"role": "viewer",
"scope": { "resource": { "type": "project", "id": "q3_report" }, "appliesTo": "self" }
}
]
},
"resource": { "ref": { "type": "project", "id": "q3_report" }, "ancestors": [] },
"request": { "permission": "project:delete" },
"expect": { "allowed": false, "code": "NOT_GRANTED" }
}
]
} The runner is a script in the Rolebook repository, not part of an installed package. From a checkout,
after bun run build:
bun .github/scripts/rolebook-cli.ts test suite.json
bun .github/scripts/rolebook-cli.ts test --format json suite.json It validates the whole file first, then evaluates every case in order through the public engine API
(definePolicy, trustedResource, createAuthorizer, bind, check) and compares allowed and code.
| Exit code | Meaning |
|---|---|
0 | Every case ran once and matched. |
1 | Every case ran and at least one did not match. The report names each case and whether allowed, code, or both differed. |
2 | The run did not complete: an invalid command line, an unreadable or malformed file, an unsupported version, an engine fault, or the deadline (--timeout-ms, 30 seconds by default, at most 60). |
Bounds: one file holds 1 to 64 policies and 1 to 1,000 cases, is at most 4 MiB, and nests at most 32
levels. Every object is closed, so a misspelled key is an error and never ignored. request must not
contain a resource; the case’s resource wrapper supplies it. A script should check both the exit code
and the report’s status.
A passing suite shows the engine’s decision on the JSON you supplied. It does not show where those facts come from in production or that they are current. Keep secrets and real subject data out of identifiers and committed suites: identifiers appear in reports.
Debug a denial with explain
explain() returns the rules evaluated, in order, with the one that decided:
const explanation = authorization.explain({ permission: "project:delete", resource: project });
console.log(explanation.code); // "NOT_GRANTED"
console.table(explanation.trace.map(({ outcome, effect, role, permission }) => ({ outcome, effect, role, permission }))); An empty trace with a validation code (UNKNOWN_ROLE, INVALID_ASSIGNMENT, RESOURCE_MISMATCH,
INVALID_REQUEST, INVALID_SUBJECT) means the request never reached the rules: fix the input. See
evaluation order.
Test sharing without a database
createMemorySharingAdapter() and createMemoryPolicyStore() run the whole sharing module in memory. Share
one clock between the adapter and createSharing(), configure the eligibility fence from your test fixture,
and seed resources:
import { createMemorySharingAdapter, createSharing, defineSharing, type SharingClock } from "@rolebook/sharing";
import { trustedResource } from "rolebook";
let now = new Date("2025-01-01T00:00:00.000Z");
const clock: SharingClock = { now: () => now };
const members = new Set(["owner_1", "user_789"]);
const memory = createMemorySharingAdapter({
clock,
fenceEligibleSubjects: ({ subjects }) => subjects.every((subject) => members.has(subject.id)),
// The same answer as evidence for listing pages: membership here depends on no time.
readEligibleSubjects: ({ subjects }) => ({
eligible: subjects.every((subject) => members.has(subject.id)),
expiryDependencies: [],
}),
});
memory.seed({
tenantId: "ws_456",
resourceId: "project_1",
resource: trustedResource({ type: "project", id: "project_1" }, [{ type: "workspace", id: "ws_456" }]),
owner: { type: "user", id: "owner_1" },
});
const testSharing = createSharing({
definition: defineSharing({ policy, resources: { project: { ...definition.resources.project, adapter: memory } } }),
identity,
invitationTokens,
clock,
mutationBackoffMs: () => 0,
});
now = new Date("2025-01-02T00:00:00.000Z"); // move time for expiry tests The in-memory adapter takes no locks: use it for module behaviour, not for concurrency guarantees.
To test listAccessible() or listAccess() this way, the setup needs two more things, because each page
is read at one coherent point. An adapter with
fenceEligibleSubjects also needs readEligibleSubjects, as above. And the test’s identity adapter must
supply identity evidence. The simplest way in a fixture is
capturePagePrincipal({ tenantId, subject, evaluatedAt }), returning { principal, expiryDependencies }
synchronously from the fixture’s state; an adapter that implements resolvePagePrincipal with a real
revision qualifies as well. Without them a listing rejects with AccessListingUnavailableError and the
reason identity_evidence_missing, which is a setup problem and not an empty result. authorize(),
permissions(), and commands need neither.
Run the adapter contracts
If you write or configure a storage adapter, run the sharing testkit against it: the 38-case adapter contract, the teams contract when you use teams, and the policy contracts when you use versioned sharing. The PostgreSQL package runs the adapter contract against PGlite in memory, and the SQLite package against bun:sqlite; both add database-specific concurrency suites of their own.
Know what each run covers. PGlite is not the checked createPgExecutor(pool) executor and has no
consistent-page capability, so the PostgreSQL package’s PGlite run lists through a test-only stand-in for
page reads. It exercises the adapter’s reads and the listing scan; it says nothing about page consistency,
locking, or concurrency on a real server. Those are covered by separate suites that run against a real
PostgreSQL server, and against a file-backed SQLite database through the worker-backed executor. Do the
same for your own adapter: run the contracts on the database and the executor you deploy, and add tests for
your transactions, locks, and concurrent writers. A green run on a substitute database or a different
executor does not qualify the production configuration.
Test what you supply to the decision service and offline snapshots
The decision service and offline snapshots evaluate with the engine, so your policy tests above already cover the rules. What needs its own tests is the code you plug in, because neither component can check that the facts it is given are complete:
- Authority providers. Run each provider against its real source, with tenants that deliberately
reuse user, team, and resource IDs. Assert that it returns every assignment including denies and group
memberships, the complete ordered ancestry,
not_foundonly for confirmed absence, andunavailablewhen the source cannot be read. Add a negative test for each property: a provider that drops a deny must fail your suite. - Credential verifiers. Test expiry, audience, issuer, revocation, and that a malformed header never reaches a successful result.
- Callers. Test that your client treats a no-decision as a refusal to proceed and reports it as an
availability problem, separately from
EXPLICIT_DENYandNOT_GRANTED. - Offline hosts. Test the clock adapter against a set-back clock and a lost time anchor, and the state store against restore from backup and concurrent finalization. An in-memory counter or a plain file demonstrates the protocol; it does not qualify a host for enforcement.
Other implementations that read the same wire formats can check their JSON admission against the shared
byte fixtures exported as @rolebook/scalars-p1/fixtures/p1-v1.json. See the P1 input profile.
End to end
At the HTTP layer, test that each protected route returns 401 without a session, 403 for a denied subject, and the resource for an allowed one, using the real loaders. The checks inside are the same Rolebook calls your unit tests cover; the route tests prove the wiring: that the tenant, the subject, and the resource come from the session and the database, not from the request.