RolebookDocs

Named authorized queries

Registered, filtered and sorted queries over your own resource table that return only the keys the actor is allowed, checked in one database snapshot.

listAccessible() pages through the resources sharing state can reach. A named authorized query instead filters and sorts your own resource table by columns you register, and returns only the resource keys the bound actor is allowed the query’s action on. Every candidate is checked by the canonical Sharing and Rolebook decision inside the page’s own database transaction: a row whose filter matched but whose check did not allow it is never returned.

A page returns { type, id } keys only, never application columns. Load what you show through your own tenant-scoped data path.

DatabaseFactoryExecutor it requires
PostgreSQLcreatePostgresAuthorizedQueries from @rolebook/sharing-postgrescreatePgExecutor(pool)
SQLite, Bun onlycreateSqliteAuthorizedQueries from @rolebook/sharing-sqlitecreateBunSqliteQueryExecutor() from @rolebook/sharing-sqlite/bun-query

Both factories take the adapter built with fencePolicy, the createVersionedSharing() instance whose policy store uses the adapter’s executor, and a resolver with resolveQueryPrincipalInTransaction, such as the local identity projection’s identity. The factories and their types come from the driver packages; @rolebook/sharing does not export them. The signatures are on the PostgreSQL and SQLite API pages.

This first delivery does not provide HTTP exposure, effective-subject or all-action queries, graph inheritance, ORM translation, application-column projection, multi-page frozen snapshots, remote identity or libSQL query profiles, or native UUID source keys.

Register queries

Queries are trusted server code, registered once at construction:

import type { SharingResourceConfigurations, VersionedResourceSharing } from "@rolebook/sharing";
import {
  createPostgresAuthorizedQueries,
  createPostgresLocalIdentityProjection,
  type PostgresSharingAdapter,
  type QueryDefinition,
} from "@rolebook/sharing-postgres";

// Built with fencePolicy on a createPgExecutor executor.
declare const adapter: PostgresSharingAdapter;
// Its policy store uses the same executor.
declare const sharing: VersionedResourceSharing<SharingResourceConfigurations>;
// A generated key from your secret store, the same on every instance.
declare const queryCursorKey: string;

const recentDocuments: QueryDefinition = {
  name: "recentDocuments",
  version: "v1",
  resourceType: "document",
  action: "read",
  schemaVersion: "s1",
  table: "document", // must equal the adapter's descriptor, unqualified
  tenantColumn: "tenant_id",
  idColumn: "id",
  filters: {
    status: { column: "status", type: "string", operators: ["eq", "in"], disclosable: true },
    archived: { column: "archived", type: "boolean", operators: ["eq", "isNull"], disclosable: true },
  },
  sort: { column: "rank", type: "integer", direction: "desc", nulls: "last", disclosable: true },
};

const queries = createPostgresAuthorizedQueries({
  adapter,
  sharing,
  identity: createPostgresLocalIdentityProjection({ table: "identity_projection" }).identity,
  queries: [recentDocuments],
  listingCursorKey: [queryCursorKey], // explicit: there is no random default
  environmentId: "orders-g1", // one logical dataset and cursor generation, see Cursors
});

A QueryDefinition names one resource type, one action and one table. Construction performs no database I/O and throws QueryConfigurationError (QUERY_CONFIGURATION_INVALID, a fixed message, no cause) for anything invalid or missing:

  • 1 to 64 queries with unique names, at most 16 filter names each, 64 KiB per definition and 1 MiB for the registry. Names, versions, schema versions, filter names and environmentId match [A-Za-z][A-Za-z0-9_-]{0,63}; resourceType and action must be configured in the sharing definition.
  • SQL identifiers are unqualified [A-Za-z_][A-Za-z0-9_]{0,62}, always quoted, never expressions, schema-qualified names or raw SQL. table, tenantColumn and idColumn must equal the adapter’s resource descriptor for that type.
  • Each filter’s operators is non-empty and unique. Range operators (gt, gte, lt, lte) are invalid for boolean. One column has one type across the filters, the sort and the key columns.
  • Every filter and the sort carry disclosable: true; a missing or false value is refused.
  • The adapter, the versioned sharing instance, its policy store and the executor must be the original first-party objects, with the adapter’s policy fence enforced for that same policy store, and the resolver must have resolveQueryPrincipalInTransaction.

