Inherited access
Let documents inherit access from their folder chain, with PostgreSQL or SQLite, opt-in per type and bounded.
By default every shared resource is decided on its own memberships. With inherited access, a
membership stored on a folder also applies to everything below it in the folder chain: grant Alice
editor on a folder and she can edit its documents and subfolders, at any depth up to the bound.
Inheritance is opt-in per resource type, served only by the first-party PostgreSQL and SQLite
adapters, and only for a tenant whose hierarchy has been enrolled and activated. An application that
does not opt in is unchanged.
What inherits
- A membership stored on an ancestor applies at that ancestor’s scope (
descendants), through the ancestor type’s configured member role. A role’s rules decide what reaches the descendant: a folder role needs a rule such asdocument:readto grant anything on a document. - Ownership never inherits. A folder’s owner gains nothing over its contents from ownership.
- Deny wins. A deny on an ancestor applies to every descendant, and an explicit deny on the
descendant itself wins over an inherited allow. The owner’s recovery (
revokeMemberandchangeRoleby the resource’s own owner) leaves out only memberships stored on the resource itself; an ancestor’s deny still binds the owner. - Expiry is judged at every scope with one instant per read. An expired ancestor membership, allow or deny, contributes nothing.
- Teams. A team’s membership on an ancestor applies to the team’s members, as on the resource itself.
The chain is read from the managed hierarchy relation in the same snapshot as the decision. The
ancestors your resource descriptor returns are not used for an enrolled tenant.
Bounds and what is not supported
- Depth: at most 16 ancestors (17 resources counting the target). A structure command refuses a placement that would exceed it, and a stored chain that exceeds it is refused, never shortened.
- Fail closed: a missing, repeated, cyclic or cross-tenant chain row, a quarantined tenant, a
stale policy or configuration generation, or an unusable local identity answers
HierarchyUnavailableError(HTTP 503HIERARCHY_UNAVAILABLE) with a typedreason. Nothing falls back to a flat decision. - Adapters: the memory adapter and custom adapters have no inherited read;
defineSharingrefusesinheritanceon them. - Flat tenants: an opted-in type is never served on a tenant that is not enrolled. Once a
Sharing instance is built from a definition that opts it in, every path refuses it there by type,
before any lookup, replay, journal read or candidate scan: single reads,
describeAccess, both listings, commands and protected writes thrownot_enrolled; named queries answerQUERY_UNAVAILABLE, governed callsUNAVAILABLEandexplainINSPECTION_UNAVAILABLE. Lifecycle writers that initialize, delete or move a resource are not refused. This holds whatever policy is active (recursion published later, or turned off) and whether or notenable…InheritedReadswas called: on a flat tenant nothing proves a chain complete, or that a resource presented as a root is one. Enroll a tenant before it uses these types; keep types that must serve flat tenants out of the opt-in. This is deliberately stricter than thesharing.inheritance/1contract, which lets types that do not reach a recursive type keep their flat contract. - Decide before launch: opting in a type that already has resources stops service for every tenant that holds them: those tenants are not enrolled, and existing resources cannot be adopted into the hierarchy yet. Decide whether a type uses inheritance before it stores data.
- Storage serves one kind: a Sharing instance claims each first-party adapter’s storage (its
executor and tables, not the adapter object) when it is constructed: inheriting for opted-in
types, flat otherwise. Defining alone claims nothing, so a definition that fails or is discarded
changes nothing. In a process, a storage serves inherited or flat access, not both: an instance
whose claim conflicts with an earlier one throws at construction, whichever adapter object it
uses, and
enable…InheritedReadsrefuses storage already claimed flat. A definition that uses one storage for both kinds throws before claiming anything. The claim lasts for the process and is keyed by the executor object and the tables: two executors over one database, and other processes, are separate storages, so give every process the same definition. When a definition opts a type in, protected writers accept only the evaluating definition’s own adapter for their type. - One control profile, inheriting types only: every inheriting type uses one hierarchy control
profile, the bootstrap provider’s, and
enable…InheritedReadsrefuses a definition that also holds a non-inheriting type on a first-party adapter of the same engine. Put flat types in their own Sharing definition and instance, with their own control prefix. - Existing resources are not adopted: after the actor is authorized,
enrollandactivateanswerunlinked_resources, before changing tenant state, while the tenant has a row of an inheriting type that the managed hierarchy does not place. The check runs on the control transaction, which holds the tenant’s hierarchy barrier exclusively (on SQLite also the database write lock); Sharing takes no lock on your application tables. Enroll a tenant before it has such resources; migrating an existing tenant means recreating its resources throughstructure.createin a new tenant. - Create rows and initialize them in one transaction: for an inheriting type, insert the
application row and initialize it in the same transaction (
withLifecycleTransactionwithinitializeResourceInTransactionwhile the tenant is flat,structure.createonce it is enrolled). Initialization takes the tenant barrier, so it either commits beforeenrollreads the tenant (andenrollanswersunlinked_resources) or is refused after it and rolls the row back. Inserting the row in one transaction and initializing it in another is not supported for inheriting types: a row committed whileenrolloractivateruns may be missed, and its later initialization is refused on the enrolled tenant (or, if it committed while the tenant was still flat, it holds an owner row the hierarchy does not place). The nextactivateanswersunlinked_resources. To recover, delete the application row. If a read has since quarantined the tenant,activaterefusesquarantined: callreleaseQuarantinewhile it answersverifying. When it answersreleasedwith stateactivethe tenant is back. With statebuilding, callactivate(it binds the current policy and roles, and answersinventory_incomplete), run the inventory to completion, and callactivateagain; the inventory alone does not advance if the policy or the tenant’s roles changed while the tenant was quarantined. - Governed sharing is not supported with inherited access: the governance attachment’s
admission does not carry the Sharing definition’s inheritance binding. On an enrolled tenant every
governed operation (request, approve, reject, cancel, apply, resolve) answers
UNAVAILABLEbefore any governance state is read or written, on PostgreSQL and SQLite alike; internally the refusal is the tenant’s lifecycle reason when it is notactive,policy_incompatibleotherwise. On a flat tenant an opted-in type refuses the same way (above). - Reconfiguration (known operational limit): after a policy publish or a change to a tenant’s
custom roles, the tenant must be activated again, and activation refuses while a stored
membership on an inheriting scope carries an allow that reaches further; while the tenant is not
activeits membership writes are refused too. A role reaches when it allows any permission of an inheriting type that can lie below its scope; for a recursive type that includes the type itself (folder:readon a folder reaches its child folders). To recover a tenant holding such grants: (1) publish a policy, or edit the custom role, so that the stored grants allow nothing on an inheriting type (a custom role may keep only denies); (2) callactivate, run the inventory to completion, and callactivateagain; (3) revoke every stored grant that will reach under the intended policy or role, whoever holds it (one left behind blocks step 5, and its revocation is then refused too), and record the ones to restore; (4) publish the intended policy, or edit the custom role back; (5) activate as in step 2; (6) grant the recorded ones again. Edit a reaching custom role; do not retire it: a membership whose role is retired cannot be revoked (unknown_role) and a retired role name cannot be reused. Plan configuration changes with this sequence; there is no bypass. - Configuration changes: the configuration generation binds the command map, the opted-in
types and each type’s member and ownership roles, public actions and management permissions
(tenant custom roles are bound by the tenant’s role revision instead). Changing any of them, publishing a policy, or changing a tenant’s custom
roles invalidates the activation, and inherited reads and membership writes refuse
(
policy_incompatible) until the tenant is activated again:activatere-entersbuilding, the inventory runs, andactivatecompletes. Activation still refuses while a stored membership on an inheriting scope carries an allow that reaches further, and while the tenant is notactiveits membership writes are refused too, so such a grant cannot be removed then. Remove reaching grants through the ordinary commands before changing the configuration, then re-activate and grant again. A definition that disagrees with the one the adapters were enabled with is refused the same way, on single reads, listings (empty or not), commands and their replays. Adding or removing an inheriting type for an activated tenant is not supported:activaterefuses it with aHierarchyUnavailableError(usuallypolicy_incompatible; a profile check may answer first) and leaves the admission and its progress unchanged. A membership command under a mismatched definition is refusedpolicy_incompatiblebefore the tenant’s lifecycle state is considered, so abuildingtenant answerspolicy_incompatiblerather thanbuildingto it. A protected write checks the lifecycle state first and may answerbuilding; it reaches neither its journal nor its target either way. - Identity: an enrolled tenant’s reads resolve the actor from the complete local identity
projection (
createPostgresLocalIdentityProjectionorcreateSqliteLocalIdentityProjection) in the read transaction. The generic identity adapter is not consulted. Every inheriting adapter must be created withpageIdentity, whosesourceis the identity adapter the Sharing instance uses: an enabled adapter always resolves page identity in the snapshot, so a page from an instance with another identity adapter is refused (identity_evidence_missing). - Ancestors must exist: every ancestor’s Sharing owner row is checked in the read’s snapshot.
The owner row references the application row with a cascading foreign key, so this proves the
resource exists; on SQLite that holds only while
foreign_keysis on for every connection that writes the application tables. Every stored subtree height must also satisfy the writers’ rules (in range, above the link below, room for the depth above). A surviving link to a deleted resource is refused. - Listings:
listAccessible()andlistAccess()include inherited access exactly as single checks decide it. They need strict pages: the PostgreSQL adapter, or the SQLite worker executor (createBunSqliteQueryExecutor). Without them they refuse withcapability_missing, as for flat tenants. describeAccess()adds aninheritedsection. Inspection is decided first on the actor’s own read, so an actor without access learns nothing. An allowed inspector’s read then covers every subject’s memberships on the chain, bounded at 4096 rows; a larger chain answersbudget_exhausted, never a shorter list. Direct members and inherited ones are judged at the same instant, and pending invitations are fenced against a move or a sharing change after the read. The section lists every live membership on every ancestor, so an inspector of a document sees who holds roles on its folders, including roles whose rules do not reach the document; restrictmanagement.inspectaccordingly. A retired custom role on an ancestor is listed withroleUnavailable: trueand grants nothing.- Not yet supported on an enrolled tenant:
explain(privileged inspection) does not read the managed hierarchy, so it never answers from a flat read there; it fails closed with its fixed unavailable outcome. The HTTPsharing.describeAccessoperation answers 503HIERARCHY_UNAVAILABLE(enrolled) where it would return an inherited description, as before inherited reads were public, because the wire has no inherited section yet; an absent target or an actor who may not inspect still gets the ordinaryNOT_FOUND_OR_DENIEDanswer (HTTP 200). Ownership transfer at an inheriting scope answersINHERITED_SCOPE_UNSUPPORTED.auditHistory()andpreviewImpact()refuse withHierarchyUnavailableError(enrolled).
Enabling it
The example uses SQLite; PostgreSQL has the same functions with a Postgres prefix
(enablePostgresInheritedReads, createPostgresHierarchyControl, runPostgresHierarchyInventory,
createPostgresBootstrapIntegrity).
- Policy. Declare the bootstrap type that authorizes tenant-level hierarchy actions, a recursive folder type, and documents below folders.
- Configuration. Set
inheritance: "ancestors"on every inheriting type, and give each one hierarchy commands (who may create, move and delete). - Storage. Run the resource migrations (they install the hierarchy control relations), the policy store migrations, and the policy catalog registration for the control profile. Keep a bootstrap row per tenant in an application table and a local identity projection table.
- Wire it. Compute the configuration generation, enable inherited reads on the adapters, create the versioned Sharing instance, then the hierarchy control facade.
- Per tenant. An actor allowed the bootstrap actions enrolls the tenant, an operator job runs
the activation inventory to completion, and the actor activates it. Then place resources with
structure.createandstructure.move.
import {
createHmacInvitationTokens,
createVersionedSharing,
defineSharing,
type HierarchyCommandsInput,
hierarchyConfigurationGeneration,
type TenantIdentityAdapter,
} from "@rolebook/sharing";
import {
createSqliteBootstrapIntegrity,
createSqliteHierarchyControl,
createSqliteLocalIdentityProjection,
createSqlitePolicyFence,
createSqlitePolicyStore,
createSqliteSharingAdapter,
enableSqliteInheritedReads,
hierarchyControlTables,
type ParameterizedSqliteExecutor,
runSqliteHierarchyInventory,
type SqliteResourceDescriptor,
} from "@rolebook/sharing-sqlite";
import { definePolicy } from "rolebook";
declare const executor: ParameterizedSqliteExecutor;
declare const identity: TenantIdentityAdapter;
declare const folderDescriptor: SqliteResourceDescriptor;
declare const documentDescriptor: SqliteResourceDescriptor;
declare const invitationKey: string;
const policy = definePolicy({
resources: {
tenant_admin: {
actions: ["root_create", "root_place", "enroll", "activate", "release", "repair"],
},
folder: {
recursive: true,
actions: ["read", "manage", "create", "add", "remove", "delete", "move"],
},
document: { parent: "folder", actions: ["read", "edit", "manage", "delete", "move"] },
},
roles: {
tenant_operator: {
scope: "tenant_admin",
rules: [{ effect: "allow", permission: "tenant_admin:*" }],
},
folder_owner: {
scope: "folder",
rules: [
{ effect: "allow", permission: "folder:*" },
{ effect: "allow", permission: "document:*" },
],
},
folder_editor: {
scope: "folder",
rules: [
{ effect: "allow", permission: "folder:read" },
{ effect: "allow", permission: "document:read" },
{ effect: "allow", permission: "document:edit" },
],
},
document_owner: {
scope: "document",
rules: [{ effect: "allow", permission: "document:*" }],
},
document_viewer: {
scope: "document",
rules: [{ effect: "allow", permission: "document:read" }],
},
},
});
const projection = createSqliteLocalIdentityProjection({ table: "identity_projection" });
const adapter = (resource: SqliteResourceDescriptor) =>
createSqliteSharingAdapter({
executor,
resource,
lockEligibleSubjects: projection.lockEligibleSubjects,
fencePolicy: createSqlitePolicyFence(),
pageIdentity: { source: identity, resolver: projection.identity },
});
const definition = defineSharing({
policy,
resources: {
folder: {
adapter: adapter(folderDescriptor),
memberRoles: { editor: "folder_editor" },
ownershipRole: "folder_owner",
actions: { read: "folder:read" },
management: { members: "folder:manage", invitations: "folder:manage", ownership: "folder:manage" },
inheritance: "ancestors",
},
document: {
adapter: adapter(documentDescriptor),
memberRoles: { viewer: "document_viewer" },
ownershipRole: "document_owner",
actions: { read: "document:read", edit: "document:edit" },
management: {
members: "document:manage",
invitations: "document:manage",
ownership: "document:manage",
},
inheritance: "ancestors",
},
},
});
const commands: HierarchyCommandsInput = {
bootstrap: {
type: "tenant_admin",
actions: {
rootCreate: "tenant_admin:root_create",
rootPlacement: "tenant_admin:root_place",
enrollment: "tenant_admin:enroll",
activation: "tenant_admin:activate",
quarantineRelease: "tenant_admin:release",
heightRepair: "tenant_admin:repair",
},
},
types: {
folder: {
delete: "folder:delete",
move: "folder:move",
createChild: "folder:create",
addChild: "folder:add",
removeChild: "folder:remove",
},
document: { delete: "document:delete", move: "document:move" },
},
};
// One provider per control profile: the application table holding each tenant's bootstrap row.
const bootstrap = createSqliteBootstrapIntegrity({
controlPrefix: hierarchyControlTables().prefix,
policyStore: { tablePrefix: "rolebook" },
descriptor: {
resourceType: "tenant_admin",
table: "tenant_admin",
tenantColumn: "workspace_id",
idColumn: "id",
versionColumn: "version",
incarnationColumn: "incarnation",
},
});
const configurationGeneration = hierarchyConfigurationGeneration({
label: "inherit-1",
definition,
commands,
});
enableSqliteInheritedReads({
definition,
commands,
configurationGeneration,
authorityEpoch: "epoch-1",
identity: projection,
bootstrap,
});
const sharing = await createVersionedSharing({
definition,
identity,
invitationTokens: createHmacInvitationTokens(invitationKey),
policyStore: createSqlitePolicyStore({ executor }),
});
const control = createSqliteHierarchyControl({
sharing,
policy,
commands,
bootstrap,
authorityEpoch: "epoch-1",
configurationGeneration,
});
// Per tenant, by an actor the policy allows the bootstrap actions.
const operator = control.forTenant({ tenantId: "t1", actor: { type: "user", id: "admin" } });
const enrolled = await operator.enroll({ idempotencyKey: "enroll-t1" });
if (enrolled.status !== "enrolled" && enrolled.status !== "already_enrolled")
throw new Error(`enroll: ${enrolled.status}`);
// Bounded batches: retry only while the inventory reports progress.
let inventory = await runSqliteHierarchyInventory(control, "t1");
for (let batch = 0; inventory.status === "progress" && batch < 1000; batch += 1)
inventory = await runSqliteHierarchyInventory(control, "t1");
if (inventory.status !== "complete") throw new Error(`inventory: ${inventory.status}`);
const activated = await operator.activate({ idempotencyKey: "activate-t1" });
if (activated.status !== "activated") throw new Error(`activate: ${activated.status}`); Activation is an authority change: it refuses while any stored membership on a would-be inheriting scope carries an allow that would reach further, so activate before granting on folders. (On a tenant that is not enrolled, opted-in types refuse every command, so there are no such grants to remove there.) Any later policy or configuration generation change makes inherited reads unavailable until the tenant is activated again.
Once active, grants on folders go through the ordinary execute commands, and describeAccess()
shows where inherited access comes from:
const described = await sharing
.forTenant({ tenantId: "t1", actor })
.describeAccess({ resource: { type: "document", id: "d1" } });
// described.access.inherited:
// [{ from: { type: "folder", id: "f1" }, depth: 1, subject: { type: "user", id: "alice" }, role: "editor" }] Testing an adapter
@rolebook/sharing-testkit exports sharingInheritanceContract(factory): inherit from a parent and
from a deeper ancestor, revoke on the parent, an explicit deny on the child, a move to another
parent, expiry of the parent membership, a cross-tenant ancestor, a cyclic chain and an over-deep
chain, and listing parity. The PostgreSQL and SQLite adapters run it; the memory adapter runs
sharingInheritanceRefusalContract, which checks that it refuses the option.