Skip to content

Roles and permissions

For: an app developer whose organizations need rights by name, such as “write a project”, and not only by rank.

What it does: core gives each role a set of actions. Your routes ask auth.hasPermission, and core answers from the role that the person holds now.

  • A working setup of organizations.
  • A list of the resources of your app and their actions, for the config key organizations.statements.
  1. Add your resources to organizations.statements.
  2. Give each role its rank and its actions in organizations.roles, or keep ranks.
  3. Set organizations.dynamicRoles when each organization must store its own roles.
  4. In each route that writes, call auth.hasPermission(caller, { organizationId, permissions }).
The roles config and a checked route
import { type Auth, createAuth, type MailPort, type StorageAdapter } from "@authtempo/core";
/**
* Roles by name. `statements` adds the app's own resource. `roles` gives each
* role a rank and its exact actions, so `ranks` is not set. `dynamicRoles`
* lets each organization store its own roles beside these.
*/
export function createRolesAuth(deps: { storage: StorageAdapter; mail: MailPort; secret: string }) {
return createAuth({
baseURL: "https://api.example.com",
appURL: "https://app.example.com",
trustedOrigins: ["https://app.example.com"],
secret: deps.secret,
storage: deps.storage,
mail: deps.mail,
organizations: {
statements: { project: ["read", "write"] },
roles: {
member: { rank: 1, permissions: { member: ["read"], project: ["read"] } },
admin: {
rank: 2,
permissions: {
member: ["read", "create", "update", "delete"],
ac: ["read"],
project: ["read", "write"],
},
},
owner: {
rank: 3,
permissions: {
organization: ["update", "delete"],
member: ["read", "create", "update", "delete"],
invitation: ["read", "create", "cancel"],
ac: ["read", "create", "update", "delete"],
project: ["read", "write"],
},
},
},
// At most 50 stored roles in each organization, the default.
dynamicRoles: { maxPerOrganization: 50 },
},
});
}
/**
* A route of the app that writes a project. The server check decides: it
* reads the caller's role at each request, so a narrowed role applies at once.
*/
export async function writeProject(
auth: Auth,
request: Request,
organizationId: string,
): Promise<Response> {
const caller = await auth.caller(request);
if (!caller) return Response.json({ error: "unauthorized" }, { status: 401 });
const allowed = await auth.hasPermission(caller, {
organizationId,
permissions: { project: ["write"] },
});
if (!allowed) return Response.json({ error: "forbidden" }, { status: 403 });
return Response.json({ written: true });
}
  1. Create a stored role with client.organizations.roles.create, then give it to a member.
  2. Narrow the role with client.organizations.roles.update. The next request of each holder has the smaller set.
Narrow a stored role as a test
import { describe, expect, it } from "vitest";
import { API, call, harness, signIn } from "../support/harness.ts";
import { createRolesAuth, writeProject } from "./roles.ts";
describe("roles and permissions", () => {
it("a dynamic role narrows at the next request", async () => {
const h = harness();
const auth = createRolesAuth(h);
const ada = await signIn(auth, h, "ada@example.com");
const bo = await signIn(auth, h, "bo@example.com");
const boUser = (
(await (await call(auth, "GET", "/auth/session", undefined, { cookie: bo })).json()) as {
user: { id: string };
}
).user;
const created = await call(
auth,
"POST",
"/auth/organizations/create",
{ slug: "acme", name: "Acme" },
{ cookie: ada },
);
const { organization } = (await created.json()) as { organization: { id: string } };
const organizationId = organization.id;
// The owner stores the role "editor" for this organization only, and gives it to Bo.
const role = await call(
auth,
"POST",
"/auth/organizations/roles/create",
{ organizationId, name: "editor", rank: 1, permissions: { project: ["read", "write"] } },
{ cookie: ada },
);
expect(role.status).toBe(200);
const added = await call(
auth,
"POST",
"/auth/organizations/members/add",
{ organizationId, userId: boUser.id, role: "editor" },
{ cookie: ada },
);
expect(added.status).toBe(200);
const write = () =>
writeProject(
auth,
new Request(`${API}/projects`, { headers: { cookie: bo } }),
organizationId,
);
expect((await write()).status).toBe(200);
// The owner takes "write" from the role. Bo's next request has no write.
const narrowed = await call(
auth,
"POST",
"/auth/organizations/roles/update",
{ organizationId, name: "editor", permissions: { project: ["read"] } },
{ cookie: ada },
);
expect(narrowed.status).toBe(200);
expect((await write()).status).toBe(403);
// The client check reads the same rule, and only hides a control.
const check = await call(
auth,
"POST",
"/auth/organizations/has-permission",
{ organizationId, permissions: { project: ["read"] } },
{ cookie: bo },
);
expect(await check.json()).toEqual({ success: true });
});
});

