Current-state inspection
explain(): why one subject is or is not allowed an action right now, for privileged inspectors, rate limited and audited.
explain({ resource, action, subject?, field? }) tells a privileged inspector, such as a support
engineer or a workspace administrator, why one target subject is or is not allowed one configured action
on one resource right now, optionally on one concrete field. It answers with the single Rolebook decision
for that target, including the rule trace and the structured condition record, redacted to a fixed shape.
Inspection is off by default. Every call is bounded, rate limited by a limiter you supply, and recorded
by an audit sink you supply before any detail is returned. The answer is an explanation for a person to
read, never a permission: authorize with authorize().
explain is on TenantSharing, and it is also served over HTTP by @rolebook/server and called by
@rolebook/client and the Python SDK; see Over HTTP.
Enabling inspection
Pass inspection: { audit, limiter } to createSharing() or createVersionedSharing():
import {
createSharing,
type InspectionAuditEvent,
type InspectionAuditSink,
type InspectionLimiter,
} from "@rolebook/sharing";
// Your own token buckets and append-only log: Rolebook ships neither.
declare const buckets: {
take(key: string, signal: AbortSignal): Promise<boolean>;
done(key: string): void;
};
declare const inspectionLog: {
// Inserts keyed by event.inspectionId; inserting the same ID again is a no-op.
insertOnce(event: InspectionAuditEvent, signal: AbortSignal): Promise<void>;
};
const limiter: InspectionLimiter = {
// Called before Rolebook loads anything: apply tenant and actor limits here.
async acquire({ tenantId, actor, signal }) {
const actorKey = JSON.stringify([tenantId, actor.type, actor.id]);
if (!(await buckets.take(tenantId, signal)) || !(await buckets.take(actorKey, signal))) {
return { allowed: false };
}
return { allowed: true, release: () => buckets.done(actorKey) };
},
};
const audit: InspectionAuditSink = {
// Resolve only once the event is durably recorded.
async append(event, { signal }) {
await inspectionLog.insertOnce(event, signal);
},
};
const inspecting = createSharing({
definition,
identity,
invitationTokens,
inspection: { audit, limiter },
});
inspecting.inspectionEnabled; // true - Without
inspection, everyexplain()call answersINSPECTION_DISABLEDbefore it looks at its input, andinspectionEnabledisfalse. - With a valid configuration,
inspectionEnabledistrue. It is fixed for the instance’s lifetime. - When
inspectionis present but is not an object, oraudit.appendorlimiter.acquireis not a function,createSharing()throws aTypeErrorandcreateVersionedSharing()rejects with one. - The hooks are captured once at construction and called as methods of the objects you passed.
Calling explain
const support = { type: "user", id: "support_1" } as const;
const customer = { type: "user", id: "user_789" } as const;
const result = await inspecting
.forTenant({ tenantId, actor: support })
.explain({ resource: { type: "project", id: projectId }, action: "read", subject: customer });
if (result.ok) {
const { decision, policyDigest, sharingRevision, evaluatedAt } = result.explanation;
console.log(decision.allowed, decision.code, decision.matched?.role);
} else {
console.log(result.code); // for example "NOT_FOUND_OR_DENIED" or "RATE_LIMITED"
} The inspector is the actor the tenant handle is bound to. subject is the target whose decision is
explained; leave it out to explain the inspector’s own decision.
Who may inspect
The inspector must be allowed the resource type’s management.inspect permission, which defaults to
management.members (see defineSharing). It is the same
permission that gates describeAccess() and auditHistory().
- The permission is selected once from the configuration and checked once, resource-wide (with no field), on the inspector’s own binding.
- There is no fallback: when an explicit
inspectpermission is denied,membersis not tried. - Any valid answer other than
ALLOWED(an explicit deny, no grant, or a fault in the inspector’s own assignments, such as an unknown role) isNOT_FOUND_OR_DENIED. - A group can be neither the inspector nor the target.
The request
The input is bounded declarative data. It must be a plain object whose own enumerable data properties are exactly:
| Key | Required | Value |
|---|---|---|
resource | yes | { type, id } with no other key: a configured resource type and an opaque ID. |
action | yes | A configured action label of that resource type. |
subject | no | { type, id } with no other key. Defaults to the bound actor. |
field | no | One concrete Core field path: at most 512 characters and 16 dot-separated segments, each a letter followed by up to 127 letters, digits, _, or -. No wildcards, and no __proto__, prototype, or constructor segment. |
Anything else is INVALID_REQUEST, including:
- an unknown key, a symbol key, an accessor, or a non-enumerable property;
- an optional key present with the value
undefined; - an array, number, boolean, or
nullanywhere in the input, or an object with a non-plain prototype; - a Proxy whose trap throws;
- more than 8 KiB of serialized UTF-8 JSON, more than 32 values (objects and strings, the request itself included), or nesting deeper than 4 levels (the request object is level 1);
- an unknown resource type or action, or a malformed field.
A valid field that no rule allows is an explained denial, not INVALID_REQUEST. The caller cannot
supply context, assignments, groups, a timestamp, a revision, or a policy selection: every input to the
decision is read from your adapters.
What happens, in order
The stages always run in this order, and each failure stops the call with one fixed code:
- Enabled check. Without an
inspectionconfiguration:INSPECTION_DISABLED. The deadline starts right after this check. - Capture and validation. The input is copied once into a frozen request and validated against the
resource catalog:
INVALID_REQUEST. A handle bound to a malformed tenant or actor ID answersNOT_FOUND_OR_DENIEDhere. - Inspection ID. 128 fresh random bits.
- Instance slot. One of the instance’s 32 inspection slots, or
RATE_LIMITED. - Host limiter.
limiter.acquire(), orRATE_LIMITED. - Runtime, inspector, and resource. One runtime is pinned for the call. The identity adapter resolves the inspector, and the storage adapter reads the resource once, with every membership. That frozen state serves both the inspector’s and the target’s bindings.
- One clock reading. The sharing clock is read once, after the resource and the inspector are captured. Both bindings decide membership expiry at that instant.
- Inspection permission. The check described in who may inspect.
- Target. Only now is the target resolved. Nothing about it is read before the inspector is authorized, and when it is the inspector, the frozen inspector principal is reused.
- One evaluation. The target is evaluated exactly once, with Core
explain(request, { detail: "conditions" }).allowed,code, andmatchedcome from that one result, so without afieldthey match the Rolebook decisionauthorize()would reach for the target over the same state. - Serialization. The explanation is projected onto the redacted envelope.
- Audit.
audit.append()is called once, and the answer waits for it.
The explanation
A success is { ok: true, code: "EXPLAINED", explanation }, deeply frozen. explanation is an
InspectionEnvelope:
| Field | Meaning |
|---|---|
schema, version, mode | "rolebook-inspection", 1, "current-state". |
inspectionId | 128 random bits as 32 lowercase hex characters, new for every attempt. The audit event carries the same ID. |
evaluatedAt | Unix milliseconds of the single sharing-clock reading. |
resource, target, action, field? | The validated request. target is the bound actor when subject was left out. |
sharingRevision | The opaque sharing revision the resource state was read at. |
policyVersion? | The runtime’s evaluation version, present on a versioned instance. |
policyDigest | SHA-256 of the UTF-8 canonicalPolicyJson of the effective policy (custom roles included), as 64 lowercase hex characters. |
redactionVersion | 1. |
capture | { consistency: "captured-inputs" }; see what it does not guarantee. |
decision | allowed, code, permission, matched?, trace, traceTruncated, conditionTraceTruncated. |
decision.code is ALLOWED, EXPLICIT_DENY, or NOT_GRANTED. Each trace entry is
{ outcome, effect, role, permission, via?, details }, and details is Core’s DecisionTraceDetails
unchanged: the rule ID, the rule’s reason code, and the structured condition record with its logical
operators, partial trees, skipped children, and truncation flags exactly as Core returned them. See
decisions for how to read a Core trace. Rule IDs are local to policyDigest, not
durable grant IDs.
What is redacted
The envelope is built from exact key lists, so nothing else can pass through:
- Core’s free-text
reasonfields are dropped. - Nothing in the envelope or the audit event carries a
whereliteral, a field-pattern list, subject or resource attributes, context, an assignment list, an email, a token, or exception text. - When the serialized
EXPLAINEDresult would exceed 2 MiB, the answer isINSPECTION_UNAVAILABLE, never a shortened trace. The size never changes the decision.
Errors
A failure is { ok: false, code } with no message, cause, or partial trace.
code | When |
|---|---|
INVALID_REQUEST | The input is not the exact bounded shape above, names an unknown resource type or action, or has a malformed field. |
INSPECTION_DISABLED | The instance has no inspection configuration. |
NOT_FOUND_OR_DENIED | The resource is missing or in another tenant, the inspector is absent or ineligible, the bound context is malformed, the inspector’s own stored membership can no longer be bound (for example a retired custom role), or the inspector is not allowed the inspection permission. |
TARGET_UNAVAILABLE | The inspector was authorized, but the identity adapter reports the target absent or eligible: false. |
RATE_LIMITED | The limiter answered { allowed: false }, or 32 inspections are already running on this instance (the limiter is not called then). |
INSPECTION_UNAVAILABLE | Any operational fault: see below. |
NOT_FOUND_OR_DENIED is one answer for every one of its causes. An inspector who is not allowed the
inspection permission gets it whether or not the resource exists, so it reveals nothing, not even
existence.
INSPECTION_UNAVAILABLE covers:
- a limiter, identity, storage, or policy-store callback that throws, rejects, or returns a malformed result, including a limiter answer that is not exactly one of the two shapes;
- a principal, inspector or target, that resolves as another subject, in another tenant, or as a group;
- a resource state with a membership that does not decode (the module never evaluates a partial list);
- an invalid Core binding or decision code for the target (never reported as a denial), an inspector check whose answer is outside Core’s contract or whose binding throws, or Core’s internal fault reporter firing;
- a failing random source or clock;
- the 2 MiB ceiling;
- the 5,000 ms deadline, or a deadline timer that cannot be scheduled;
- an audit append that throws, rejects, does not return a promise, or resolves after the deadline.
The limiter
limiter.acquire({ tenantId, actor, inspectionId, signal }) is how the host rate limits inspection.
Rolebook enforces no rate of its own.
- It runs after the request is validated and an instance slot is taken, and before any runtime,
identity, storage, or target load. It is not called for
INVALID_REQUEST,INSPECTION_DISABLED, a malformed bound context, or a full instance. actoris the bound inspector, not yet authorized, so the limiter also counts attempts that will be denied. Apply both a tenant limit and an actor limit.- It must answer exactly
{ allowed: false }or{ allowed: true, release }: a plain object whose only own properties are those enumerable data properties, withreleasea function. Anything else, a throw, or a rejection isINSPECTION_UNAVAILABLE. releaseis called exactly once, as a method of that result, when the call’s work settles. That includes a lease granted after the deadline already answered the caller. It may return a promise; a throw or rejection is contained and never changes the result.signalaborts when the deadline passes.
A reasonable starting point is a token bucket of 20 attempts per minute per actor and 100 per minute per tenant, with bursts of the same size. A deployment with several instances needs a shared limiter, or must state that its limits are per instance.
The audit sink
After the inspector is authorized, and only while the deadline remains, audit.append(event, { signal })
is called exactly once: for an explanation, and also when the target turns out unavailable or the
evaluation fails. No detail is returned until it resolves, and the library never appends again for that
call.
appendmust record the event durably, and idempotently byinspectionId, before it resolves.- A rejected, throwing, or late append, or one that does not return a promise, is
INSPECTION_UNAVAILABLE. - An append can commit after its deadline has passed, so deduplicate by
inspectionId. Callers should not retry automatically. - Attempts that end before the inspector is authorized (
INVALID_REQUEST,INSPECTION_DISABLED,RATE_LIMITED,NOT_FOUND_OR_DENIED, and faults before authorization) produce no event, and neither does an authorized attempt whose deadline passes before the append. Log denials in your own security channel if you need them.
The event is an InspectionAuditEvent:
| Field | Value |
|---|---|
schema, version | "rolebook-inspection-audit", 1. |
inspectionId | The attempt’s ID, as in the envelope. |
tenantId, actor | The bound tenant and inspector. |
resource, target, action, field? | The validated request. |
evaluatedAt | The single sharing-clock reading. |
outcome | "explained", "target_unavailable", or "unavailable". |
allowed?, decisionCode? | The target decision’s allowed and code, only when outcome is "explained". |
policyDigest? | The effective policy digest. Optional in the type; the current implementation includes it on every event. |
redactionVersion | 1. |
The event never carries a trace, a fact, or a literal.
Concurrency and the deadline
- One instance runs at most 32 inspections at once, shared by every
forTenanthandle and, on a versioned instance, across policy refreshes. A call beyond that isRATE_LIMITEDwithout calling the limiter. - Each call has a 5,000 ms monotonic deadline that starts right after the enabled check. It is checked
after the synchronous capture and after every awaited stage. Once it has passed, no further stage
starts and the call answers
INSPECTION_UNAVAILABLE. A deadline timer also answers the caller when it fires, and from then on no stage starts, even if the monotonic clock has not yet reached 5,000 ms. - The
signalgiven to the limiter and the audit sink aborts at the deadline. Identity and storage reads take no signal and are not cancelled. - A call keeps its slot until its pending stage and its
releasesettle, even after the caller has been answered. A hook that ignores the abort therefore holds its slot, and 32 abandoned calls make further callsRATE_LIMITEDrather than piling up. - A synchronous Proxy trap or callback can still block the event loop, so the deadline is not a hard real-time bound.
What an explanation does not guarantee
captured-inputsis not a snapshot. The identity, policy, and storage reads happen one after another, each authoritative on its own, and their immutable combination is evaluated once. It is not a transaction-wide snapshot, not a freshness token, and not a guarantee that the decision still holds when the response arrives. Providers can change independently between reads, and a versioned instance keeps its existing refresh bounds. A later call reloads everything, so it sees a revocation.- It is never a permission. Do not use an explanation to authorize anything, and do not cache it as
a decision. Call
authorize()for that. - The digest identifies the policy, nothing else.
policyDigestnames the effective policy snapshot that was evaluated. It proves nothing about the facts your adapters supplied or about your identity and storage providers.
Over HTTP
@rolebook/server serves explain as POST {basePath}/v1/sharing.explain. It is
enabled only when the root’s inspectionEnabled is true when the handler is created, which is the case
for an instance created with inspection. The body is exactly the explain input; the tenant and the
inspector come from the server’s getContext, never from the body, and any other body key is refused.
| Library result | HTTP status | Body |
|---|---|---|
EXPLAINED | 200 | { "ok": true, "code": "EXPLAINED", "explanation": { ... } }, exactly as returned |
INVALID_REQUEST | 400 | { "error": { "code": "INVALID_REQUEST", "message": "Invalid request" } } |
INSPECTION_DISABLED, NOT_FOUND_OR_DENIED, TARGET_UNAVAILABLE | 404 | { "error": { "code": "NOT_FOUND_OR_DENIED", "message": "Not found or denied" } } |
RATE_LIMITED | 429 | { "error": { "code": "RATE_LIMITED", "message": "Rate limited" } } |
INSPECTION_UNAVAILABLE, or anything thrown | 503 | { "error": { "code": "INSPECTION_UNAVAILABLE", "message": "Inspection unavailable" } } |
- A disabled server, a private denial, and an unavailable target are one identical 404: status, body,
and headers. A disabled server answers it without reading the body and without calling the limiter,
the audit sink, or
explain. - The body may be at most 8 KiB; a longer one is the ordinary 413
PAYLOAD_TOO_LARGE, decided while reading and before parsing. - Every response of the operation carries
Cache-Control: no-store. No body, query, or exception text is logged or echoed.
@rolebook/client has explain(input), and the Python SDK has
client.explain(resource, action, subject=..., field=...). Both return the narrowed
HttpInspectionResult: the explanation, or
{ ok: false, code } with INVALID_REQUEST, NOT_FOUND_OR_DENIED, RATE_LIMITED, or
INSPECTION_UNAVAILABLE. Any other response, including a 404 or 200 body that is not exactly the
contract, raises the client’s ordinary error, and neither client retries an inspection. The Go and Rust
SDKs do not call sharing.explain yet.
Hand-built TenantSharing objects
explain is a required member of TenantSharing. Code that builds
a TenantSharing object by hand, such as a wrapper or a test double, instead of getting one from
forTenant() must add it and decide what it does:
- forward explicitly to the same bound tenant:
explain: (input) => tenant.explain(input); - or deliberately disable it:
explain: async () => ({ ok: false, code: "INSPECTION_DISABLED" }).
In a security-sensitive wrapper, list the methods it exposes one by one rather than spreading the
tenant object, so a method added later is not exposed before someone has reviewed it. Code that needs
only a few operations should depend on a narrower type, for example
Pick<TenantSharing<Resources>, "authorize">.
The required method makes such objects complete; it is not the security boundary. That remains the
inspection configuration, the permission check, the limiter and the audit sink.