listingCursorKey takes keys in the secret key form, one or up to eight. The definitions are captured at construction; changing the objects afterwards changes nothing.

disclosable is an attestation

disclosable: true is not a protection. Every subject who may run the query and receive this action’s resources may learn the filtered and sorted column values by inference, through which items a filter returns and in what order, including columns the subject could not otherwise read. Register a separate query (or action) where those audiences differ. Rolebook does not infer field permissions.

The source table and its indexes

The source table is your own table, in the same database as the sharing, identity and policy tables. Your migrations must guarantee its contract, because a page proves only what it reads:

  • Non-null tenant and ID columns with unique (tenant, id), and exactly one row per initialized resource of the type. A row without managed sharing state makes the page QUERY_UNAVAILABLE.
  • Every registered column stored as its declared type. Each fetched value is checked and nothing is coerced: a value outside the storage profile makes the page QUERY_UNAVAILABLE. Rows a filter excludes are never read, so they are never validated, and CHECK expressions are not proven.
  • IDs and strings follow the strict profile: at most 128 (IDs) or 512 (strings) UTF-16 units, valid Unicode, no C0 control character and no DEL.
Registered typePostgreSQL columnSQLite value
integersmallint, integer or bigint; a value outside the JavaScript safe-integer range is unavailable, never roundedan INTEGER in the safe-integer range
stringtext or varchar (not char(n)), compared under COLLATE "C" in a UTF8 databaseTEXT, compared under COLLATE BINARY in a UTF-8 database
booleanbooleanan INTEGER that is exactly 0 or 1
tenant and IDnon-null text or varchar; native uuid is not supportedTEXT NOT NULL

A page scans in one total order: a null rank (nulls first or last as declared), then the sort value in the declared direction, then the resource ID ascending in binary order whatever the direction. Strings compare in binary UTF-8 order, never a locale collation, and false sorts before true. Pagination is keyset over that exact tuple, never an offset.

Indexes are a deployment prerequisite for performance, never for correctness: a missing index changes neither the results nor the errors. Each query needs one index matching its tenant, sort and ID order with binary text collation. For recentDocuments above (rank, desc, nulls last) on PostgreSQL:

CREATE INDEX document_by_rank ON document (tenant_id COLLATE "C", rank DESC NULLS LAST, id COLLATE "C");

SQLite orders by an explicit null rank, (column IS NULL) for nulls last and (column IS NOT NULL) for nulls first, both ascending. For nulls: "last" with direction: "asc":

CREATE INDEX document_by_rank ON document (tenant_id, (rank IS NULL), rank, id);

For direction: "desc" declare the value column DESC (the null rank and the ID stay ascending); for nulls first use (rank IS NOT NULL). On PostgreSQL add COLLATE "C" to a string sort column; on SQLite add COLLATE BINARY to one declared with another collation. Index the registered filters your workload needs, and confirm with EXPLAIN (PostgreSQL) or EXPLAIN QUERY PLAN (SQLite, with no USE TEMP B-TREE FOR ORDER BY) that the page statement uses the index.

Run a page

Bind a tenant facade from your trusted server path, then page with nextCursor until exhausted:

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

// Your authenticated session: the tenant, the actor and a session or authority incarnation.
declare const session: {
  readonly tenantId: string;
  readonly userId: string;
  readonly authorityId: string;
};

const tenant = queries.forTenant({
  tenantId: session.tenantId,
  actor: { type: "user", id: session.userId },
  context: {},
  sessionBinding: session.authorityId,
});

const keys: ResourceKey[] = [];
let cursor: string | undefined;
for (;;) {
  const result = await tenant.query({
    name: "recentDocuments",
    filters: [
      { field: "status", op: "in", value: ["open", "review"] },
      { field: "archived", op: "eq", value: false },
    ],
    limit: 50,
    ...(cursor === undefined ? {} : { cursor }),
  });
  if (!result.ok) throw new Error(result.code); // see Errors below
  keys.push(...result.page.items);
  if (result.page.exhausted || result.page.nextCursor === undefined) break;
  cursor = result.page.nextCursor;
}

forTenant() captures the binding synchronously and throws QueryConfigurationError when it is invalid. tenantId and actor come from your authenticated request path. context is trusted plain JSON within Core’s context bounds (default {}), and may not set tenantId or sharingRevision. sessionBinding (1 to 128 UTF-16 units, no C0 control character or DEL) is your session or authority incarnation: it is bound into every cursor and never returned.

