Skip to content

Permissions ​

The permission model is kernel-owned — it is enforcement input, never delegated to an auth provider. The evaluation engine is an adapter behind one interface, with a built-in relationship-tuple engine as the default.

The authored surface ​

Humans (and agents, under review) write three kinds of things:

Permission keys ​

Module-namespaced strings declared in the manifest with human-readable descriptions:

workorder:create   Create work orders
workorder:report   Start work, report time and material
invoicing:export   Export an invoice basis (makes it immutable)

A key that only the platform's own principals may hold says so where it is declared, with holder: 'system':

ts
permissions: [
  { key: 'assistant:use', description: 'Open and read your own threads' },
  { key: 'assistant:run', description: "Write the assistant's side of a thread", holder: 'system' },
],

A vertical built from its model reserves a key of its own the same way, in manifestOperations: { 'list:reap': { description: 'Reap abandoned lists', holder: 'system' } } in place of the plain description.

Such a key is never given to a person. lint:permissions refuses it in any role a person can hold and in any entity grant shape. It may appear only in a schedule's or a peer's permissions, or in a role declared holder: 'system'. A vertical that composes the engine inherits the reservation with the manifest, and the permission snapshot marks the key so that removing holder: 'system' shows in the reviewed diff. Leave holder out and the key may be held by anyone it is granted to, which is what every key meant before the field.

Past the lint ​

substrat push refuses the same things before anything is uploaded, and words the refusal the way the lint does:

  • a role or shape holding a reserved key;
  • an owner grant holding one: a module's ownerGrants, or your package's substrat.ownerGrants.

The registry a push ships marks each reserved key, and each system-held role, with holder: 'system'. The platform refuses a push whose registry rows mark a key that a role, a shape or the owner grants hold. The deploy manifest also carries each loaded module's permission declarations (modules: [{ id, permissions, ownerGrants? }]). At publish, the platform derives the key rows from those declarations and refuses a registry that disagrees about its keys, descriptions, declaring modules or holder marks. A CLI too old to send modules remains accepted without this consistency check; its registry is still checked by the older row rules. This check compares two claims shipped by the same builder. The next step of #2446 will verify known engine manifests against a platform catalog; third-party modules remain author-asserted.

At runtime, a host reads the reservations off the modules it registers and the modules its permissions lists, and refuses at these doors:

  • Inviting someone into a role that carries a reserved key is refused. So is moving them into one, and so is a membership request for one. canAssign gives the same answer, and since it is also the bound on taking a role away, a person cannot remove such a role either.
  • Granting a reserved key directly to a principal, an org or a connection is refused, whoever asks. That covers a platform grant, a declared shape granted to a person, a connection's grant (a connection acts for the outside provider that holds its token), and ctx.grant from an operation, including one running as a system actor. A connection grant the platform already recorded is skipped when a provision or reconcile delivers it, so it never fails the provision. The skip is reported in that call's answer and as a warn line in your deployment's log; the platform does not read the answer field yet, so the log is where it shows.
  • Reconciling declared shapes is refused when a shape holds a reserved key, before anyone is topped up: the reconcile would give the key to every holder of the shape, and record it as what a binding link gives. A shape may still list a reserved key in retired, which takes it back.
  • The platform's own role assignment refuses a role that mixes a reserved key with keys a person may hold. It also refuses an all-reserved role stored as person-held, and admits one stored as system-held. New role definitions record person when holder is omitted. A role row from before this field keeps a null holder and the earlier key-only decision until the definition is written again. The directory and scope projection both carry the holder.

A role made only of reserved keys must declare holder: 'system', or the platform door refuses it; roles defined before the migration are unaffected until redefined.

