Grant access
Grant access when an App runs for principals: a Role names who, a Grant names what, and the Runtime enforces both in every principal execution.
Before you start
Section titled “Before you start”-
Operations declared with
addMutationandaddQuery. Add queries and mutations covers their handlers. -
An App named
identitywith auserTemplate. The Runtime resolves a principal to an Item ofprn::identity:template/user, so import that App as a dependency.examples/permissions/identity-app.ts import type { AppSpec } from '@alpynehq/alpyne-types/builder';export const identityApp: AppSpec = (app) => {app.configure('identity');const user = app.addTemplate('user');user.addProperty('displayName', 'string');};
-
Declare App Roles. On the App, call
addRole(key, { label }). An App Role is assigned to principals. Callextendso that one Role includes another: a principal holdingapproveralso holdsviewerin every check and Grant. The Builder rejects a cycle of extensions.examples/permissions/leave-access-app.ts import type { AppSpec } from '@alpynehq/alpyne-types/builder';import { identityApp } from './identity-app';interface RequestInput {readonly id: string;}interface RequestSummary {readonly canReview: boolean;readonly managerNote?: string;readonly reason?: string;}export const leaveAccessApp: AppSpec = (app) => {app.configure('leave');app.addDependency('identity', identityApp);const viewer = app.addRole('viewer', { label: 'Viewer' });const approver = app.addRole('approver', { label: 'Approver' });approver.extend(viewer);const leaveRequest = app.addTemplate('leaveRequest');const reason = leaveRequest.addProperty('reason', 'string');const managerNote = leaveRequest.addProperty('managerNote', 'string');const requestedBy = leaveRequest.addProperty('requestedBy', 'id');const pending = leaveRequest.addState('pending').setDefault();const approved = leaveRequest.addState('approved');pending.addTransition('approve', approved);const requester = leaveRequest.addRole('requester', async (item) => {const principalId = item.properties.requestedBy;return typeof principalId === 'string' ? [principalId] : [];});const reviewer = leaveRequest.addRole('reviewer', async () => [approver.prn]);leaveRequest.addGrant(requester, [reason, requestedBy]);leaveRequest.addGrant(reviewer, [reason, requestedBy, managerNote]);const show = app.addQuery('show', async (input: RequestInput, current): Promise<RequestSummary | undefined> => {const item = await current.templates.leaveRequest.getItem(input.id);if (item === undefined) return undefined;const canReview = current.checkRole(current.roles.approver);const note = item.properties.managerNote;const why = item.properties.reason;return {canReview,managerNote: typeof note === 'string' ? note : undefined,reason: typeof why === 'string' ? why : undefined,};});show.input.addProperty('id', 'id').mandatory();show.output.object().addProperty('canReview', 'boolean').mandatory();show.addGrant(viewer);const approve = app.addMutation('approve', async (input: RequestInput, current) => {current.assertRole(current.roles.approver);const item = await current.templates.leaveRequest.getItem(input.id);if (item === undefined) throw new Error('Leave request not found');if (item.state?.value !== 'pending') return;await item.state.transitions.approve.execute({});});approve.input.addProperty('id', 'id').mandatory();approve.output.void();approve.addGrant(approver);}; -
Grant operations. On a Mutation or Query, call
addGrant(role)with an App Role. A principal invokes the operation when it holds any granted Role; Grants combine additively. An operation without a matching Grant rejects the call before the handler runs. Grants apply to principal executions; thesystemandsudocontexts carry Runtime-level authority inside their Workspace.examples/permissions/leave-access-app.ts import type { AppSpec } from '@alpynehq/alpyne-types/builder';import { identityApp } from './identity-app';interface RequestInput {readonly id: string;}interface RequestSummary {readonly canReview: boolean;readonly managerNote?: string;readonly reason?: string;}export const leaveAccessApp: AppSpec = (app) => {app.configure('leave');app.addDependency('identity', identityApp);const viewer = app.addRole('viewer', { label: 'Viewer' });const approver = app.addRole('approver', { label: 'Approver' });approver.extend(viewer);const leaveRequest = app.addTemplate('leaveRequest');const reason = leaveRequest.addProperty('reason', 'string');const managerNote = leaveRequest.addProperty('managerNote', 'string');const requestedBy = leaveRequest.addProperty('requestedBy', 'id');const pending = leaveRequest.addState('pending').setDefault();const approved = leaveRequest.addState('approved');pending.addTransition('approve', approved);const requester = leaveRequest.addRole('requester', async (item) => {const principalId = item.properties.requestedBy;return typeof principalId === 'string' ? [principalId] : [];});const reviewer = leaveRequest.addRole('reviewer', async () => [approver.prn]);leaveRequest.addGrant(requester, [reason, requestedBy]);leaveRequest.addGrant(reviewer, [reason, requestedBy, managerNote]);const show = app.addQuery('show', async (input: RequestInput, current): Promise<RequestSummary | undefined> => {const item = await current.templates.leaveRequest.getItem(input.id);if (item === undefined) return undefined;const canReview = current.checkRole(current.roles.approver);const note = item.properties.managerNote;const why = item.properties.reason;return {canReview,managerNote: typeof note === 'string' ? note : undefined,reason: typeof why === 'string' ? why : undefined,};});show.input.addProperty('id', 'id').mandatory();show.output.object().addProperty('canReview', 'boolean').mandatory();show.addGrant(viewer);const approve = app.addMutation('approve', async (input: RequestInput, current) => {current.assertRole(current.roles.approver);const item = await current.templates.leaveRequest.getItem(input.id);if (item === undefined) throw new Error('Leave request not found');if (item.state?.value !== 'pending') return;await item.state.transitions.approve.execute({});});approve.input.addProperty('id', 'id').mandatory();approve.output.void();approve.addGrant(approver);}; -
Declare Template Roles and grant Properties. On the Template, call
addRole(key, callback). The callback receives the Item and returns the access identifiers that hold the Role for that Item: principal Identifiers, App Role PRNs, or both. Then calladdGrant(role, properties). A principal sees an Item when at least one Grant’s Role matches, and it sees the union of the Properties those Grants list. Without a matching Grant,getItemreturnsundefinedfor that principal.examples/permissions/leave-access-app.ts import type { AppSpec } from '@alpynehq/alpyne-types/builder';import { identityApp } from './identity-app';interface RequestInput {readonly id: string;}interface RequestSummary {readonly canReview: boolean;readonly managerNote?: string;readonly reason?: string;}export const leaveAccessApp: AppSpec = (app) => {app.configure('leave');app.addDependency('identity', identityApp);const viewer = app.addRole('viewer', { label: 'Viewer' });const approver = app.addRole('approver', { label: 'Approver' });approver.extend(viewer);const leaveRequest = app.addTemplate('leaveRequest');const reason = leaveRequest.addProperty('reason', 'string');const managerNote = leaveRequest.addProperty('managerNote', 'string');const requestedBy = leaveRequest.addProperty('requestedBy', 'id');const pending = leaveRequest.addState('pending').setDefault();const approved = leaveRequest.addState('approved');pending.addTransition('approve', approved);const requester = leaveRequest.addRole('requester', async (item) => {const principalId = item.properties.requestedBy;return typeof principalId === 'string' ? [principalId] : [];});const reviewer = leaveRequest.addRole('reviewer', async () => [approver.prn]);leaveRequest.addGrant(requester, [reason, requestedBy]);leaveRequest.addGrant(reviewer, [reason, requestedBy, managerNote]);const show = app.addQuery('show', async (input: RequestInput, current): Promise<RequestSummary | undefined> => {const item = await current.templates.leaveRequest.getItem(input.id);if (item === undefined) return undefined;const canReview = current.checkRole(current.roles.approver);const note = item.properties.managerNote;const why = item.properties.reason;return {canReview,managerNote: typeof note === 'string' ? note : undefined,reason: typeof why === 'string' ? why : undefined,};});show.input.addProperty('id', 'id').mandatory();show.output.object().addProperty('canReview', 'boolean').mandatory();show.addGrant(viewer);const approve = app.addMutation('approve', async (input: RequestInput, current) => {current.assertRole(current.roles.approver);const item = await current.templates.leaveRequest.getItem(input.id);if (item === undefined) throw new Error('Leave request not found');if (item.state?.value !== 'pending') return;await item.state.transitions.approve.execute({});});approve.input.addProperty('id', 'id').mandatory();approve.output.void();approve.addGrant(approver);}; -
Check Roles inside handlers. Call
current.checkRole(current.roles.approver)to branch on a Role, andcurrent.assertRole(role)to reject the execution when the Role is missing; it throwsAssertRoleFailedError. Item-level checks areitem.checkRole(role)anditem.assertRole(role)with a Template Role, both asynchronous because the Role callback runs.examples/permissions/leave-access-app.ts import type { AppSpec } from '@alpynehq/alpyne-types/builder';import { identityApp } from './identity-app';interface RequestInput {readonly id: string;}interface RequestSummary {readonly canReview: boolean;readonly managerNote?: string;readonly reason?: string;}export const leaveAccessApp: AppSpec = (app) => {app.configure('leave');app.addDependency('identity', identityApp);const viewer = app.addRole('viewer', { label: 'Viewer' });const approver = app.addRole('approver', { label: 'Approver' });approver.extend(viewer);const leaveRequest = app.addTemplate('leaveRequest');const reason = leaveRequest.addProperty('reason', 'string');const managerNote = leaveRequest.addProperty('managerNote', 'string');const requestedBy = leaveRequest.addProperty('requestedBy', 'id');const pending = leaveRequest.addState('pending').setDefault();const approved = leaveRequest.addState('approved');pending.addTransition('approve', approved);const requester = leaveRequest.addRole('requester', async (item) => {const principalId = item.properties.requestedBy;return typeof principalId === 'string' ? [principalId] : [];});const reviewer = leaveRequest.addRole('reviewer', async () => [approver.prn]);leaveRequest.addGrant(requester, [reason, requestedBy]);leaveRequest.addGrant(reviewer, [reason, requestedBy, managerNote]);const show = app.addQuery('show', async (input: RequestInput, current): Promise<RequestSummary | undefined> => {const item = await current.templates.leaveRequest.getItem(input.id);if (item === undefined) return undefined;const canReview = current.checkRole(current.roles.approver);const note = item.properties.managerNote;const why = item.properties.reason;return {canReview,managerNote: typeof note === 'string' ? note : undefined,reason: typeof why === 'string' ? why : undefined,};});show.input.addProperty('id', 'id').mandatory();show.output.object().addProperty('canReview', 'boolean').mandatory();show.addGrant(viewer);const approve = app.addMutation('approve', async (input: RequestInput, current) => {current.assertRole(current.roles.approver);const item = await current.templates.leaveRequest.getItem(input.id);if (item === undefined) throw new Error('Leave request not found');if (item.state?.value !== 'pending') return;await item.state.transitions.approve.execute({});});approve.input.addProperty('id', 'id').mandatory();approve.output.void();approve.addGrant(approver);}; -
Assign Roles to principals. In a write execution, call
current.roles.approver.assign(user)with the user Item, orassign('current')for the executing principal.revoke(user)removes the Role and returns whether the principal held it. The Runtime resolves a principal’s Roles, including extended ones, when it creates the execution.examples/permissions/leave-access-app.test.ts import type { AlpyneAuthContext, ReadRuntimeInstance } from '@alpynehq/alpyne-types/runtime';import { createHarnessInstance } from '@pyn-backend/platform-harness-public';import { createTestPlatformService } from '@pyn-backend/platform-service-test';import { createTestCronService } from '@pyn-backend/service-cron-test';import { createTestSystemService } from '@pyn-backend/service-system-test';import { createTestLoggerService } from '@pyn-backend/test-services-logger';import { randomUUID } from 'node:crypto';import { describe, expect, it } from 'vitest';import { leaveAccessApp } from './leave-access-app';const setup = async () => {const system = createTestSystemService();const logger = createTestLoggerService();const cron = createTestCronService({ system });const platform = createTestPlatformService({ cron, logger, system });const harness = await createHarnessInstance({ cron, logger, platform, system }, leaveAccessApp);const workspace = await harness.createWorkspace();const ids = await workspace.write(async (ctx) => {const parent = await ctx.getWorkspaceItem();const user = ctx.apps.identity.templates.user;const alice = await user.createItem(parent, { properties: { displayName: 'Alice' } });const bob = await user.createItem(parent, { properties: { displayName: 'Bob' } });const carol = await user.createItem(parent, { properties: { displayName: 'Carol' } });const request = await parent.createChild(ctx.apps.leave.templates.leaveRequest, {properties: { managerNote: 'Check the roster', reason: 'Holiday', requestedBy: alice.id },});await ctx.apps.leave.roles.viewer.assign({ id: alice.id, templatePrn: 'prn::identity:template/user' });await ctx.apps.leave.roles.approver.assign({ id: bob.id, templatePrn: 'prn::identity:template/user' });await ctx.apps.leave.roles.viewer.assign({ id: carol.id, templatePrn: 'prn::identity:template/user' });return { alice: alice.id, bob: bob.id, carol: carol.id, request: request.id };});const asPrincipal = async (principalId: string) => {const access: AlpyneAuthContext = {identityId: randomUUID(),principalId,rolePrns: [],sessionId: randomUUID(),type: 'principal',workspaceId: workspace.workspaceId,};return await platform.createInstance(access);};const show = async (principalId: string) => {const instance = await asPrincipal(principalId);return await instance.execute('read', async (_root, ctx: ReadRuntimeInstance) => {const current = ctx.apps.leave;return await current.queries.show.handler({ id: ids.request }, current, ctx);});};const approve = async (principalId: string) => {const instance = await asPrincipal(principalId);return await instance.execute('readwrite', { payload: {}, traceId: 'test' }, async (ctx) => {const current = ctx.apps.leave;await current.mutations.approve.handler({ id: ids.request }, current, ctx);});};return { approve, ids, show, workspace };};describe('leave request access', () => {it('shows each principal the Properties their Roles are granted', async () => {const { ids, show } = await setup();const requester = await show(ids.alice);const reviewer = await show(ids.bob);const bystander = await show(ids.carol);expect(requester).toStrictEqual({ canReview: false, managerNote: undefined, reason: 'Holiday' });expect(reviewer).toStrictEqual({ canReview: true, managerNote: 'Check the roster', reason: 'Holiday' });expect(bystander).toBeUndefined();});it('allows the approver and rejects other principals on a granted Mutation', async () => {const { approve, ids, workspace } = await setup();await expect(approve(ids.alice)).rejects.toThrow();await approve(ids.bob);await workspace.read(async (ctx) => {expect((await ctx.getItem(ids.request))?.state?.value).toBe('approved');});expect.assertions(2);});}); -
Execute as a principal. Build a
principalauth context with the user’s Identifier asprincipalId, pass it toplatform.createInstance, and callexecute('read', fn)orexecute('readwrite', event, fn)on the instance. Invoke the operation throughcurrent.queries.show.handlerorcurrent.mutations.approve.handlerso the Grant check runs.examples/permissions/leave-access-app.test.ts import type { AlpyneAuthContext, ReadRuntimeInstance } from '@alpynehq/alpyne-types/runtime';import { createHarnessInstance } from '@pyn-backend/platform-harness-public';import { createTestPlatformService } from '@pyn-backend/platform-service-test';import { createTestCronService } from '@pyn-backend/service-cron-test';import { createTestSystemService } from '@pyn-backend/service-system-test';import { createTestLoggerService } from '@pyn-backend/test-services-logger';import { randomUUID } from 'node:crypto';import { describe, expect, it } from 'vitest';import { leaveAccessApp } from './leave-access-app';const setup = async () => {const system = createTestSystemService();const logger = createTestLoggerService();const cron = createTestCronService({ system });const platform = createTestPlatformService({ cron, logger, system });const harness = await createHarnessInstance({ cron, logger, platform, system }, leaveAccessApp);const workspace = await harness.createWorkspace();const ids = await workspace.write(async (ctx) => {const parent = await ctx.getWorkspaceItem();const user = ctx.apps.identity.templates.user;const alice = await user.createItem(parent, { properties: { displayName: 'Alice' } });const bob = await user.createItem(parent, { properties: { displayName: 'Bob' } });const carol = await user.createItem(parent, { properties: { displayName: 'Carol' } });const request = await parent.createChild(ctx.apps.leave.templates.leaveRequest, {properties: { managerNote: 'Check the roster', reason: 'Holiday', requestedBy: alice.id },});await ctx.apps.leave.roles.viewer.assign({ id: alice.id, templatePrn: 'prn::identity:template/user' });await ctx.apps.leave.roles.approver.assign({ id: bob.id, templatePrn: 'prn::identity:template/user' });await ctx.apps.leave.roles.viewer.assign({ id: carol.id, templatePrn: 'prn::identity:template/user' });return { alice: alice.id, bob: bob.id, carol: carol.id, request: request.id };});const asPrincipal = async (principalId: string) => {const access: AlpyneAuthContext = {identityId: randomUUID(),principalId,rolePrns: [],sessionId: randomUUID(),type: 'principal',workspaceId: workspace.workspaceId,};return await platform.createInstance(access);};const show = async (principalId: string) => {const instance = await asPrincipal(principalId);return await instance.execute('read', async (_root, ctx: ReadRuntimeInstance) => {const current = ctx.apps.leave;return await current.queries.show.handler({ id: ids.request }, current, ctx);});};const approve = async (principalId: string) => {const instance = await asPrincipal(principalId);return await instance.execute('readwrite', { payload: {}, traceId: 'test' }, async (ctx) => {const current = ctx.apps.leave;await current.mutations.approve.handler({ id: ids.request }, current, ctx);});};return { approve, ids, show, workspace };};describe('leave request access', () => {it('shows each principal the Properties their Roles are granted', async () => {const { ids, show } = await setup();const requester = await show(ids.alice);const reviewer = await show(ids.bob);const bystander = await show(ids.carol);expect(requester).toStrictEqual({ canReview: false, managerNote: undefined, reason: 'Holiday' });expect(reviewer).toStrictEqual({ canReview: true, managerNote: 'Check the roster', reason: 'Holiday' });expect(bystander).toBeUndefined();});it('allows the approver and rejects other principals on a granted Mutation', async () => {const { approve, ids, workspace } = await setup();await expect(approve(ids.alice)).rejects.toThrow();await approve(ids.bob);await workspace.read(async (ctx) => {expect((await ctx.getItem(ids.request))?.state?.value).toBe('approved');});expect.assertions(2);});});
Verify
Section titled “Verify”The test below reads one request as three principals and approves it as two of them.
import type { AlpyneAuthContext, ReadRuntimeInstance } from '@alpynehq/alpyne-types/runtime';import { createHarnessInstance } from '@pyn-backend/platform-harness-public';import { createTestPlatformService } from '@pyn-backend/platform-service-test';import { createTestCronService } from '@pyn-backend/service-cron-test';import { createTestSystemService } from '@pyn-backend/service-system-test';import { createTestLoggerService } from '@pyn-backend/test-services-logger';import { randomUUID } from 'node:crypto';import { describe, expect, it } from 'vitest';
import { leaveAccessApp } from './leave-access-app';
const setup = async () => { const system = createTestSystemService(); const logger = createTestLoggerService(); const cron = createTestCronService({ system }); const platform = createTestPlatformService({ cron, logger, system }); const harness = await createHarnessInstance({ cron, logger, platform, system }, leaveAccessApp); const workspace = await harness.createWorkspace();
const ids = await workspace.write(async (ctx) => { const parent = await ctx.getWorkspaceItem(); const user = ctx.apps.identity.templates.user; const alice = await user.createItem(parent, { properties: { displayName: 'Alice' } }); const bob = await user.createItem(parent, { properties: { displayName: 'Bob' } }); const carol = await user.createItem(parent, { properties: { displayName: 'Carol' } }); const request = await parent.createChild(ctx.apps.leave.templates.leaveRequest, { properties: { managerNote: 'Check the roster', reason: 'Holiday', requestedBy: alice.id }, });
await ctx.apps.leave.roles.viewer.assign({ id: alice.id, templatePrn: 'prn::identity:template/user' }); await ctx.apps.leave.roles.approver.assign({ id: bob.id, templatePrn: 'prn::identity:template/user' }); await ctx.apps.leave.roles.viewer.assign({ id: carol.id, templatePrn: 'prn::identity:template/user' }); return { alice: alice.id, bob: bob.id, carol: carol.id, request: request.id }; });
const asPrincipal = async (principalId: string) => { const access: AlpyneAuthContext = { identityId: randomUUID(), principalId, rolePrns: [], sessionId: randomUUID(), type: 'principal', workspaceId: workspace.workspaceId, }; return await platform.createInstance(access); };
const show = async (principalId: string) => { const instance = await asPrincipal(principalId); return await instance.execute('read', async (_root, ctx: ReadRuntimeInstance) => { const current = ctx.apps.leave; return await current.queries.show.handler({ id: ids.request }, current, ctx); }); };
const approve = async (principalId: string) => { const instance = await asPrincipal(principalId); return await instance.execute('readwrite', { payload: {}, traceId: 'test' }, async (ctx) => { const current = ctx.apps.leave; await current.mutations.approve.handler({ id: ids.request }, current, ctx); }); };
return { approve, ids, show, workspace };};
describe('leave request access', () => { it('shows each principal the Properties their Roles are granted', async () => { const { ids, show } = await setup();
const requester = await show(ids.alice); const reviewer = await show(ids.bob); const bystander = await show(ids.carol);
expect(requester).toStrictEqual({ canReview: false, managerNote: undefined, reason: 'Holiday' }); expect(reviewer).toStrictEqual({ canReview: true, managerNote: 'Check the roster', reason: 'Holiday' }); expect(bystander).toBeUndefined(); });
it('allows the approver and rejects other principals on a granted Mutation', async () => { const { approve, ids, workspace } = await setup();
await expect(approve(ids.alice)).rejects.toThrow(); await approve(ids.bob);
await workspace.read(async (ctx) => { expect((await ctx.getItem(ids.request))?.state?.value).toBe('approved'); }); expect.assertions(2); });});From the repository root, run:
pnpm run cli test alpynehq/alpyne/website/examples/permissions/You should see:
Test Files 1 passed (1) Tests 2 passed (2)Alice holds viewer and is the requester, so show returns reason and no managerNote, and canReview is false. Bob holds approver, which extends viewer, so show returns both Properties and canReview is true. Carol holds viewer but no Template Role matches her, so getItem returns undefined and the Query returns undefined. Alice’s call to approve rejects before the handler runs; Bob’s call moves the request to approved.
Related
Section titled “Related”- Workspaces and access for auth contexts, Roles and Grants as a model.
- Authorization for the normative rules on how Grants combine and filter.
- Add queries and mutations for the operations that Grants protect.
- Test an app for the harness that the principal instances above run in.
AppRoleBuilderandTemplateBuilder.addGrantfor the full declaration API.