A request is { name, filters?, limit?, cursor? } with exactly those keys:

  • At most 16 KiB of UTF-8, depth 8 and 512 nodes. filters is a conjunction of at most 16 predicates, [] (match every tenant row) when omitted. A contradictory conjunction returns an empty exhausted page, not an error.
  • Each predicate is { field, op, value } over a registered filter and one of its operators. eq takes one non-null value, in 1 to 32 distinct values of one type, ranges an integer or a string, and isNull a boolean (false selects non-null values). Null never matches eq, in or a range. The same field may have several predicates; an exact duplicate is refused.
  • Strings are at most 512 UTF-16 units with no C0 control character, DEL or unpaired surrogate, integers are safe integers, and nothing is converted between types.
  • limit is an integer from 1 to 100 (default 25). It is not bound to the cursor and may change between pages.

Predicates are put in a canonical order, so reordering a conjunction or an in set produces the same cursor binding. No other equivalence is recognized.

Results

A result is either { ok: true, page } or { ok: false, code } (see QueryResult). A page has items, nextCursor (when not exhausted), exhausted, completion, evaluatedAt, queryVersion, schemaVersion, consistency: "local-snapshot" and traversal: "live".

  • items are the allowed keys in scan order, at most limit of them.
  • exhausted: true means the source proved it has nothing after the last candidate the page processed. Such a page has completion: "complete" and no nextCursor.
  • exhausted: false always comes with a nextCursor, even on an empty page: the scan stopped at the result limit or the candidate budget before it could prove the end. Continue with it; only an exhausted page ends the traversal.
  • completion: "budget_limited" means the 2,000-candidate budget stopped the page before it reached limit results or the end. completion: "complete" means it stopped on the result limit or the end.
  • nextCursor resumes after the last candidate the page processed, allowed or not, never after the last row it fetched, so no candidate is skipped.
  • evaluatedAt is the page’s database time in epoch milliseconds. queryVersion and schemaVersion echo the registration.

There are no totals, counts, denied IDs, matched rules, facts or raw filter and sort values in a result, and an error never echoes a value.

Errors

query() never throws for an operational failure. Every failure is one of four fixed codes, with no detail and no partial page:

codeWhen
INVALID_REQUESTThe request is not a plain object of exactly the request keys, exceeds a bound, names an unknown query, filter or operator, has a value of the wrong type, a duplicate predicate or an invalid limit, or has a cursor that is not a string.
INVALID_CURSORThe cursor does not open: malformed, truncated or tampered, sealed for another environment, tenant or actor, under a key no longer configured, or in another format such as a listing cursor. Also an authenticated payload that is not a valid named-query cursor, or whose position does not fit the selected query’s sort type.
CURSOR_STALE_RESTARTThe cursor is genuine but no longer applies: another query name, a changed query definition or version, another filter set, context or session binding, a changed effective policy (including a tenant custom role), or a lease that has expired or was issued later than this page’s database time. Start again without a cursor.
QUERY_UNAVAILABLEThe page could not be answered completely: the deadline passed, the factory is closing or already has 32 pages in flight, a connection or lease was not available, a serialization failure, schema drift or a value outside the storage profile, a source row without managed sharing state, an ineligible or expired actor, a check Core cannot make for the actor, or any other fault. A candidate the check denies is skipped, never a failure.

The request is validated first, then the cursor: its syntax, authentication and payload, then its fit with the query, filters, context and session binding. All of that happens before anything reaches the database, so a bad cursor is never sent to it. The cursor’s policy and lease checks run inside the page transaction, after the policy is selected and before the actor is resolved. When several problems coexist, the first check that fails decides the code.

Cursors