Roles a host defines and seats itself are held to the same rule:

  • Defining a role (defineRole, and the role set a provision or a restore projects into a scope) is refused when a person's role would hold a reserved key, or a system-held role a key a person may hold. A redefinition is judged against the role it replaces: a key it adds meets the same rule; a system-held role redefined as a person's counts its old keys as reserved; and a role cannot be declared holder: 'system' while anyone but a system principal holds a seat in it, unless it is already stored system-held. That holds when its stored row is a person's, a row from before the holder was recorded, or gone altogether (a seat can outlive its row), and it counts seats in archived scopes too. A first definition of a role nobody holds is judged by its keys alone. So a role assigned through a door cannot be widened afterwards, by a key or by a holder change. A definition is never refused for a key it takes out, only for a reserved key it still holds.
  • The owner's seat, which a provision gives the owner of record, and the owner hand-over go through the person's door: a role carrying a reserved key, or one declared holder: 'system', is refused. The hand-over asks before the owner record moves.
  • Every person's door refuses a role declared holder: 'system', from the holder the role is stored with, even on a host that registers none of the modules.
  • A host that registers no modules learns a reservation from the tenant's system-held roles: their keys count as reserved when a role is defined there.
  • A key the host knows nothing about is admitted, deliberately. A host judges only the modules it knows and the tenant's system-held roles; refusing every key it cannot place would refuse every role a module-less host is given. Push is where your whole surface is judged. A key reserved only through a schedule's permissions, which no system-held role holds, is therefore not caught on a host that does not register its module; the control plane checking the registry's marks against the engines it knows is #2446.
  • A release that makes a person's role system-held while people hold it passes push, because push cannot see who holds a role, and its promote is refused. When a release declares a system-held role, promoting it to prod first asks every scope the promote would move onto it for the roles it stores and which of them are held there, and judges the release's roles the way each scope's reconcile would. If any scope would refuse them, the promote answers 409 and nothing is served, adopted or moved. Take those seats back, or ship a release that keeps the role a person's, and promote again. A release with no system-held role is judged by no scope. A promote that would move more scopes than one promote reads is refused with a 503; the platform's staff can raise that limit, or promote with an acknowledgement that skips the read and is recorded in the promote's audit log. A deployment too old to answer the question is moved unjudged and counted in the promote's answer (roleStateUnread); any other failed read refuses the promote. Every one of these answers names only your own scopes; other tenants' scopes appear as counts.
  • Where the promote could not judge a scope, or a seat was made after it asked, that scope's reconcile still refuses the release, on every pass, naming the tenant, the scope and the role, at every scope where a person holds a seat in that role (an archived scope included). Nothing is written, but that scope's whole reconcile is held: the release's other roles, its new schedules' grants, delivered connection grants and entity-grant retirements are not applied there while the scope runs the new code. To clear it, take those seats back in each such scope, or ship a release that keeps the role a person's.
  • A role a release drops is kept as a tombstone (#2531): its row is marked revoked, with the keys and holder it had, instead of deleted. It grants nothing, so a seat in it authorizes nothing until the role comes back, and it is kept for good as evidence. A system-held role a release drops and a later one adds back is judged as if it had stayed defined, so its host principal's seat does not hold the reconcile, and adding the key back as a person's role cannot give a person the keys it held. This treats a tombstone like a role kept defined; it does not prove who holds the seat. A dropped person's role added back as system-held while someone holds it is still refused. A scope that dropped the row before tombstones were kept has none: there, take the host principal's seat back and give it again once the role is back.
  • A system-held role stored before holders were recorded (adapter 0.154 or 0.155, never reconciled under 0.156 to 0.159, or a dump taken before 2026-10-21) cannot be upgraded while its host principal holds a seat: no seat can be told to be a system principal's. A reconcile is refused on every pass until you take that seat back, reconcile, and seat it again. A restore of such a dump is refused (409, nothing restored), and since a seat inside a dump cannot be taken back first, the only way is a new role key. No vertical in this repository uses a system-held role.
  • Nothing is revoked. A refused definition or seat writes nothing, so a seat that already holds a key reserved after it was seated keeps working. A directory fan-out of a stored definition is projected as it is and not judged again, since dropping the role there would revoke its seats. lint:role-seat-paths refuses a host path that seats or defines a role without asking.

A staff restore or import on a host the control plane runs is judged too (#2555). It loads the dump's seats under the tenant's roles as the directory stores them now, so before anything is replaced, the roles the dump seats or stores are judged against the dump's own roles and seats. A dump holding a seat in a role since made system-held is refused, with nothing loaded, unless the dump itself stores that role system-held. A dump that carries no roles (a SQLite scope file, or a scope that read its roles from the control plane) cannot say which definition its seats were made under, so such a seat is judged as a person's. On such a host, a scope holding a seat in a system-held role therefore cannot be restored from its own export. No role is system-held on such a host today; the remedy, an export that carries the tenant's roles, is a follow-up. The refusal names the role key and nothing else, and says so when the reason is that the dump carries no definition of the role. The host throws forbidden; the control plane's restore route answers 422, with the sentence in detail. A staff restore takes a dump the staff caller supplies, and that dump is trusted input: its provenance is the staff caller's. What is judged is how the tenant's roles apply to it now.

On Cloudflare, where the control plane projects permissions into its scopes, a staff restore or import also lands with the directory's current permission state. As its last step, inside the load's own transaction, it writes what a fan-out sends: the tenant's roles, its tenant-level grants and memberships (connection grants included), its entitlements and identity links, and the vertical's connection keys. Anything the directory has revoked since the backup was taken stays revoked, without waiting for the next fan-out. The scope's own seats are the dump's, and nothing revokes them. The role set is judged there, against the seats the dump has just brought, so the roles that land are the roles that were judged. A refusal leaves every row of the scope as it was. An import that cannot finish takes down the scope it created, never activated, and only that one: its directory record is removed, so a retry with the same scope id imports. An import pointed at an existing scope is never taken down. Refused in the load, it leaves that scope as it was. Failing after the load (in the second read, below), it has replaced the scope's rows, and that is recorded before it fails, as a restore is. If that removal fails, the refusal still stands, staff see an ops-failure row, and the scope stays in provisioning for staff to reap. The removed scope's storage is left for the retry to replace. Until then it holds the tenant's projected permission state (identity links and connection keys included), and a later tenant deletion does not reach it. The scope keeps its own reader and enforcement settings through the load, never the dump's, and the projection then moves them exactly as a fan-out would. The end state is the scope's old state followed by one fan-out. Where scopes are not projected, only those settings are kept. The directory is read once more after the load, and if it changed in between, the scope is projected again, once, judged against the seats the load brought. A role redefined in that window which those seats refuse is refused there. The restore is still recorded, then fails, and the scope stays on the set the load judged, but only until the next fan-out, which is not judged and writes the refused definition over those seats. So act on such a refusal: take the restored seats in that role back, or define the role person-held again. The refusal says so. A preview's snapshot is not projected: it is a same-instant copy, and the fan-out keeps its source current. The pure SQLite host keeps this state in its directory and no scope holds a copy of it, so nothing changes there.

On a deployment with no control plane (#2531), the role set a provision, a reconcile or a restore's role repair writes is judged again inside the unit that writes it, against the roles, tombstones and seats the scope holds as the write lands. The first check, before anything is written, still gives the detailed refusal in the usual case. The second catches a seat made in between. A restore's role repair now runs inside the load's own transaction, after the dump's rows are in, so it is judged against exactly the seats the restore brings. A paged (staged) restore is judged the same way, although its first check could see only the role set. A refusal there names the role key and nothing else: role '<key>' is refused by the reserved-key rule, judged against the roles and seats this scope holds as the write lands (K-55); nothing was written. Nothing is written:

  • a provision or reconcile leaves no role row, tombstone, owner seat, provisioning receipt or enforcement flip. The scope's module migrations have already run by then, as they do before every projection;
  • a restore keeps the scope's rows as they were, and a staged restore keeps its stage, so the same commit can be retried.

A deployment whose scope objects predate this refuses the call outright rather than writing unjudged, and a @substrat-run/vertical-host paired with an older adapter repairs the roles after the load as before. The directory's fan-out of a tenant's stored roles is still not judged again (below).

Not covered yet:

  • on Cloudflare, a staff restore or import reads the directory's state before the scope loads the dump. What the load writes is judged in its unit, but a directory write in between is caught by the second read after the load rather than inside it (#2595 would order projections instead). An import for a tenant with no live scope is judged without the scope class's reserved keys (the seat rule still holds);
  • on Cloudflare, a scope archived straight from provisioning whose record shows no migration applied is not read (reading would create its storage), so a definition that scope could decide is refused, naming it. The migration count is not proof the scope was never used: a vertical with no migrations of its own records none and can still hold a seat there. While it is the tenant's only scope, every role definition is refused until you unarchive or reap it (both work; a reap needs no hostname). No product path reaches this today;
  • on a shared control plane, the directory record of a connection grant for a scope your deployment serves, and of a tenant-wide one: the plane cannot see your deployment's reservations, so it records the grant. The grant confers nothing, since your deployment refuses it at delivery and skips it at every re-seat, but it stays listed until revoked;
  • grants and shape bindings recorded before these checks existed, or before the key was reserved, and what reaches a person through them later (such as an org membership or a binding link), including what an older build of your vertical seats again after a rollback.

Push and the lint hold what a vertical declares there.

Those modules have to be the ones the lint and the push read, which are your permission entry's modules. Give the host the same permissions and it refuses to register a module the list leaves out:

ts
const host = new CloudflareScopeHost({ scope: env.SCOPE, permissions });
export const ScopeDO = defineScopeDO(MODULES, {}, { permissions });

Decided, and left as is (#2531). These paths are deliberately not judged by the rule:

  • a copy the platform makes: a preview's snapshot inside your deployment. It copies, at once, the roles and seats a live scope holds, which were judged where they were written, and a copy revokes nothing;
  • the fan-out of a tenant's stored roles into its scopes: the role was judged where it was defined, and judging it again would drop it and revoke its seats. It is left unjudged on purpose, and the in-unit judgement above (#2531) does not apply to it;
  • the platform's own role assignment, which keeps the platform rule. Telling a person from a host principal needs a record of what kind of principal each one is, kept on the principal when it is created; that is decided with the host principal's lifecycle. Only staff and the platform's own service reach this door;
  • a role defined on a Cloudflare coordinator for a tenant that has no scope yet: it is judged by the coordinator's modules alone. No product path reaches it, since the dashboard defines its roles after the tenant's first scope exists. Revisited when the dashboard, or any coordinator, registers a module that reserves a key;
  • the owner grants an install gives: an install grants them on the app's scope, which judges them against its own modules' reservations, and push refuses a reserved key in a manifest's owner grants. A grant naming no scope, on a host that does not register your modules, is judged by that host's modules alone;
  • a key reserved only through a schedule's permissions, on a host that registers no modules: no product path defines a role there, and push holds the registry's marks to your modules;
  • on Cloudflare, the coordinator's read of a scope's seats before it defines a role: the scopes and the directory are separate units, so a seat made in between is not seen. The dashboard is the one caller, and its roles hold no reserved key. Revisited when the dashboard, or any coordinator, registers a module that reserves a key.

The owner hand-over needs a scope host that judges the new owner's seat as a person's. A @substrat-run/vertical-host paired with an adapter from before that check answers 501 at the hand-over and moves nothing; upgrade the adapter beside it to hand the owner seat over.

Roles @ nodes ​

A role bundles permissions; an assignment binds a principal to a role at a node of the tenancy tree — the tenant root or a specific scope — with inheritance down the tree:

ts
host.admin.defineRole(tenantId, {
  key: 'technician',
  permissions: ['workorder:read', 'workorder:report'],
  source: 'vertical',
});

host.admin.assignRole({
  principalId: tech,
  roleKey: 'technician',
  node: { tenantId, scopeId: stockholmBranch }, // or scopeId: null = whole tenant
});

Capability grants ​

Narrow, direct, time-boxable grants — one permission, one node, optionally narrowed to one entity and its declared descendants:

ts
host.admin.grant({
  principalId: portalCustomer,
  permission: 'workorder:read',
  node: { tenantId, scopeId: branch },
  entity: { entityType: 'facility', entityId: theirBuilding },
  expiresAt: nextMonth,      // optional
  grantedBy: adminPrincipal,
});

Entity-narrowed grants are how portal users (a customer, a board member, a subcontractor) see only their facilities and orders inside a shared scope. Grants can also target an organization; members reach them via membership.

A connection is a first-class grant subject too — not only principals and orgs. A connector (an external provider acting through a connection) can hold a capability grant without pretending to be a person: host.admin.grantToConnection(...), and a check's subject is polymorphic ({ kind: 'principal' | 'connection' | 'system', id }). A connection is keyed (tenant, vertical, provider), so granting it one permission reaches only that tenant's scopes running that vertical — the blast radius of a leaked provider token is one permission on one vertical's data, readable in a diff. A key reserved to a system principal is never granted to a connection, and lint:connector-grants refuses a connector whose standing grants name one.

A module's system principal is the third such subject — the caller behind scheduled work. A schedule runs an operation on a timer, and it is not a person either; host.admin.grantToSystem(...) gives { kind: 'system', id: moduleId } exactly the permissions the schedule declared, so the operation's own ctx.check resolves the same way it does for anyone — the gate stays the check, never a bypass — and the emitted events read as { system: '@your/module' }. Like a connection it holds no memberships; its authority is exactly the grants written against system:<moduleId>, projected at provisioning. The schedule switch (revokeFromSystem / restoreToSystem) turns one module's scheduled work off on one scope and back on. While it is off, the module's system grants there are revoked, so a job acting with that authority is denied too, and a new grant to the module there is refused. The platform also records the switch outside the scope, so a scope whose storage is wiped or restored from an older backup is switched off again after it is provisioned, and staff can list every scope with a module switched off (GET /system-switches).

Organizations are a real directory record, not a string you make up at the call site:

ts
await host.admin.createOrg(actor, {
  id: orgId,          // branded ULID — slug and name are attributes, not identity
  tenantId,
  slug: 'acme',       // unique within the tenant
  name: 'Acme AB',
});

addMember, removeMember, listMembers and grantToOrg all fail closed on an org that does not exist in that tenant. That refusal is the point of the record: a grant to an org nobody registered would otherwise look applied, resolve for nobody, and still show up in the permission diff as though access had been conferred. Because the id is a ULID rather than a name, renaming an org cannot orphan the tuples that reference it.

From declaration to enforcement ​

The keys and role templates are declared in TypeScript — the same objects the host registers (module manifests declare the keys, provisioning declares the roles). That declared surface is not trusted to stay honest by convention; it passes three successive gates on its way to a running scope:

authoredDeclared in TypeScriptmodule manifests → keys + descriptionsroles → templates · entity grants → shapesrenderscheckpoint · a human reads thispnpm lint:permissionsemits PERMISSIONS.md, the review artifactCI --check fails the build on driftsubstrat pushshipsThe deploy manifestthe surface rides along as a registrycontent-hashed → digests.permissionpromotegateAdmissiona real diff between two versionsa widened surface is visible, not implicitat write timeper tenantProvisioningrole templates projected into eachtenant's own _substrat_rolesevery operationruntimectx.checkreads scope-local tables onlyabsent or empty projection = deny
The branch off the top ends in a person: PERMISSIONS.md exists to be read in a diff, and CI going red is what makes the reading unskippable — it is not itself the approval.

Three kinds of honesty, at three altitudes:

  • Review-time. PERMISSIONS.md is the human-readable render of the surface — the artifact for the permission checkpoint. Because CI regenerates it with --check and fails on any difference, a role that gains a key cannot merge without showing up in the diff a reviewer must approve. The check reads the same declared objects the host registers, so the artifact cannot drift from what is enforced. Its Operations section names the key each operation declares it checks and what the check narrows to (the scope, one record, or a walk over rows), so moving an operation to another key shows in that diff too. An operation whose handler checks a key with nothing declared is listed as "checked in code, not declared", not given a guessed key.
  • Deploy-time. The surface is carried in the version's deploy manifest and content-hashed as digests.permission, so admission can compute a genuine permission diff between the running version and the incoming one. The declared surface is immutable per version — it is a property of the code, frozen when that version is built.
  • Request-time. Roles and grants are projected into each scope's own tables at write time; the checker reads only that local projection (see below), and an absent or empty projection is a deny. Missing data can only ever remove authority, never confer it.

This is the same layering the rest of the model rests on: the declared surface is a per-version code fact, operator state (a tenant's live roles) is a runtime-mutable table, and minted grants are scope-local tuples. None is a copy that can silently diverge from the others — each is the authority for its own layer.

Evaluation: relationship tuples with a fixed algebra ​

Internally, the built-in checker compiles the authored surface into relationship tuples (subject → relation → object) and evaluates checks with a fixed, four-rule derivation algebra:

  1. Role expansion — principal has role, role carries permission.
  2. Tenancy-tree inheritance — permission at a node flows down to child scopes.
  3. Entity parent edges — declared in module manifests (workorder → facility) and written at runtime via ctx.link and moved via ctx.relink; entity-narrowed grants flow along these edges, depth-capped. The one exception: a key that an entity-grant shape protects (a 'grantee' or binding shape's keys) does not flow past a record of the shape's type. A grant of it on a parent never reaches that record or anything beneath it through the record. On such a record the key is held only by the shape's own grant there, or at the node, by a role or a scope-level grant.
  4. Org/group membership — grants to an organization reach its members.

No negation, no configurable rewrite rules. Verticals never see or author tuples — roles and grants remain the only authored surface.

Where tuples live — a scope reads only its own state. Scope and entity tuples (rules 2 and 3) live in the scope's own database and are evaluated inside its serialization domain, so there is no distributed-consistency problem for them. Tenant-level facts — role definitions, role assignments, tenant grants, and org membership (rules 1 and 4) — are tenant-wide, so the directory (the control plane) is their authority. But the checker never reads the directory on a request: the control plane projects those facts into scope-local tables (_substrat_roles, _substrat_tenant_tuples) at write time, and the checker reads the projection exactly as it reads scope tuples.

This is the important shift, and it is deliberate: the control plane is a write-time authority that projects into scopes; it is never a read-time dependency on the request path. Cost moves from the read path (every request) to the write path (rare role/grant changes) — the correct direction for a read-heavy multi-tenant system, and what makes a scope genuinely isolated: it can run as its own Cloudflare Worker with no control-plane binding at all. (For the earlier per-request model and why it was replaced — scaling, isolation, and the untrusted-vertical requirement — see the scope-local permissions design note.)

The consistency consequence is small and one-directional. Scope-level grants/roles stay synchronous and immediately consistent ("no zookies") — the checker runs in the scope's own serialization domain. Only tenant-level changes are now eventually consistent across a tenant's scopes, bounded by the write-time fan-out and a reconciliation sweep. An absent or empty projection is a deny, byte-for-byte the normal deny path, so missing data can only ever remove authority, never grant it. Revocation still fans out as tombstones (below) — now into every scope the tuple was projected to.

Revocation: tuples tombstone, they never disappear ​

Access is withdrawn by tombstoning a tuple — it keeps its row, gains a revokedAt, and the checker's walk skips it. Nothing deletes a tuple.

That is deliberate. A tuple that once granted access is the evidence of why an access was allowed, so deleting it destroys the audit trail exactly where it is most needed: a deleted row can show neither that access was revoked nor that it was ever granted. Every revocation path in the kernel works this way — removeMember is the first of them — and listMembers({ includeRevoked: true }) is the evidence view over the result.

Liveness is therefore one predicate, applied identically everywhere: a tuple grants only while it is unexpired and unrevoked. Expiry (expiresAt above) and revocation are siblings, not separate mechanisms. The checker interface is deliberately swappable (an OpenFGA-backed adapter is the designated alternative), and any implementation must pass the same contract tests.

Decisions carry proof ​

ts
type Decision =
  | { allowed: true; proof: RelationTuple[] }   // the chain that granted access
  | { allowed: false; checked: PermissionKey; node: Node };

An allow always carries the tuple chain that produced it — an unexplained allow is unrepresentable. This powers:

  • explain — why does this user see this?
  • view-as-user — render any screen as any principal, with real decisions;
  • the human-readable permission diff — the review artifact for the permission checkpoint: who gains what, where in the tree.

And it carries past the request: when an operation emits, the kernel stamps onto the event envelope which permission(s) it checked-and-passed and — when the allow came through a capability grant rather than a role — a ref to the granting tuple (authorization, K-34). The full chain is re-derivable by explain; what re-derivation cannot recover once tuples have since changed is which permission and grant were consulted at write time. That pointer is what the envelope keeps, so a mutation carries its own proof of authority (Events & audit). Decisions carry proof forward, not only at the instant they are made.

Denials are recorded ​

An allow leaves its trace on the event it authorized; a denial has no event to ride, so it is captured on its own. When an enforced check refuses, the kernel writes a row to a scope-local _substrat_denials table (id, actor, permission, tenant_id, scope_id, operation, impersonation, at, drained_at) — the one moment where an actor's intent and the permission model visibly disagree, and which no other log witnesses (the admin log records changes, the outbox records allowed mutations). Because a denial rolls its operation back, the row is written outside that transaction, at the operation boundary after the rollback, so the record survives the very failure it describes. impersonation is the same { session, by } stamp the event envelope carries, and null for the same reason — see Impersonation: actor is the principal the check answered about, and this is the staff member who was acting as them, when one was.

This is not the K-24 staff-directory read log (_substrat_access_log): that records control-plane reads against the directory; _substrat_denials records refused checks inside a scope. Two different tables for two different facts. Both drain rather than expire — drained_at marks a row shipped onward, and only a drained row may be pruned.

Reading them back ​

Two staff reads on HostAdmin, served by the control plane as GET /tenants/:t/scopes/:s/denials and …/denials/summary, and rendered per scope in the console:

  • summarizeDenials buckets the log per (actor, permission) with a count, the number of distinct operations, and first/last occurrence. This is the view to open first, and the ordering is by count on purpose: the volume of this log is attacker-influenceable — a probing client mints unlimited rows — so a newest-first page would let whoever wrote the last hundred rows push every other actor off the screen. groupBy: 'operation' asks the other question — which operation keeps getting refused — with one bucket per operation and the same total and window facts beside it; the summary echoes the grouping it answered with. A denial that unwound something other than an operation invocation has no operation, and those rows come back as one bucket keyed operation: null — still counted, still part of total — rather than vanishing from the sum.
  • listDenials returns the raw rows behind a bucket, newest first, narrowed by actor, permission, operation, and a since/until window.

The summary also carries the log's own window — its oldest and newest held rows, computed ignoring the filter. That is what keeps an empty result honest: because rows drain rather than expire, absence before the window's floor means "no longer held", not "never happened".

Both reads are actor-stamped and recorded to the K-24 access log, so reading the denial log is itself logged, and both cross-check the (tenantId, scopeId) pair and fail closed on a mismatch — a confused-deputy scope id resolves to nothing, never another tenant's refusals.

In operations ​

The standard first line of every operation:

ts
import { assertAllowed } from '@substrat-run/kernel';

const handler: OperationHandler<Input, Output> = async (ctx, input) => {
  assertAllowed(await ctx.check('workorder:read', orderRef(input.orderId)));
  // ...
};

ctx.check evaluates the ambient principal at the ambient node. Pass an EntityRef for per-entity checks: the checker tries node-level first (staff see everything in the scope), then walks the declared parent edges against entity-narrowed grants (portal users see their own things).

Sharing at runtime: ctx.grant and ctx.revoke ​

Entity-narrowed grants are minted at seed time by a platform actor (HostAdmin.grant). When a user shares their own record with another person — and takes them off it again — the operation does it itself, on OperationContext:

ts
await ctx.grant(principal, PERM.listContribute, listRef(listId));   // share
await ctx.revoke(principal, PERM.listContribute, listRef(listId));  // un-share

Three guardrails make this non-escalating by construction:

  • Entity-required — module code can never write a scope- or tenant-wide grant, only narrow one onto a thing.
  • Delegating — the caller's own decision on that entity is re-checked, so an operation can only hand out what it was itself given. Delegation, never elevation.
  • Transactional — a grant made by an operation that then throws never happened, the same as its rows and its events.

Every later ctx.check reads the grant, so nothing else in the app has to remember who may touch what. Neither alternative is this: a ctx.link parent edge can be moved but never removed (see Moving an entity), so it is not a revoke, and org membership is revocable but coarse-grained (a whole org, not one record). The mistake this section exists to prevent is minting an org per domain row — or keeping a membership table consulted by hand in every handler — to get a revoke the kernel already has. The todo demo (src/module.ts, todo/share-list and todo/revoke-share) is the two-line reference.

Moving an entity ​

A document changes folder; a building changes management company. ctx.relink(child, from, to) replaces one parent edge with another in a single write, so access follows the move: a grant above the old parent stops reaching the entity, a grant above the new one starts, and no check in between ever sees it with no parent at all.

ts
// Neither relink nor link checks a permission: the operation checks all three ends.
assertAllowed(await ctx.check('docs:move', doc));     // may move this document
assertAllowed(await ctx.check('folder:write', from)); // may take it out of here
assertAllowed(await ctx.check('folder:write', to));   // may put it in there
ctx.relink(doc, from, to);

The kernel holds the shape of the graph, not who may change it:

  • to must be a declared relation, exactly as for ctx.link, or the call is refused with validation_failed. So is a to that is the entity itself or lies beneath it, which would make it its own ancestor.
  • from must be a parent the entity has now, or the call is refused with conflict. An entity with several parents keeps the others.
  • Moving to where it already is does nothing.
  • The move is one entity.relinked event ({ child, from, to }), stamped with the operation and actor like any event it emits. It goes on the moved entity's timeline only: from and to get no event, so a folder's own history does not show what moved in or out of it. A vertical that wants that emits its own event on the folder. That event is the lasting record: linking back to the old parent later brings the old edge back in place, and records that as an entity.linked event.
  • It is transactional with the operation: if the operation throws, the entity never moved.

The screen outlives the grant ​

A revoke has a client-side half. The app follows three rules, and the first two are the ones every vertical here already keeps: it never filters for access — a list nobody shared is not hidden, it never comes back from the server at all — and it renders what the server returned, so a 403 is a wall with the server's own message, never an empty list. The third is the one a permission-centric app cannot skip: it re-asks. Someone sitting on a list they were just removed from keeps seeing it until something refetches. Nothing leaks — the server refuses every subsequent action — but they are looking at data they no longer have access to, and for an app whose pitch is "you see only what you may", that is the worst-looking failure available, and exactly what a revocation demo shows on stage. So a view revalidates on focus, on visibility and on a slow poll (useAutoRefresh(load) from @substrat-run/ui), a click on the nav item already selected refetches instead of being a no-op same-route link, and a read that comes back 403 replaces the content with the wall rather than leaving it underneath — every read the screen makes, the next page of a walk and the detail of one row as much as the refetch. demos/todo/app/src/App.tsx (ListView) and demos/shop/app/src/App.tsx (the nav tabs) are the reference.

ctx.grant shares with a person, someone the checker already knows. A link shares with whoever holds the URL, and that is nobody the checker knows. A capability is the kernel's answer. It is authority carried by a secret: a row in the scope's own spine names one entity, the keys it may use there, and optionally an expiry, a use limit and a list of operations. Whoever exchanges the secret acts as { capability: <id> }. The checker resolves that actor like any other, it is stamped on every event it causes, and its refusals are recorded like anyone's.

ts
assertAllowed(await ctx.check(PERM.folderShare, folderRef));
const { secret } = await ctx.capabilities.mint({
  entity: folderRef,              // this folder and everything beneath it
  permissions: [PERM.folderRead],
  expiresAt: input.expiresAt,     // optional; so is maxUses
});
return { link: `${origin}/#share=${secret}` }; // a fragment: never sent to a server
  • Exactly one subtree, exactly its keys. A capability reaches its entity and whatever lies beneath it through declared parent edges, the same walk entity grants take. It holds no node-level authority, so an operation that checks only at the node refuses it.
  • Never more than the minter holds, at every use. Minting re-checks each key on the entity, as ctx.grant does. The checker also re-checks the minter every time the capability acts, so a link stops working when the person who made it loses access. Only a principal can mint.
  • Revocable at once. ctx.capabilities.revoke(id) is open to whoever could have minted the capability. The row is read on every check, so a revoke refuses the very next call, including one made through a session handed out earlier.
  • A use is an exchange. The secret is presented once. mountCapabilityExchange from @substrat-run/vertical-host trades it for an HttpOnly session cookie, so the secret does not stay in browser history or in a Referer. maxUses counts exchanges, which means browsers, and not reads.
  • Only the secret's hash is stored. The kernel keeps its hash and nothing else. As a tripwire against accidents, the operation that mints it is refused if it writes the secret verbatim to an event, to its own tables or to a platform intent. That catches a mistake; it cannot stop a module that means to leak its own secret.
  • A link does not open a copy of its scope. A fork, a snapshot or a preview made by the platform starts with no capabilities, so a link minted on production keeps opening production and nothing else. A backup restored into the scope it came from keeps its links, as does moving a scope onto a new version, so a restore does not end the links that were live. Whether a restore counts as a copy is decided by where the backup says it came from: one restored onto a different scope starts with none, while a file presented as the target's own backup keeps whatever links it carries.

A link to a folder can also deliver the files under it. mountLinkShareDownload from @substrat-run/vertical-host mounts GET /api/capability/attachments/:attachmentId. The request carries only the session cookie, and the route acts as the capability first. With no cookie, it falls back to the signed-in visitor, as linkShareStub does.

ts
mountCapabilityExchange(app, { host: () => host, node: (c) => nodeOf(c) });
mountLinkShareDownload(app, {
  host: () => host,
  node: (c) => nodeOf(c),
  principal: (c) => signedInPrincipal(c), // optional: without it, links only
});
  • A file is read as its entity is. The download checks the attachment target's readPermission on the file's entity, as the capability, through the same checker. A file outside the capability's subtree is refused, and so is one its minter can no longer read. Both refusals are recorded against the capability.
  • A link never writes a file. Through a capability, upload and remove are refused even when the capability carries the write key, and the refusal is recorded.
  • A download is not a use. maxUses still counts exchanges only.
  • An operations-narrowed capability reads no attachments by default. Set attachments: 'read' when minting it to allow attachment list, open and search. This opt-in grants no permission: every read still checks the target's readPermission as the capability, including its subtree and the minter's current access. It never allows upload or removal.
  • Nothing about the response is cacheable or executable. It is sent Cache-Control: private, no-store, always as Content-Disposition: attachment, with nosniff and a sandbox content security policy.

To build a listing or a route of your own, use linkShareAttachments(c, host, node, principal). It returns the same surface with the same precedence. The host method under it, getCapabilityAttachments, is optional on ScopeHost. On a host without it, a request that carries the cookie is refused rather than answered as the signed-in visitor.

Each exchange sets a cookie of its own, sb_capability_<capabilityId>, so opening a second link keeps the first. The exchange answers with the capabilityId; a page that holds several links sends it back to say which one a call acts as, in the X-Substrat-Capability header, or as ?capability=<id> on a plain download link, which cannot carry a header.

ts
const { capabilityId } = await (await fetch('/api/capability/exchange', { … })).json();
await fetch('/api/folder', { headers: { 'x-substrat-capability': capabilityId } });
const href = `/api/capability/attachments/${fileId}?capability=${capabilityId}`;
  • A name selects; it never searches. A request naming a link this browser does not hold (never opened here, evicted or cleared) is refused as a revoked link is. It is never answered by another link the browser holds, nor by the signed-in visitor. The session behind the name acts as its own capability, so a link to one folder can never act on another, whatever it is called.
  • Naming nothing acts as the link opened last, which is what the single cookie did. A page that only ever holds one link needs no change, and a cookie set before this change keeps working until it expires.
  • At most eight links. Opening a ninth evicts the one exchanged longest ago. Opening it again brings it back, if it has uses left.
  • Forgetting is per link. clearCapabilitySession(c, { capabilityId }) forgets one link and keeps the rest. With no link named, it forgets them all.

Another app of the same tenant: peers ​

Sometimes one app of a tenant has to call another app's operations. A board-room app reads customers from a CRM, and the CRM hands an approved document back. Neither call is a person acting, so there is no user token to carry. A peer lets the platform say which app is calling, so nobody has to paste an API key into the other app's settings.

The app being called declares who may call it, in its module manifest:

ts
peers: [
  { vertical: 'acme/board-room', operations: ['customer/list', 'customer/get'], permissions: ['customer:read'] },
],
  • What a peer holds is declared, and reviewed. The listed permissions are granted to vertical:acme/board-room on every install of this app, from provisioning on, and PERMISSIONS.md shows them in their own section. Widening what another app may do is a permission diff like any other.
  • An install older than the declaration gets it at its next reconcile. Promoting the version that declares a peer lets that peer through the door at once, but the permissions are written into each existing install by a reconcile. The platform runs one on every install whose running version changed, on its regular pass after the promote. substrat scope provision <scopeId> runs it for one install now. Until then the calling app's panel says the target grants it nothing. An app that keeps no owner of record still gets this part of the reconcile: the permissions its version declares are added, and nothing else is changed.
  • Narrowing it takes effect when the version is promoted. A peer holds only what the version serving the install declares. Drop a permission from a peer's entry, or drop the peer, and the first call after the promote no longer has it, on every install, with no reconcile in between. The grant an earlier version wrote stays in the scope as a record, but it counts for nothing, and switching the peer off and on again does not bring it back. Declare the permission again and the peer holds it again. A permission a tenant took away stays taken away whichever way the declaration moves. The calling app's panel follows the same rule: a peer that holds no permission the running version declares reads as refused at the door, not as active.
  • It may invoke only what is listed. Any other operation is refused forbidden before it runs. operations: [] declares a peer that holds its permissions and invokes nothing. That is the shape for an app that only receives from this one.
  • Your operations do not change. assertAllowed(await ctx.check(PERM.customerRead)) resolves for the peer exactly as it does for a person who holds the key.
  • It is recorded as itself. Every event and every denial names { vertical, scope }: the calling app and the instance of it that called. A person signed in to the calling app does not come along, and a peer cannot mint a link share.
  • A tenant can switch one off. revokeFromPeer refuses that app's next call on one scope and removes everything it held there, and no re-provision gives it back. restoreToPeer gives back exactly what was removed. The switch is recorded outside the scope too, so a restore or a rewind to a point before it does not let the app back in. An app whose only access to the scope comes from a tenant-wide grant can be switched off there as well.
  • Same tenant only. The platform finds "the instance of that app in this tenant" by its slug. It never looks in another tenant, never picks a preview, and refuses to guess when a tenant runs two instances of the same app.

On the pure host, @substrat-run/adapter-sqlite/vertical-broker runs two apps side by side under the same rules, for tests and local development.

A provider's connections: connection landings ​

A poll-only connector (Fortnox, Planima) reads a provider on a timer and lands what it finds through one of your operations, as the connection. Your app says which operation and which key, in its module manifest:

ts
connections: [
  { provider: 'fortnox', operation: 'ledger/record-period', permission: 'ledger:record' },
  { provider: 'planima', operation: 'maintenance/record-plan', permission: 'plan:record',
    options: { organizationId: null, horizonYears: 50 } },
],
  • The platform grants and binds it. Every live connection of that provider in a tenant where your app is installed is granted the key on each install and bound to it, on the connector pass after the connection appears. A company that approves a connect link is landing data within the next pass, with nobody running substrat connection bind. A bureau with ten Fortnox companies gets ten bindings into the same install.
  • It is reviewed like any other grant. The declaration is part of the permission registry: PERMISSIONS.md shows it in its own section, and it moves the permission digest, so a version that changes what a connection may do is acknowledged at promote.
  • The key must be yours to give. It must be a key a module declares, and not one reserved to a system principal: a connection acts for whoever holds the provider's token. One landing per provider.
  • It follows the running version. A pass grants and binds from the version each install runs. A changed operation, key or declared option is re-bound; an option you do not declare is left as an operator set it. A version that stops declaring a landing does not unbind anything: the connection keeps its binding, and the connection's row in Health › Connections reports any landing that now fails.
  • A landing can wait to be asked. bind: 'on-request' is for a source each instance connects for itself, one folder per instance, say. The pass grants and binds nothing for it; an instance binds its own connection, with its own options, when it asks. The declaration still names the operation and the key, so PERMISSIONS.md shows the provider marked on request and the digest moves if you change it. Leaving bind out means every-install, everything above. Switching an every-install landing to on-request revokes nothing: the key and binding an earlier version gave each instance stay until they are removed, as with a landing a version stops declaring. Push an on-request landing with the @substrat-run/cli release that carries it: an older CLI builds the registry without the mode, and the platform cannot tell its push from an every-install landing.
  • Revoking the connection ends it. The revoke takes the connection's keys and bindings together, and the pass never seats them again.
  • Nothing lands silently. A connection with no binding reads nothing polls this connection; a scope the connector could not land in, or a declaration the provider refuses (an option it does not take), fails the connection's row. The row counts what did not land (1 of 3 bindings did not land) under a reference; the provider's own answer stays with platform staff, who find it by that reference.

Assigning a role: ctx.canAssign ​

Reviewing role definitions protects nothing on its own. Nothing in a checkpoint over defineRole stops an admin from assigning someone — or themselves — to owner: no role was widened, no defineRole was called, and no permission diff shows anything. The moment a vertical defines any role carrying role-assignment permission, assignment becomes an escalation path.

So there is a bound, and it is a mechanism rather than a convention:

A principal may assign role R at node N only if the assigner already holds every permission R carries at N.

ts
'team/invite': async (ctx, input) => {
  assertAllowed(await ctx.check(MEMBER_MANAGE));      // may you manage members at all
  const bound = await ctx.canAssign(input.roleKey);   // may you confer THIS much
  if (!bound.covered) {
    throw substratError('forbidden', `cannot assign ${input.roleKey}: you do not hold ${bound.missing.join(', ')}`);
  }
  …
}

Two checks, in that order, answering different questions. canAssign is a bound, never a substitute for the operation's own permission check.

Removal takes the same bound. A junior admin who can strip a role they could not have granted can lock the owner out of their own tenant. Revocation is the mirror of assignment, not a lesser act — so gate both sides on it.

It is narrowing-aware, and that is the load-bearing part. Only authority held at the node counts. A principal whose workorder:read is narrowed to one entity does not thereby hold workorder:read for the purposes of this comparison — otherwise sharing a single record would launder into authority over every record, by way of assignment. Membership does expand: authority held through an org is authority that can be conferred.

One resolution, not N checks. ctx.check answers about one permission and walks the tuples to do it, so asking it twenty times for a twenty-permission role walks them twenty times on every invite acceptance. The kernel resolves the effective set once and compares — which is also why the comparison lives in the kernel rather than in each vertical: enumerating "who can do what" is the kernel's job, and this is that enumeration turned inward.

Bootstrap. The rule implies a tenant's first admin cannot assign themselves, and does not need to: the initial owner is seeded platform-side during provisioning, which is out-of-band host code that already holds the authority. Self-service begins at the second member.

Outside an operation, the host asks it. A harness route that grants a role without an operation around it asks the host instead: host.canAssign(tenantId, scopeId, principal, roleKey) gives the answer ctx.canAssign would give that principal, from the same role table and the same comparison, narrowing included. The member invite routes a vertical mounts from @substrat-run/vertical-auth/invite-routes do exactly that: after the vertical's own admin gate, an invite is created only at a role the inviter already covers, and revoked only at one — the role the stored invite confers. A vertical offering two invitable roles no longer lets every admin its gate admits confer the higher one.

Defaults ​

  • denyAllChecker — the secure default. A host without an explicit checker allows nothing.
  • UNSAFE_allowAllChecker — grants everything to everyone via a synthetic proof tuple. For tests and scratch scripts; the name is deliberately alarming. Never wire it into anything a tenant can reach.