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.
- resolve_roles (policy: RbacPolicy, roles: string[]) -> ResolvedRoles
- has_permission (policy: RbacPolicy, roles: string[], permission: string) -> bool
- check_access (policy: RbacPolicy, subject: AccessSubject, action: string, resource: AccessResource) -> AccessDecision
- access_matrix (policy: RbacPolicy) -> AccessTestCase[]
The types it declares, generated into your project
@dataclass(frozen=True)
class RoleDef:
"""One role: what it inherits and what it grants."""
name: str
#: roles whose grants this one also has
inherits: List[str]
#: grants: resource:action, resource:action:own, with * for any resource or action; * alone grants everything
permissions: List[str]
@dataclass(frozen=True)
class RbacPolicy:
"""The app's whole role model."""
roles: List[RoleDef]
#: every concrete resource:action the app checks, for accessMatrix
permissions: List[str]
@dataclass(frozen=True)
class ResolvedRoles:
"""A user's effective roles and grants."""
roles: List[str]
permissions: List[str]
@dataclass(frozen=True)
class AccessSubject:
"""Who is asking."""
id: str
roles: List[str]
@dataclass(frozen=True)
class AccessResource:
"""What is being acted on."""
#: the resource type, as it appears in grants (posts)
resource_type: str
id: str
#: the id of the subject who owns it; null when nobody does
owner_id: Optional[str]
AccessReason = Literal["granted", "granted_own", "not_owner", "denied"]
@dataclass(frozen=True)
class AccessDecision:
"""Whether the action is allowed, and why."""
allowed: bool
reason: AccessReason
#: the grant that allowed it, first in sorted order; null when not allowed
grant: Optional[str]
@dataclass(frozen=True)
class AccessTestCase:
"""One expected outcome, generated from the policy, for an app's own test suite."""
#: such as "editor may update posts they own"
name: str
role: str
resource_type: str
action: str
#: true: the subject owns the resource; false: someone else does
own: bool
allowed: bool
Once installed, your code imports each one from the group's module.
resolve_roles throws on bad input 16 tests
def resolve_roles(policy: RbacPolicy, roles: Sequence[str]) -> 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
resolve_roles(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, sortedresolve_roles(roles ×4, permissions posts:read, posts:update, posts:delete, comments:delete, )→ roles , permissions no roles, nothing grantedresolve_roles(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
from fune.auth.rbac import resolve_roles # auth.rbac@^1
from typing import Dict, List, Sequence, Tuple
from .auth_rbac_types import RbacPolicy, ResolvedRoles, RoleDef
def _segment(text: str) -> bool:
# Compared by character range: lower-case ASCII letters, digits, _ and -.
return len(text) > 0 and all("a" <= ch <= "z" or "0" <= ch <= "9" or ch in "_-" for ch in text)
def parse_grant(grant: str) -> Tuple[str, str, bool]:
"""A grant as (resource, action, own); "*" alone is "*:*"."""
if not isinstance(grant, str):
raise ValueError("invalid grant %s" % (grant,))
if grant == "*":
return ("*", "*", False)
parts = grant.split(":")
ok = lambda s: s == "*" or _segment(s) # noqa: E731
if (len(parts) == 2 or (len(parts) == 3 and parts[2] == "own")) and ok(parts[0]) and ok(parts[1]):
return (parts[0], parts[1], len(parts) == 3)
raise ValueError("invalid grant %s" % grant)
def parse_permission(permission: str, allow_own: bool) -> Tuple[str, str, bool]:
"""A concrete permission as (resource, action, own): no wildcards, :own only where asked."""
if isinstance(permission, str):
parts = permission.split(":")
shape = len(parts) == 2 or (allow_own and len(parts) == 3 and parts[2] == "own")
if shape and _segment(parts[0]) and _segment(parts[1]):
return (parts[0], parts[1], len(parts) == 3)
raise ValueError("invalid permission %s" % (permission,))
def check_policy(policy: RbacPolicy) -> Dict[str, RoleDef]:
"""The policy checked whole (names, inherited roles, grants, cycles found
depth-first in policy order, permissions); the roles by name."""
by_name: Dict[str, RoleDef] = {}
for role in policy.roles:
if not isinstance(role.name, str) or role.name == "":
raise ValueError("role name must be a non-empty string")
if role.name in by_name:
raise ValueError("duplicate role %s" % role.name)
by_name[role.name] = role
for role in policy.roles:
for parent in role.inherits:
if parent not in by_name:
raise ValueError("unknown role %s" % parent)
for grant in role.permissions:
parse_grant(grant)
state: Dict[str, int] = {}
stack: List[str] = []
def visit(name: str) -> None:
state[name] = 1
stack.append(name)
for parent in by_name[name].inherits:
seen = state.get(parent)
if seen == 1:
path = stack[stack.index(parent):] + [parent]
raise ValueError("role inheritance cycle: %s" % " -> ".join(path))
if seen is None:
visit(parent)
stack.pop()
state[name] = 2
for role in policy.roles:
if role.name not in state:
visit(role.name)
for permission in policy.permissions:
parse_permission(permission, False)
return by_name
def expand_roles(by_name: Dict[str, RoleDef], roles: Sequence[str]) -> List[str]:
"""The roles given plus every role they inherit, deduplicated and sorted."""
seen = set()
queue = list(roles)
while queue:
name = queue.pop(0)
if name in seen:
continue
if name not in by_name:
raise ValueError("unknown role %s" % (name,))
seen.add(name)
queue.extend(by_name[name].inherits)
return sorted(seen)
def grants_of(by_name: Dict[str, RoleDef], roles: Sequence[str]) -> List[str]:
"""Every grant of these (already expanded) roles, deduplicated and sorted."""
grants = set()
for name in roles:
grants.update(by_name[name].permissions)
return sorted(grants)
def resolve_roles(policy: RbacPolicy, roles: Sequence[str]) -> ResolvedRoles:
"""What a user holding these roles effectively is and may do."""
by_name = check_policy(policy)
every = expand_roles(by_name, roles)
return ResolvedRoles(roles=every, permissions=grants_of(by_name, every))has_permission throws on bad input 15 tests
def has_permission(policy: RbacPolicy, roles: Sequence[str], permission: str) -> bool
| 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
has_permission(roles ×4, permissions posts:read, posts:update, posts:delete, comments:delete, viewer, posts:read)→ true a viewer may read postshas_permission(roles ×4, permissions posts:read, posts:update, posts:delete, comments:delete, viewer, posts:update)→ false a viewer may not update postshas_permission(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
from fune.auth.rbac import has_permission # 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.
from typing import Sequence
from .auth_rbac_resolve_roles import check_policy, expand_roles, grants_of, parse_grant, parse_permission ← resolveRoles, another function of this group · built into the same file, even by a slim install
from .auth_rbac_types import RbacPolicy
def has_permission(policy: RbacPolicy, roles: Sequence[str], permission: str) -> bool:
"""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."""
by_name = check_policy(policy)
grants = grants_of(by_name, expand_roles(by_name, roles))
resource, action, own = parse_permission(permission, True)
for grant in grants:
r, a, own_only = parse_grant(grant)
if (r == "*" or r == resource) and (a == "*" or a == action) and (not own_only or own):
return True
return Falsecheck_access throws on bad input 13 tests
def check_access(policy: RbacPolicy, subject: AccessSubject, action: str, 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
check_access(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 postcheck_access(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 postcheck_access(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
from fune.auth.rbac import check_access # 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.
from typing import Optional
from .auth_rbac_resolve_roles import check_policy, expand_roles, grants_of, parse_grant, parse_permission ← resolveRoles, another function of this group · built into the same file, even by a slim install
from .auth_rbac_types import AccessDecision, AccessResource, AccessSubject, RbacPolicy
def check_access(policy: RbacPolicy, subject: AccessSubject, action: str, resource: AccessResource) -> AccessDecision:
"""May this subject do this action to this resource? An unrestricted grant
allows it; an :own grant only when the subject owns the resource. A
resource with no owner is nobody's own."""
by_name = check_policy(policy)
if not isinstance(subject.id, str) or subject.id == "":
raise ValueError("subject.id must be a non-empty string")
grants = grants_of(by_name, expand_roles(by_name, subject.roles))
rtype, act, _ = parse_permission("%s:%s" % (resource.resource_type, action), False)
own_grant: Optional[str] = None
for grant in grants:
r, a, own_only = parse_grant(grant)
if (r == "*" or r == rtype) and (a == "*" or a == act):
if not own_only:
return AccessDecision(allowed=True, reason="granted", grant=grant)
if own_grant is None:
own_grant = grant
if own_grant is not None:
if resource.owner_id is not None and resource.owner_id == subject.id:
return AccessDecision(allowed=True, reason="granted_own", grant=own_grant)
return AccessDecision(allowed=False, reason="not_owner", grant=None)
return AccessDecision(allowed=False, reason="denied", grant=None)access_matrix throws on bad input 10 tests
def access_matrix(policy: RbacPolicy) -> List[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
access_matrix(roles ×2, permissions posts:read, posts:update)→ ×8 viewer and author over reading and updating postsaccess_matrix(roles , permissions )→ an empty policy has no casesaccess_matrix(roles ×1, permissions )→ roles without permissions have no cases
from fune.auth.rbac import access_matrix # 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.
from typing import List
from .auth_rbac_check_access import check_access ← checkAccess, another function of this group · built into the same file, even by a slim install
from .auth_rbac_resolve_roles import check_policy, parse_permission ← resolveRoles, another function of this group · built into the same file, even by a slim install
from .auth_rbac_types import AccessResource, AccessSubject, AccessTestCase, RbacPolicy
def access_matrix(policy: RbacPolicy) -> List[AccessTestCase]:
"""The expected answer for every role, every permission the app declares,
and both ownerships, in policy order: a test table generated from the policy."""
check_policy(policy)
cases: List[AccessTestCase] = []
for role in policy.roles:
for permission in policy.permissions:
resource_type, action, _ = parse_permission(permission, False)
for own in (False, True):
decision = check_access(
policy,
AccessSubject(id="subject", roles=[role.name]),
action,
AccessResource(resource_type=resource_type, id="resource", owner_id="subject" if own else "someone-else"),
)
verb = "may" if decision.allowed else "may not"
if own:
name = "%s %s %s %s they own" % (role.name, verb, action, resource_type)
else:
name = "%s %s %s any %s" % (role.name, verb, action, resource_type)
cases.append(
AccessTestCase(
name=name, role=role.name, resource_type=resource_type, action=action, own=own,
allowed=decision.allowed,
)
)
return casesInstall
fune build
With that line in your source, in a Python project (language python in fune.project), fune build resolves it and nothing else, pins them in fune.lock, downloads only the Python 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 Python implementation. Install it without the registry with fune add ./auth.rbac-1.0.0-python.fune, or fetch it from a terminal with fune pull auth.rbac@1.0.0:python.
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.