A nextCursor is sealed with the same AES-256-GCM cursor engine as listing cursors, under its own format, rolebook/named-query/v1, with a key derived for that format alone. Treat it as opaque.

  • Every cursor is 10,980 characters whatever its position, so its length reveals nothing about denied candidates.
  • It is bound to the environment, tenant and actor (a mismatch is INVALID_CURSOR), and to the query, the normalized filters, the context, the session binding and the effective policy (a mismatch is CURSOR_STALE_RESTART). A policy change that only relabels the version does not stale it. A grant, a revocation or an expiry does not restart a traversal either: identity is resolved anew on every page.
  • Each cursor is a 15-minute lease from its page’s database time. The next page compares it with its own database time, and a cursor issued later than that is stale too, so the database clocks that serve one traversal must agree. Every returned cursor gets a fresh lease; an old one is never extended.
  • listingCursorKey is a list: the first key seals, every key opens. To rotate, add the new key to every instance before any instance seals with it, then put it first, and keep the old key in the list for at least 15 minutes plus your clock skew. A cursor sealed under a removed key is INVALID_CURSOR.
  • After a session security change, change sessionBinding to invalidate the session’s cursors. The current identity is checked on every page regardless.

The continuation domain: environmentId

environmentId is part of every cursor’s authenticated data, together with the tenant and the actor. It names one logical dataset and one generation of continuation, not merely a deployment stage: factories that share the value and a key open each other’s cursors, whichever first-party driver serves them.

  • Keep the same environmentId and keys across a driver switch, for example SQLite to PostgreSQL, only when existing cursors are meant to continue. Change it after a restore, a reseed or a cutover that should invalidate them. Removing a key from listingCursorKey also invalidates every cursor sealed under it.
  • The codes do not change. Another environment, a key that is no longer listed, another tenant or another actor is INVALID_CURSOR, decided before any database work. An authenticated cursor whose query, filters, context, session binding or profile no longer match is CURSOR_STALE_RESTART, also before any database work; one whose effective policy no longer matches, whose lease has expired, or that was issued later than the page’s database time is CURSOR_STALE_RESTART from inside the page transaction, so the databases that serve one traversal need clocks that agree.
  • environmentId is not checked against anything in the database. It is the operator’s statement that two deployments hold the same logical dataset: two unrelated databases configured with the same value and keys accept each other’s cursors. Every page is authorized again, so the consequence is a wrong starting position, never a grant.
  • Matching digests establish compatible definitions, not identical data. Both drivers use the same sql-binary-v1 order, so a page resumed on the other driver starts after the cursor’s position; this is the same live traversal over independent snapshots, with no replication consistency and no frozen result set.

Provisioning and rotation. Choose one environmentId per logical dataset and generation, and give it and the same listingCursorKey list to every instance that should continue the others’ cursors. To rotate a key, add the new key to every instance, then list it first, and keep the old key listed for at least the 15-minute cursor lease plus your clock-skew allowance.

What a page guarantees

  • Local snapshot (consistency: "local-snapshot"). Everything a page reads from the database, policy, identity, candidates, memberships, ownership and resources, and every check share one transaction snapshot and one database evaluatedAt, which governs every expiry. The trusted context and sessionBinding you pass are application facts, not database state: context used for authority must come from your own trusted request path, and copying it into a request gives it no freshness. There is no claim about remote identity providers.
  • Live traversal (traversal: "live"). Pages are independent snapshots. Inserts, deletes and changed sort values between pages can repeat or omit items across a traversal; no multi-page snapshot is promised. Every returned item was allowed at its own page’s snapshot, not later.
  • Whole pages only. A page that cannot be checked completely fails as a whole and never returns a partial result. A candidate is returned only when the canonical check allows it. It is skipped when the check denies it (an explicit deny or no grant) or when no binding can be built from its stored state, such as a membership whose role is no longer mapped (a retired custom role): that is the canonical denial, exactly as authorize() denies the resource and listAccessible() skips it. A check Core cannot make for the actor (an assignment with an unknown or mis-scoped role), an answer outside Core’s valid decisions, a malformed or out-of-order candidate, or a missing resource makes the page QUERY_UNAVAILABLE, never an empty or shortened page. An ineligible actor is QUERY_UNAVAILABLE too, not an empty page.

Bounds

  • Deadline. A page ends within 2,000 ms of a monotonic clock that starts before request validation, so validation, hashing, connection acquisition, the transaction, every read and check and cursor sealing all count. When it passes, the page answers QUERY_UNAVAILABLE at once and no result is produced afterwards. No deadline here is a hard real-time guarantee.
  • Candidate budget. A page checks at most 2,000 candidates, fetched in batches of at most 200, and stops at once at the result limit or the budget.
  • Pages in flight. At most 32 pages per factory, including pages whose caller already received QUERY_UNAVAILABLE but whose connection has not settled yet. A page beyond that is QUERY_UNAVAILABLE; nothing waits in a queue.
  • No retries. A timeout, a serialization failure or a busy connection is never retried.
  • close() rejects new requests, ends the pages in flight and waits up to 1,000 ms for them to settle, else rejects with QueryCloseError (QUERY_CLOSE_FAILED); a later call waits on the same cleanup again.