A statement set maps a resource to a list of actions, such as { project: ["read", "write"] }. A resource or an action name matches ^[a-z][a-zA-Z0-9-]{0,31}$. Core owns seven resources:

Resource Actions
organization update, delete
member read, create, update, delete
invitation read, create, cancel
team create, update, delete
ac read, create, update, delete (the stored roles)
apiToken read, create, update, revoke (the organization tokens)
audit read (the organization audit)

organizations.statements adds the resources of your app. createAuth refuses a core name, a bad name, an empty list, and a repeated action.

  • ranks (the default) maps each role to a rank. Core derives the core actions of each role from the table below. A role of ranks holds no action of your own resources.
  • roles maps each role to { rank, permissions }. The role holds exactly its permissions, and each one must be a known action.
  • Set one form, never both. Each form names owner, and a role name holds no comma.
  • A member may hold several roles joined by a comma, such as member,billing. The set is the union of the parts. A part that no table names adds nothing.

In the ranks form, a role holds an action when its rank is at least the rank of the role in this table. With the default ranks, every answer equals the rank rules of earlier versions.

Action Lowest role
member:read, ac:read viewer
organization:update admin
member:create, member:update, member:delete admin
invitation:read, invitation:create, invitation:cancel admin
team:create, team:update, team:delete admin
ac:create, ac:update, ac:delete admin
apiToken:read, apiToken:create, apiToken:update, apiToken:revoke admin
organization:delete owner
audit:read owner

A slug change needs organization:update and the owner rank too. The audit shows the acts of each member, so in the ranks form only a role at the owner rank reads it. In the roles form, a role holds audit:read only when its permissions list it. A stored role never holds audit:read (rule 3 of the dynamic roles).

  • A caller grants a role only when its rank is at most the caller’s rank, and its actions are a subset of the caller’s. This holds at an add, a role change, an invite, and a stored role write.
  • A caller changes or removes another member under the same two conditions.
  • An owner is a member who holds a config role at the owner rank. The last owner cannot leave, be demoted, or be removed.
  • Two owner writes at the same moment cannot both succeed. The second answers conflict.

With organizations.dynamicRoles, each organization stores its own roles beside the config roles. The role routes follow eight rules:

  1. A name is one role name. It is not a config role, the platform role, or owner. A taken name answers role_taken.
  2. A rank is from 1 to the caller’s rank, and below the owner rank.
  3. The actions are known names and a subset of the caller’s actions. They never name audit, also for the owner: a create or an update with it answers statement_not_grantable. A row from before schema 18 can hold an app statement that was named audit. Core leaves that statement out of the row, and the row keeps its other actions.
  4. The list and the get need ac:read. The create, the update, and the delete need ac:create, ac:update, and ac:delete, and a fresh session.
  5. A delete answers role_in_use while a member or a pending invitation holds the role. A create answers the same while one holds the name.
  6. Core keeps no cache. A narrow applies at the next request.
  7. A stored row with a bad shape grants nothing. Core writes one log line authtempo: role row invalid <row id>, and the list leaves the row out.
  8. The cap maxPerOrganization (default 50) counts inside the transaction, before the write. A create at the cap answers role_limit.

An update or a delete of a stored role also needs the role’s rank and actions. While dynamic roles are on, a grant refuses a role part that neither the config nor a stored role names.

auth.hasPermission(caller, { organizationId, permissions }) answers true only when the caller holds every action in the organization. Any failure answers false, and it never throws.

  • A session reads its member role at each request.
  • A user token reads its user’s role, narrowed by its own permissions. It grants nothing outside its bound organization.
  • An organization token reads its own set, in its own organization only.
  • An OAuth caller grants nothing. Check its scopes yourself.
  • An empty request, an unknown resource, and an unknown action answer false.

auth.permissionsOf(caller, organizationId) answers the role string and its set. POST /organizations/has-permission and GET /organizations/permissions give the same answers to a session.

Core has no OR connector. To accept either of two actions, write two checks.

client.organizations.hasPermission asks the server. roleHasPermission(table, role, permissions) of @authtempo/client checks a static role table with no request. A client check only hides a control. The server check decides.

  • forbidden_rank: the caller lacks the action, or the role to grant has more actions than the caller.
  • invalid_body: an unknown action, a name of the config, or a rank above the caller or at the owner rank.
  • role_taken: the organization already stores a role of that name.
  • statement_not_grantable: a stored role named audit. Remove it. Only the owner rank reads the audit.
  • role_in_use: a member or a pending invitation holds the role. Change those roles first.
  • role_limit: the organization stores maxPerOrganization roles. Delete one first.
  • session_not_fresh: a role write needs a fresh session. Re-authenticate, then send it again.
  • conflict: another write changed the role or the owner at the same moment. Read it again and retry.
  • unauthorized: the route needs a session. A token answers 401.
  • invalid_token: an accept of an invitation whose role no table names now.