auth.rbac
Roles with inheritance, permission checks with wildcards and ownership, and a generated per-role access-test matrix.
1.0.0 · published 2026-10-10 by charlie · Anterra
Pinned by 54 tests, run in TypeScript, Python and Rust.resolveRoles 16 · hasPermission 15 · checkAccess 13 · accessMatrix 10
What it does
Role-based access control as data: a policy of roles, what each inherits and what each grants, and four pure functions over it. The policy lives in your code or your database; these answer "who may do what" the same way in a TypeScript front end, a Python API and a Rust service.
const policy = {
roles: [
{ name: "viewer", inherits: [], permissions: ["posts:read", "comments:read"] },
{ name: "author", inherits: ["viewer"], permissions: ["posts:create", "posts:update:own", "posts:delete:own", "comments:*:own"] },
{ name: "editor", inherits: ["author"], permissions: ["posts:update", "posts:publish"] },
{ name: "admin", inherits: [], permissions: ["*"] },
],
permissions: ["posts:read", "posts:update", "posts:delete", "comments:delete"],
};
checkAccess(policy, { id: user.id, roles: user.roles }, "update", { resourceType: "posts", id: post.id, ownerId: post.authorId });
// { allowed: true, reason: "granted_own", grant: "posts:update:own" }
The functions
A group: 4 functions that work together, each in its own file, each pinned by its own tests in TypeScript, Python and Rust. A project can install only the ones it calls.
- resolveRoles (policy: RbacPolicy, roles: string[]) -> ResolvedRoles
- hasPermission (policy: RbacPolicy, roles: string[], permission: string) -> bool
- checkAccess (policy: RbacPolicy, subject: AccessSubject, action: string, resource: AccessResource) -> AccessDecision
- accessMatrix (policy: RbacPolicy) -> AccessTestCase[]
The types it declares, generated into your project
/** One role: what it inherits and what it grants. */
export interface RoleDef {
readonly name: string;
/** roles whose grants this one also has */
readonly inherits: readonly string[];
/** grants: resource:action, resource:action:own, with * for any resource or action; * alone grants everything */
readonly permissions: readonly string[];
}
/** The app's whole role model. */
export interface RbacPolicy {
readonly roles: readonly RoleDef[];
/** every concrete resource:action the app checks, for accessMatrix */
readonly permissions: readonly string[];
}
/** A user's effective roles and grants. */
export interface ResolvedRoles {
readonly roles: readonly string[];
readonly permissions: readonly string[];
}
/** Who is asking. */
export interface AccessSubject {
readonly id: string;
readonly roles: readonly string[];
}
/** What is being acted on. */
export interface AccessResource {
/** the resource type, as it appears in grants (posts) */
readonly resourceType: string;
readonly id: string;
/** the id of the subject who owns it; null when nobody does */
readonly ownerId: string | null;
}
export type AccessReason = "granted" | "granted_own" | "not_owner" | "denied";
/** Whether the action is allowed, and why. */
export interface AccessDecision {
readonly allowed: boolean;
readonly reason: AccessReason;
/** the grant that allowed it, first in sorted order; null when not allowed */
readonly grant: string | null;
}
/** One expected outcome, generated from the policy, for an app's own test suite. */
export interface AccessTestCase {
/** such as "editor may update posts they own" */
readonly name: string;
readonly role: string;
readonly resourceType: string;
readonly action: string;
/** true: the subject owns the resource; false: someone else does */
readonly own: boolean;
readonly allowed: boolean;
}
Once installed, your code imports each one from the group's module.
resolveRoles throws on bad input 16 tests
export function resolveRoles(policy: RbacPolicy, roles: readonly string[]): ResolvedRoles
| policy | RbacPolicy | the app's roles and permissions; checked whole every call (names, grants, inheritance cycles) |
| roles | string[] | the roles a user holds |
| returns | ResolvedRoles | those roles plus every role they inherit, and all their grants, each deduplicated and sorted |
For example
resolveRoles(roles ×4, permissions posts:read, posts:update, posts:delete, comments:delete, editor)→ roles author, editor, viewer, permissions comments:*:own, comments:read, posts:create, posts:delete:own, posts:publish, posts:read, posts:update, posts:update:own an editor inherits author and viewer, and every grant of the three, sortedresolveRoles(roles ×4, permissions posts:read, posts:update, posts:delete, comments:delete, )→ roles , permissions no roles, nothing grantedresolveRoles(roles ×4, permissions posts:read, posts:update, posts:delete, comments:delete, viewer, viewer)→ roles viewer, permissions comments:read, posts:read a role given twice counts once
import { resolveRoles } from "#fune/auth.rbac@^1";
import type { RbacPolicy, ResolvedRoles, RoleDef } from "./auth_rbac_types.ts";
// One permission segment: lower-case ASCII letters, digits, _ and -.
const SEGMENT = /^[a-z0-9_-]+$/;
/** A grant as [resource, action, own]; "*" alone is "*:*". Throws on anything else. */
export function parseGrant(grant: string): [string, string, boolean] {
if (typeof grant !== "string") throw new Error(`invalid grant ${String(grant)}`);
if (grant === "*") return ["*", "*", false];
const parts = grant.split(":");
const ok = (s: string) => s === "*" || SEGMENT.test(s);
if ((parts.length === 2 || (parts.length === 3 && parts[2] === "own")) && ok(parts[0]) && ok(parts[1])) {
return [parts[0], parts[1], parts.length === 3];
}
throw new Error(`invalid grant ${grant}`);
}
/** A concrete permission as [resource, action, own]: no wildcards, and :own only where asked. */
export function parsePermission(permission: string, allowOwn: boolean): [string, string, boolean] {
if (typeof permission === "string") {
const parts = permission.split(":");
const shape = parts.length === 2 || (allowOwn && parts.length === 3 && parts[2] === "own");
if (shape && SEGMENT.test(parts[0]) && SEGMENT.test(parts[1])) return [parts[0], parts[1], parts.length === 3];
}
throw new Error(`invalid permission ${String(permission)}`);
}
/**
* The policy checked whole: unique non-empty names, inherited roles that
* exist, well-formed grants, no inheritance cycle (found by a depth-first
* walk over the roles in policy order, so the reported cycle is always the
* same one), and concrete permissions. Returns the roles by name.
*/
export function checkPolicy(policy: RbacPolicy): Map<string, RoleDef> {
if (typeof policy !== "object" || policy === null || !Array.isArray(policy.roles) || !Array.isArray(policy.permissions)) {
throw new TypeError("policy must be an RbacPolicy");
}
const byName = new Map<string, RoleDef>();
for (const role of policy.roles) {
if (typeof role.name !== "string" || role.name === "") throw new Error("role name must be a non-empty string");
if (byName.has(role.name)) throw new Error(`duplicate role ${role.name}`);
byName.set(role.name, role);
}
for (const role of policy.roles) {
for (const parent of role.inherits) if (!byName.has(parent)) throw new Error(`unknown role ${parent}`);
for (const grant of role.permissions) parseGrant(grant);
}
const state = new Map<string, number>();
const stack: string[] = [];
const visit = (name: string): void => {
state.set(name, 1);
stack.push(name);
for (const parent of (byName.get(name) as RoleDef).inherits) {
const seen = state.get(parent);
if (seen === 1) {
const path = [...stack.slice(stack.indexOf(parent)), parent];
throw new Error(`role inheritance cycle: ${path.join(" -> ")}`);
}
if (seen === undefined) visit(parent);
}
stack.pop();
state.set(name, 2);
};
for (const role of policy.roles) if (!state.has(role.name)) visit(role.name);
for (const permission of policy.permissions) parsePermission(permission, false);
return byName;
}
/** The roles given plus every role they inherit, deduplicated and sorted. */
export function expandRoles(byName: Map<string, RoleDef>, roles: readonly string[]): string[] {
if (!Array.isArray(roles)) throw new TypeError("roles must be a list of role names");
const seen = new Set<string>();
const queue = [...roles];
while (queue.length > 0) {
const name = queue.shift() as string;
if (seen.has(name)) continue;
const role = byName.get(name);
if (role === undefined) throw new Error(`unknown role ${name}`);
seen.add(name);
queue.push(...role.inherits);
}
return [...seen].sort();
}
/** Every grant of these (already expanded) roles, deduplicated and sorted. */
export function grantsOf(byName: Map<string, RoleDef>, roles: readonly string[]): string[] {
const grants = new Set<string>();
for (const name of roles) for (const grant of (byName.get(name) as RoleDef).permissions) grants.add(grant);
return [...grants].sort();
}
/** What a user holding these roles effectively is and may do. */
export function resolveRoles(policy: RbacPolicy, roles: readonly string[]): ResolvedRoles {
const byName = checkPolicy(policy);
const all = expandRoles(byName, roles);
return { roles: all, permissions: grantsOf(byName, all) };
}hasPermission throws on bad input 15 tests
export function hasPermission(policy: RbacPolicy, roles: readonly string[], permission: string): boolean
| policy | RbacPolicy | |
| roles | string[] | the roles a user holds |
| permission | string | resource:action (may they do it to anything?) or resource:action:own (may they do it to their own?) |
| returns | bool |
For example
hasPermission(roles ×4, permissions posts:read, posts:update, posts:delete, comments:delete, viewer, posts:read)→ true a viewer may read postshasPermission(roles ×4, permissions posts:read, posts:update, posts:delete, comments:delete, viewer, posts:update)→ false a viewer may not update postshasPermission(roles ×4, permissions posts:read, posts:update, posts:delete, comments:delete, author, posts:update)→ false an author may not update every post: their grant is :own
import { hasPermission } from "#fune/auth.rbac@^1";
Imports name this capability’s declared dependencies, which fune builds next to it in your project; each one links to its page.
import type { RbacPolicy } from "./auth_rbac_types.ts";
import { checkPolicy, expandRoles, grantsOf, parseGrant, parsePermission } from "./auth_rbac_resolve_roles.ts"; ← resolveRoles, another function of this group · built into the same file, even by a slim install
/**
* Whether these roles grant a permission. resource:action asks about every
* resource of the type, so only an unrestricted grant answers yes;
* resource:action:own asks about the user's own, which an :own grant also
* covers.
*/
export function hasPermission(policy: RbacPolicy, roles: readonly string[], permission: string): boolean {
const byName = checkPolicy(policy);
const grants = grantsOf(byName, expandRoles(byName, roles));
const [resource, action, own] = parsePermission(permission, true);
return grants.some((grant) => {
const [r, a, ownOnly] = parseGrant(grant);
return (r === "*" || r === resource) && (a === "*" || a === action) && (!ownOnly || own);
});
}checkAccess throws on bad input 13 tests
export function checkAccess(policy: RbacPolicy, subject: AccessSubject, action: string, resource: AccessResource): AccessDecision
| policy | RbacPolicy | |
| subject | AccessSubject | who is asking: their id and roles |
| action | string | what they want to do, such as update |
| resource | AccessResource | what they want to do it to: its resourceType (posts), id and owner |
| returns | AccessDecision | allowed or not, why, and the grant that allowed it |
For example
checkAccess(roles ×4, permissions posts:read, posts:update, posts:delete, comments:delete, id u1, roles editor, update, resource type posts, id p1, owner id u2)→ allowed true, reason granted, grant posts:update an editor updates someone else's postcheckAccess(roles ×4, permissions posts:read, posts:update, posts:delete, comments:delete, id u1, roles author, update, resource type posts, id p1, owner id u1)→ allowed true, reason granted_own, grant posts:update:own an author updates their own postcheckAccess(roles ×4, permissions posts:read, posts:update, posts:delete, comments:delete, id u1, roles author, update, resource type posts, id p1, owner id u2)→ allowed false, reason not_owner, grant — an author may not update someone else's post
import { checkAccess } from "#fune/auth.rbac@^1";
Imports name this capability’s declared dependencies, which fune builds next to it in your project; each one links to its page.
import type { AccessDecision, AccessResource, AccessSubject, RbacPolicy } from "./auth_rbac_types.ts";
import { checkPolicy, expandRoles, grantsOf, parseGrant, parsePermission } from "./auth_rbac_resolve_roles.ts"; ← resolveRoles, another function of this group · built into the same file, even by a slim install
/**
* May this subject do this action to this resource? An unrestricted grant
* allows it; an :own grant allows it only when the subject owns the
* resource. A resource with no owner is nobody's own.
*/
export function checkAccess(policy: RbacPolicy, subject: AccessSubject, action: string, resource: AccessResource): AccessDecision {
const byName = checkPolicy(policy);
if (typeof subject.id !== "string" || subject.id === "") throw new Error("subject.id must be a non-empty string");
const grants = grantsOf(byName, expandRoles(byName, subject.roles));
const [type, act] = parsePermission(`${resource.resourceType}:${action}`, false);
let ownGrant: string | null = null;
for (const grant of grants) {
const [r, a, ownOnly] = parseGrant(grant);
if ((r === "*" || r === type) && (a === "*" || a === act)) {
if (!ownOnly) return { allowed: true, reason: "granted", grant };
if (ownGrant === null) ownGrant = grant;
}
}
if (ownGrant !== null) {
const owner = resource.ownerId ?? null;
if (owner !== null && owner === subject.id) return { allowed: true, reason: "granted_own", grant: ownGrant };
return { allowed: false, reason: "not_owner", grant: null };
}
return { allowed: false, reason: "denied", grant: null };
}accessMatrix throws on bad input 10 tests
export function accessMatrix(policy: RbacPolicy): readonly AccessTestCase[]
| policy | RbacPolicy | |
| returns | AccessTestCase[] | one case per role, permission and ownership (not owned, owned), in policy order: run each through checkAccess in your own tests |
For example
accessMatrix(roles ×2, permissions posts:read, posts:update)→ ×8 viewer and author over reading and updating postsaccessMatrix(roles , permissions )→ an empty policy has no casesaccessMatrix(roles ×1, permissions )→ roles without permissions have no cases
import { accessMatrix } from "#fune/auth.rbac@^1";
Imports name this capability’s declared dependencies, which fune builds next to it in your project; each one links to its page.
import type { AccessTestCase, RbacPolicy } from "./auth_rbac_types.ts";
import { checkPolicy, parsePermission } from "./auth_rbac_resolve_roles.ts"; ← resolveRoles, another function of this group · built into the same file, even by a slim install
import { checkAccess } from "./auth_rbac_check_access.ts"; ← checkAccess, another function of this group · built into the same file, even by a slim install
/**
* The expected answer for every role, every permission the app declares,
* and both ownerships, in policy order: a test table generated from the
* policy, so a change to a role shows up as changed expectations in review.
*/
export function accessMatrix(policy: RbacPolicy): readonly AccessTestCase[] {
checkPolicy(policy);
const cases: AccessTestCase[] = [];
for (const role of policy.roles) {
for (const permission of policy.permissions) {
const [resourceType, action] = parsePermission(permission, false);
for (const own of [false, true]) {
const decision = checkAccess(policy, { id: "subject", roles: [role.name] }, action, {
resourceType,
id: "resource",
ownerId: own ? "subject" : "someone-else",
});
const verb = decision.allowed ? "may" : "may not";
const name = own
? `${role.name} ${verb} ${action} ${resourceType} they own`
: `${role.name} ${verb} ${action} any ${resourceType}`;
cases.push({ name, role: role.name, resourceType, action, own, allowed: decision.allowed });
}
}
}
return cases;
}Install
fune build
With that line in your source, in a TypeScript project (language typescript in fune.project), fune build resolves it and nothing else, pins them in fune.lock, downloads only the TypeScript package of each, and builds the code above into your project’s .fune/build, one readable file per capability with a header linking back here. Or pin a range in fune.project and build in one step:
fune add auth.rbac
That builds the whole group. To build only what you call, and whatever it uses inside the group:
fune add auth.rbac --only resolveRoles
The manifest, vectors and README with only the TypeScript implementation. Install it without the registry with fune add ./auth.rbac-1.0.0-typescript.fune, or fetch it from a terminal with fune pull auth.rbac@1.0.0:typescript.
The whole function, every language, is one file too: auth.rbac-1.0.0.fune, 94,322 bytes, sha256 ec822707e7da7f998666aa6a45145feac4393a54e730d8a12bb52c67ce974e1b. It installs into a project of any language.
Customise it in your app
The seams this capability offers. Put a marker directly above a function of your own and fune build wires it into the built code; the package on the registry is not changed, the built file’s header lists it under CUSTOMISED, and fune hooks lists every hook in the project. How hooks work.
before — your function gets the arguments and returns them, changed or not, or throws to refuse the call.
// fune: before auth.rbac.resolveRoles
// fune: before auth.rbac.hasPermission
// fune: before auth.rbac.checkAccess
// fune: before auth.rbac.accessMatrix
after — your function gets the result and the arguments, and returns the final result.
// fune: after auth.rbac.resolveRoles
// fune: after auth.rbac.hasPermission
// fune: after auth.rbac.checkAccess
// fune: after auth.rbac.accessMatrix
replace — it requires no other capability, so there is no dependency to replace.
step — your function runs at a numbered point inside a function’s body, receives the in-scope values it names as parameters, and may return replacements. List the points with fune show auth.rbac --steps.
// fune: step auth.rbac.<fn> after <n|label>
Tests
A version published now needs at least 8 tests for every function, and one that expects the error for each function that throws; the registry refuses it otherwise. fune verify --all runs each case in TypeScript, Python and Rust, and a project runs them again with fune verify. This page lists the cases; it does not run them. The exact JSON is vectors.json.
resolveRoles 16 tests
| Case | Arguments | Expected | |
|---|---|---|---|
| an editor inherits author and viewer, and every grant of the three, sorted | roles ×4, permissions posts:read, posts:update, posts:delete, comments:delete, editor | → | roles author, editor, viewer, permissions comments:*:own, comments:read, posts:create, posts:delete:own, posts:publish, posts:read, posts:update, posts:update:own |
| no roles, nothing granted | roles ×4, permissions posts:read, posts:update, posts:delete, comments:delete, | → | roles , permissions |
| a role given twice counts once | roles ×4, permissions posts:read, posts:update, posts:delete, comments:delete, viewer, viewer | → | roles viewer, permissions comments:read, posts:read |
| the * grant sorts first | roles ×4, permissions posts:read, posts:update, posts:delete, comments:delete, viewer, admin | → | roles admin, viewer, permissions *, comments:read, posts:read |
| a diamond inherits the shared role once | roles ×4, permissions , a | → | roles a, b, c, d, permissions x:read, x:write |
| a three-role cycle is reported with its path | roles ×3, permissions , | → | error: role inheritance cycle: a -> b -> c -> a |
| a cycle the given roles never reach is still refused | roles ×3, permissions , x | → | error: role inheritance cycle: p -> q -> p |
| the cycle is reported from the first role in policy order | roles ×2, permissions , | → | error: role inheritance cycle: b -> a -> b |
| a role inheriting itself | roles ×1, permissions , | → | error: role inheritance cycle: r -> r |
| an unknown role given | roles ×4, permissions posts:read, posts:update, posts:delete, comments:delete, owner | → | error: unknown role owner |
Show the other 6 tests
| Case | Arguments | Expected | |
|---|---|---|---|
| an unknown role inherited | roles ×1, permissions , | → | error: unknown role ghost |
| two roles with one name | roles ×2, permissions , | → | error: duplicate role a |
| a third segment other than own | roles ×1, permissions , | → | error: invalid grant posts:read:mine |
| upper case in a grant | roles ×1, permissions , | → | error: invalid grant Posts:read |
| a trailing newline in a grant | roles ×1, permissions , | → | error: invalid grant posts:read |
| a wildcard in the policy's concrete permissions | roles ×1, permissions posts:*, | → | error: invalid permission posts:* |
hasPermission 15 tests
| Case | Arguments | Expected | |
|---|---|---|---|
| a viewer may read posts | roles ×4, permissions posts:read, posts:update, posts:delete, comments:delete, viewer, posts:read | → | true |
| a viewer may not update posts | roles ×4, permissions posts:read, posts:update, posts:delete, comments:delete, viewer, posts:update | → | false |
| an author may not update every post: their grant is :own | roles ×4, permissions posts:read, posts:update, posts:delete, comments:delete, author, posts:update | → | false |
| an author may update their own posts | roles ×4, permissions posts:read, posts:update, posts:delete, comments:delete, author, posts:update:own | → | true |
| an editor may update every post | roles ×4, permissions posts:read, posts:update, posts:delete, comments:delete, editor, posts:update | → | true |
| an unrestricted grant covers the user's own too | roles ×4, permissions posts:read, posts:update, posts:delete, comments:delete, viewer, posts:read:own | → | true |
| * grants a permission nobody listed | roles ×4, permissions posts:read, posts:update, posts:delete, comments:delete, admin, billing:refund | → | true |
| an action wildcard with :own | roles ×4, permissions posts:read, posts:update, posts:delete, comments:delete, author, comments:delete:own | → | true |
| an action wildcard with :own does not grant every comment | roles ×4, permissions posts:read, posts:update, posts:delete, comments:delete, author, comments:delete | → | false |
| a resource wildcard grants the action on any resource | roles ×1, permissions , auditor, invoices:read | → | true |
Show the other 5 tests
| Case | Arguments | Expected | |
|---|---|---|---|
| a resource wildcard grants no other action | roles ×1, permissions , auditor, invoices:void | → | false |
| no roles, no permission | roles ×4, permissions posts:read, posts:update, posts:delete, comments:delete, , posts:read | → | false |
| a wildcard is not a permission to ask about | roles ×4, permissions posts:read, posts:update, posts:delete, comments:delete, viewer, posts:* | → | error: invalid permission posts:* |
| one segment is not a permission | roles ×4, permissions posts:read, posts:update, posts:delete, comments:delete, viewer, posts | → | error: invalid permission posts |
| an unknown role | roles ×4, permissions posts:read, posts:update, posts:delete, comments:delete, nobody, posts:read | → | error: unknown role nobody |
checkAccess 13 tests
| Case | Arguments | Expected | |
|---|---|---|---|
| an editor updates someone else's post | roles ×4, permissions posts:read, posts:update, posts:delete, comments:delete, id u1, roles editor, update, resource type posts, id p1, owner id u2 | → | allowed true, reason granted, grant posts:update |
| an author updates their own post | roles ×4, permissions posts:read, posts:update, posts:delete, comments:delete, id u1, roles author, update, resource type posts, id p1, owner id u1 | → | allowed true, reason granted_own, grant posts:update:own |
| an author may not update someone else's post | roles ×4, permissions posts:read, posts:update, posts:delete, comments:delete, id u1, roles author, update, resource type posts, id p1, owner id u2 | → | allowed false, reason not_owner, grant — |
| a post with no owner is nobody's own | roles ×4, permissions posts:read, posts:update, posts:delete, comments:delete, id u1, roles author, update, resource type posts, id p1, owner id — | → | allowed false, reason not_owner, grant — |
| a viewer may not delete posts at all | roles ×4, permissions posts:read, posts:update, posts:delete, comments:delete, id u1, roles viewer, delete, resource type posts, id p1, owner id u1 | → | allowed false, reason denied, grant — |
| an admin's * grant | roles ×4, permissions posts:read, posts:update, posts:delete, comments:delete, id u1, roles admin, delete, resource type posts, id p1, owner id — | → | allowed true, reason granted, grant * |
| an author deletes their own comment through comments:*:own | roles ×4, permissions posts:read, posts:update, posts:delete, comments:delete, id u1, roles author, delete, resource type comments, id p1, owner id u1 | → | allowed true, reason granted_own, grant comments:*:own |
| the first grant in sorted order is named | roles ×4, permissions posts:read, posts:update, posts:delete, comments:delete, id u1, roles editor, admin, update, resource type posts, id p1, owner id u2 | → | allowed true, reason granted, grant * |
| an editor reads posts through the inherited viewer grant | roles ×4, permissions posts:read, posts:update, posts:delete, comments:delete, id u1, roles editor, read, resource type posts, id p1, owner id — | → | allowed true, reason granted, grant posts:read |
| an empty subject id | roles ×4, permissions posts:read, posts:update, posts:delete, comments:delete, id , roles author, update, resource type posts, id p1, owner id | → | error: subject.id must be a non-empty string |
Show the other 3 tests
| Case | Arguments | Expected | |
|---|---|---|---|
| an action with a colon | roles ×4, permissions posts:read, posts:update, posts:delete, comments:delete, id u1, roles author, update:own, resource type posts, id p1, owner id u1 | → | error: invalid permission posts:update:own |
| an upper-case resource type | roles ×4, permissions posts:read, posts:update, posts:delete, comments:delete, id u1, roles author, update, resource type Posts, id p1, owner id u1 | → | error: invalid permission Posts:update |
| an unknown role | roles ×4, permissions posts:read, posts:update, posts:delete, comments:delete, id u1, roles owner, update, resource type posts, id p1, owner id u1 | → | error: unknown role owner |
accessMatrix 10 tests
| Case | Arguments | Expected | |
|---|---|---|---|
| viewer and author over reading and updating posts | roles ×2, permissions posts:read, posts:update | → | ×8 |
| an empty policy has no cases | roles , permissions | → | |
| roles without permissions have no cases | roles ×1, permissions | → | |
| permissions without roles have no cases | roles , permissions x:read | → | |
| an admin's * allows both | roles ×1, permissions invoices:void | → | ×2 |
| a role with no grants is denied both | roles ×1, permissions posts:read | → | ×2 |
| an :own wildcard allows only the owned case | roles ×1, permissions comments:delete | → | ×2 |
| roles come in policy order, not sorted | roles ×2, permissions x:a | → | ×4 |
| a cycle is refused before any case | roles ×2, permissions x:read | → | error: role inheritance cycle: a -> b -> a |
| an :own permission in the policy's list is refused | roles ×1, permissions posts:read:own | → | error: invalid permission posts:read:own |
Verification
Verified by the operator, not the sandbox 54 test vectors declared; none run by the registry.
Verified locally by the registry's operator, not by the sandbox. This version was published with FUNE_VERIFY_MODE=inline-dev (the operator's import of the first-party registry, or a development server): the server validated the package - its manifest, signatures, imports, safety lint and test rules - but the registry did not run its test vectors in its sandbox. The operator runs them with `fune verify --all` before importing.
Signed by the registry with key fw-9dc887227da47575 (ed25519), over its integrity and this report's digest. The full report · JSON
More from the author
## Grants and permissions
- A **permission** is `resource:action`, each segment lower-case ASCII letters, digits, `_` and `-` (`posts:update`, `api-keys:revoke`). - A **grant** (in a role's `permissions`) is `resource:action`, or `resource:action:own` for the subject's own resources only. Either segment may be `*` (any resource, any action), and `*` alone means `*:*`. There are no deny rules: a grant only ever adds. - Anything else (`posts:read:mine`, `Posts:read`, a trailing newline) throws `invalid grant ...` or `invalid permission ...`.
## The functions
- **resolveRoles(policy, roles)**: the roles plus everything they inherit, and all their grants, each deduplicated and sorted (by code point, so `*` sorts first). - **hasPermission(policy, roles, permission)**: `posts:update` asks "may they update every post?", which only an unrestricted grant answers yes; `posts:update:own` asks "may they update their own?", which an unrestricted or an `:own` grant answers yes. For a decision about one resource, use checkAccess. - **checkAccess(policy, subject, action, resource)**: an unrestricted grant gives `granted`; otherwise an `:own` grant gives `granted_own` when `resource.ownerId` equals `subject.id`, and `not_owner` when it does not (a resource with a null owner is nobody's own); otherwise `denied`. `grant` names the grant that allowed it, the first in sorted order; null when not allowed. - **accessMatrix(policy)**: the access tests the policy implies (below).
The resource field is `resourceType` rather than `type`, because `type` is a Rust keyword and the registry's lint refuses raw identifiers.
## The policy is checked whole, every call
Every function first checks the entire policy, not just the roles in hand, so a mistake anywhere fails the first request rather than one unlucky user's:
- `role name must be a non-empty string`, `duplicate role <name>`; - `unknown role <name>`: inherited by a role, or given in the call; - `invalid grant <grant>`, and `invalid permission <p>` for an entry of `policy.permissions` (concrete `resource:action` only: no `*`, no `:own`); - `role inheritance cycle: a -> b -> a`. Cycles are found by a depth-first walk over the roles in policy order, following `inherits` in listed order, so the same policy always reports the same cycle, starting from the first role in policy order that is on it (or leads to it).
Then `checkAccess` checks `subject.id must be a non-empty string`, the subject's roles, and that `resourceType:action` is a permission.
## Generated access tests
`accessMatrix` walks every role (policy order) by every permission in `policy.permissions` (listed order) by ownership (not owned, then owned), and says what checkAccess answers for a subject `{ id: "subject", roles: [role] }` on a resource `{ resourceType, id: "resource", ownerId: own ? "subject" : "someone-else" }`. Each case is named:
- `<role> may <action> any <resourceType>` / `<role> may not <action> any <resourceType>` (owned by someone else) - `<role> may <action> <resourceType> they own` / `<role> may not <action> <resourceType> they own`
such as `editor may update any posts` and `viewer may not delete posts they own`. Commit the generated table (or a snapshot of it) next to your policy: a change to a role then shows up in review as changed expectations, and your own tests prove the app's real authorisation path agrees with the policy.
import { accessMatrix } from "#fune/auth.rbac@^1";
for (const c of accessMatrix(policy)) {
test(c.name, async () => {
const user = await makeUser({ roles: [c.role] });
const owner = c.own ? user : await makeUser({ roles: [] });
const res = await api.as(user).request(c.action, c.resourceType, await makeResource(c.resourceType, owner));
expect(res.status === 403).toBe(!c.allowed);
});
}import pytest
from fune.auth.rbac import access_matrix
@pytest.mark.parametrize("case", access_matrix(POLICY), ids=lambda c: c.name)
def test_access(case, client, make_user, make_resource):
user = make_user(roles=[case.role])
owner = user if case.own else make_user(roles=[])
res = client.as_user(user).act(case.action, make_resource(case.resource_type, owner))
assert (res.status_code != 403) == case.allowed## What it does not do
No deny rules, no attribute conditions beyond ownership, no organisation or tenant scoping (put the tenant check before it), and no storage of who holds which role.