PostgreSQL

  • The adapter and the policy store use one original createPgExecutor(pool) executor. A page is one SERIALIZABLE READ ONLY transaction on one pool connection; pool acquisition counts against the deadline, and a connection that arrives late is discarded without BEGIN.
  • Before each statement the page sets statement_timeout and lock_timeout to the milliseconds left. A statement that ignores cancellation keeps its page slot and connection until it settles; the connection is then rolled back and discarded, never returned to the pool clean.
  • A page runs no DML or DDL. close() never closes your pool.
  • Tenant and ID columns must be text or varchar. Native uuid source keys are not supported by this first profile: an adapter with resourceSqlType: "uuid" is refused at construction, and a column found to be another type at page time makes the page QUERY_UNAVAILABLE.
  • The database must be UTF8, and the source must be an ordinary or partitioned table.

SQLite

  • Bun only. The adapter must be built on an executor from createBunSqliteQueryExecutor() (checked by provenance, not by shape), and the same executor object must build the adapter, the policy store and the query factory. createBunSqliteExecutor(), createLibsqlExecutor() and every other executor are refused for this API, because a synchronous SQLite call cannot be interrupted by a deadline; their other uses are unchanged.
  • The database file must already be UTF-8 and in WAL mode; the worker executor checks both and never converts a file.
  • A page is one query lease of the executor: a read-only BEGIN DEFERRED transaction on one worker connection, whose file snapshot is opened by SELECT 1 FROM main.sqlite_schema LIMIT 1 before the page reads anything, then the database clock is read. It never commits. The table is always read from main.
  • A page never waits for a connection: when every connection of the executor is leased or busy, the page is QUERY_UNAVAILABLE. With less than 1 ms of the deadline left it does not ask for a lease.
  • A running SQLite statement cannot be interrupted. When the deadline passes the page answers at once and the executor terminates the worker that owns its connection, but that connection slot stays occupied until the statement returns and the worker’s exit is confirmed; a replacement starts only then, when work needs one.
  • queries.close() drains this factory’s pages and never closes the executor; executor.close() at shutdown owns the workers.
  • The same executor can also serve the SQLite protected-write adapter. A protected write is ordinary work: it waits for a free connection in arrival order and holds its worker from BEGIN IMMEDIATE to the end of its COMMIT, while a page never waits. Long protected writes can therefore make pages QUERY_UNAVAILABLE: size maxConnections for the writes and other work you expect at once plus the pages that must still be answered, and keep protected callbacks short. A page whose lease opened before a protected write committed on another worker keeps its snapshot and does not see that write; a page that starts after the commit does.
import type { SharingResourceConfigurations, VersionedResourceSharing } from "@rolebook/sharing";
import {
  createSqliteAuthorizedQueries,
  createSqliteLocalIdentityProjection,
  type QueryDefinition,
  type SqliteSharingAdapter,
} from "@rolebook/sharing-sqlite";
import { createBunSqliteQueryExecutor } from "@rolebook/sharing-sqlite/bun-query";

// One executor object for the adapter, the policy store and the query factory.
const executor = createBunSqliteQueryExecutor({ filename: "/var/lib/app/app.db", maxConnections: 4 });
// Built with createSqliteSharingAdapter({ executor, fencePolicy, ... }).
declare const adapter: SqliteSharingAdapter;
// Its policy store is createSqlitePolicyStore({ executor }).
declare const sharing: VersionedResourceSharing<SharingResourceConfigurations>;
declare const recentDocuments: QueryDefinition;
declare const queryCursorKey: string;

const queries = createSqliteAuthorizedQueries({
  adapter,
  sharing,
  identity: createSqliteLocalIdentityProjection({ table: "identity_projection" }).identity,
  queries: [recentDocuments],
  listingCursorKey: [queryCursorKey],
  environmentId: "orders-g1",
});

// At shutdown:
await queries.close(); // drains this factory's pages
await executor.close(); // terminates the workers

The worker executor itself is described under createBunSqliteQueryExecutor.