Functional Weave
Code in Rust

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.

  1. resolve_roles (policy: RbacPolicy, roles: string[]) -> ResolvedRoles
  2. has_permission (policy: RbacPolicy, roles: string[], permission: string) -> bool
  3. check_access (policy: RbacPolicy, subject: AccessSubject, action: string, resource: AccessResource) -> AccessDecision
  4. access_matrix (policy: RbacPolicy) -> AccessTestCase[]

The types it declares, generated into your project

/// One role: what it inherits and what it grants.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RoleDef {
    pub name: String,
    /// roles whose grants this one also has
    pub inherits: Vec<String>,
    /// grants: resource:action, resource:action:own, with * for any resource or action; * alone grants everything
    pub permissions: Vec<String>,
}

/// The app's whole role model.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RbacPolicy {
    pub roles: Vec<RoleDef>,
    /// every concrete resource:action the app checks, for accessMatrix
    pub permissions: Vec<String>,
}

/// A user's effective roles and grants.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ResolvedRoles {
    pub roles: Vec<String>,
    pub permissions: Vec<String>,
}

/// Who is asking.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AccessSubject {
    pub id: String,
    pub roles: Vec<String>,
}

/// What is being acted on.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AccessResource {
    /// the resource type, as it appears in grants (posts)
    pub resource_type: String,
    pub id: String,
    /// the id of the subject who owns it; null when nobody does
    pub owner_id: Option<String>,
}

// AccessReason is a string in Rust, one of: "granted", "granted_own", "not_owner", "denied".
// Parameters take it as &str and results hold it as String.

/// Whether the action is allowed, and why.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AccessDecision {
    pub allowed: bool,
    pub reason: String,
    /// the grant that allowed it, first in sorted order; null when not allowed
    pub grant: Option<String>,
}

/// One expected outcome, generated from the policy, for an app's own test suite.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AccessTestCase {
    /// such as "editor may update posts they own"
    pub name: String,
    pub role: String,
    pub resource_type: String,
    pub action: String,
    /// true: the subject owns the resource; false: someone else does
    pub own: bool,
    pub allowed: bool,
}

Once installed, your code imports each one from the group's module.

resolve_roles throws on bad input 16 tests

pub fn resolve_roles(policy: &RbacPolicy, roles: &[String]) -> ResolvedRoles
policyRbacPolicythe app's roles and permissions; checked whole every call (names, grants, inheritance cycles)
rolesstring[]the roles a user holds
returnsResolvedRolesthose 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, sorted
  • resolve_roles(roles ×4, permissions posts:read, posts:update, posts:delete, comments:delete, ) → roles , permissions no roles, nothing granted
  • resolve_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
fune!(auth.rbac@^1);  // then call resolve_roles(…)
impl/rust/resolve_roles.rs · 201 lines · open · raw

Imports name this capability’s declared dependencies, which fune builds next to it in your project; each one links to its page.

use super::funejson::Value;  ← the fune runtime: the JSON value the test vectors use; fune build keeps it only where a signature takes one

// One permission segment: lower-case ASCII letters, digits, _ and -.
fn segment(text: &str) -> bool {
    !text.is_empty() && text.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'_' || b == b'-')
}

/// A grant as (resource, action, own); "*" alone is "*:*".
///
/// # Panics
/// Panics on a grant that is not resource:action or resource:action:own.
pub fn parse_grant(grant: &str) -> (String, String, bool) {
    if grant == "*" {
        return ("*".to_string(), "*".to_string(), false);
    }
    let parts: Vec<&str> = grant.split(':').collect();
    let ok = |s: &str| s == "*" || segment(s);
    if (parts.len() == 2 || (parts.len() == 3 && parts[2] == "own")) && ok(parts[0]) && ok(parts[1]) {
        return (parts[0].to_string(), parts[1].to_string(), parts.len() == 3);
    }
    panic!("invalid grant {}", grant);
}

/// A concrete permission as (resource, action, own): no wildcards, :own only where asked.
///
/// # Panics
/// Panics on anything else.
pub fn parse_permission(permission: &str, allow_own: bool) -> (String, String, bool) {
    let parts: Vec<&str> = permission.split(':').collect();
    let shape = parts.len() == 2 || (allow_own && parts.len() == 3 && parts[2] == "own");
    if shape && segment(parts[0]) && segment(parts[1]) {
        return (parts[0].to_string(), parts[1].to_string(), parts.len() == 3);
    }
    panic!("invalid permission {}", permission);
}

fn find<'a>(policy: &'a RbacPolicy, name: &str) -> Option<&'a RoleDef> {
    policy.roles.iter().find(|r| r.name == name)
}

fn visit(policy: &RbacPolicy, name: &str, state: &mut Vec<(String, u8)>, stack: &mut Vec<String>) {
    state.push((name.to_string(), 1));
    stack.push(name.to_string());
    for parent in &find(policy, name).unwrap().inherits {
        match state.iter().find(|(n, _)| n == parent).map(|(_, s)| *s) {
            Some(1) => {
                let from = stack.iter().position(|n| n == parent).unwrap();
                let mut path: Vec<String> = stack[from..].to_vec();
                path.push(parent.clone());
                panic!("role inheritance cycle: {}", path.join(" -> "));
            }
            Some(_) => {}
            None => visit(policy, parent, state, stack),
        }
    }
    stack.pop();
    for entry in state.iter_mut() {
        if entry.0 == name {
            entry.1 = 2;
        }
    }
}

/// The policy checked whole: unique non-empty names, inherited roles that
/// exist, well-formed grants, no inheritance cycle (found depth-first over
/// the roles in policy order, so the cycle reported is always the same one),
/// and concrete permissions.
///
/// # Panics
/// Panics on the first problem found.
pub fn check_policy(policy: &RbacPolicy) {
    let mut names: Vec<&str> = Vec::new();
    for role in &policy.roles {
        if role.name.is_empty() {
            panic!("role name must be a non-empty string");
        }
        if names.contains(&role.name.as_str()) {
            panic!("duplicate role {}", role.name);
        }
        names.push(&role.name);
    }
    for role in &policy.roles {
        for parent in &role.inherits {
            if !names.contains(&parent.as_str()) {
                panic!("unknown role {}", parent);
            }
        }
        for grant in &role.permissions {
            parse_grant(grant);
        }
    }
    let mut state: Vec<(String, u8)> = Vec::new();
    let mut stack: Vec<String> = Vec::new();
    for role in &policy.roles {
        if !state.iter().any(|(n, _)| *n == role.name) {
            visit(policy, &role.name, &mut state, &mut stack);
        }
    }
    for permission in &policy.permissions {
        parse_permission(permission, false);
    }
}

/// The roles given plus every role they inherit, deduplicated and sorted.
///
/// # Panics
/// Panics on a role the policy does not define.
pub fn expand_roles(policy: &RbacPolicy, roles: &[String]) -> Vec<String> {
    let mut seen: Vec<String> = Vec::new();
    let mut queue: Vec<String> = roles.to_vec();
    let mut i = 0;
    while i < queue.len() {
        let name = queue[i].clone();
        i += 1;
        if seen.contains(&name) {
            continue;
        }
        let role = match find(policy, &name) {
            Some(role) => role,
            None => panic!("unknown role {}", name),
        };
        seen.push(name);
        queue.extend(role.inherits.iter().cloned());
    }
    seen.sort();
    seen
}

/// Every grant of these (already expanded) roles, deduplicated and sorted.
pub fn grants_of(policy: &RbacPolicy, roles: &[String]) -> Vec<String> {
    let mut grants: Vec<String> = Vec::new();
    for name in roles {
        for grant in &find(policy, name).unwrap().permissions {
            if !grants.contains(grant) {
                grants.push(grant.clone());
            }
        }
    }
    grants.sort();
    grants
}

/// What a user holding these roles effectively is and may do.
///
/// # Panics
/// Panics on a malformed policy or an unknown role.
pub fn resolve_roles(policy: &RbacPolicy, roles: &[String]) -> ResolvedRoles {
    check_policy(policy);
    let all = expand_roles(policy, roles);
    let permissions = grants_of(policy, &all);
    ResolvedRoles { roles: all, permissions }
}

pub fn rbac_strings_from_value(value: &Value, what: &str) -> Vec<String> {
    match value {
        Value::Arr(items) => items
            .iter()
            .map(|item| match item {
                Value::Str(s) => s.clone(),
                _ => panic!("{} must be a list of strings", what),
            })
            .collect(),
        _ => panic!("{} must be a list of strings", what),
    }
}

pub fn rbac_text_from_value(value: &Value, what: &str) -> String {
    match value {
        Value::Str(s) => s.clone(),
        _ => panic!("{} must be a string", what),
    }
}

pub fn rbac_policy_from_value(value: &Value) -> RbacPolicy {
    let roles = match value.get("roles") {
        Value::Arr(items) => items
            .iter()
            .map(|r| RoleDef {
                name: rbac_text_from_value(r.get("name"), "role name"),
                inherits: rbac_strings_from_value(r.get("inherits"), "inherits"),
                permissions: rbac_strings_from_value(r.get("permissions"), "permissions"),
            })
            .collect(),
        _ => panic!("policy must be an RbacPolicy"),
    };
    RbacPolicy { roles, permissions: rbac_strings_from_value(value.get("permissions"), "policy permissions") }
}

pub fn rbac_string_list_to_value(items: &[String]) -> Value {
    Value::Arr(items.iter().map(|s| Value::str(s)).collect())
}

pub fn fune_vector(args: &[Value]) -> Value {
    let policy = rbac_policy_from_value(&args[0]);
    let roles = rbac_strings_from_value(&args[1], "roles");
    let resolved = resolve_roles(&policy, &roles);
    Value::obj(vec![
        ("roles", rbac_string_list_to_value(&resolved.roles)),
        ("permissions", rbac_string_list_to_value(&resolved.permissions)),
    ])
}

has_permission throws on bad input 15 tests

pub fn has_permission(policy: &RbacPolicy, roles: &[String], permission: &str) -> bool
policyRbacPolicy
rolesstring[]the roles a user holds
permissionstringresource:action (may they do it to anything?) or resource:action:own (may they do it to their own?)
returnsbool

For example

  • has_permission(roles ×4, permissions posts:read, posts:update, posts:delete, comments:delete, viewer, posts:read) → true a viewer may read posts
  • has_permission(roles ×4, permissions posts:read, posts:update, posts:delete, comments:delete, viewer, posts:update) → false a viewer may not update posts
  • has_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
fune!(auth.rbac@^1);  // then call has_permission(…)
impl/rust/has_permission.rs · 29 lines · open · raw

Imports name this capability’s declared dependencies, which fune builds next to it in your project; each one links to its page.

use super::auth_rbac_resolve_roles::{
    check_policy, expand_roles, grants_of, parse_grant, parse_permission, rbac_policy_from_value,
    rbac_strings_from_value, rbac_text_from_value,
};
use super::funejson::Value;  ← the fune runtime: the JSON value the test vectors use; fune build keeps it only where a signature takes one

/// 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.
///
/// # Panics
/// Panics on a malformed policy, an unknown role or a malformed permission.
pub fn has_permission(policy: &RbacPolicy, roles: &[String], permission: &str) -> bool {
    check_policy(policy);
    let grants = grants_of(policy, &expand_roles(policy, roles));
    let (resource, action, own) = parse_permission(permission, true);
    grants.iter().any(|grant| {
        let (r, a, own_only) = parse_grant(grant);
        (r == "*" || r == resource) && (a == "*" || a == action) && (!own_only || own)
    })
}

pub fn fune_vector(args: &[Value]) -> Value {
    let policy = rbac_policy_from_value(&args[0]);
    let roles = rbac_strings_from_value(&args[1], "roles");
    let permission = rbac_text_from_value(&args[2], "permission");
    Value::Bool(has_permission(&policy, &roles, &permission))
}

check_access throws on bad input 13 tests

pub fn check_access(policy: &RbacPolicy, subject: &AccessSubject, action: &str, resource: &AccessResource) -> AccessDecision
policyRbacPolicy
subjectAccessSubjectwho is asking: their id and roles
actionstringwhat they want to do, such as update
resourceAccessResourcewhat they want to do it to: its resourceType (posts), id and owner
returnsAccessDecisionallowed 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 post
  • check_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 post
  • check_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
fune!(auth.rbac@^1);  // then call check_access(…)
impl/rust/check_access.rs · 70 lines · open · raw

Imports name this capability’s declared dependencies, which fune builds next to it in your project; each one links to its page.

use super::auth_rbac_resolve_roles::{
    check_policy, expand_roles, grants_of, parse_grant, parse_permission, rbac_policy_from_value,
    rbac_strings_from_value, rbac_text_from_value,
};
use super::funejson::Value;  ← the fune runtime: the JSON value the test vectors use; fune build keeps it only where a signature takes one

fn decision(allowed: bool, reason: &str, grant: Option<String>) -> AccessDecision {
    AccessDecision { allowed, reason: reason.to_string(), grant }
}

/// 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.
///
/// # Panics
/// Panics on a malformed policy, an empty subject id, an unknown role or a
/// malformed resource type or action.
pub fn check_access(policy: &RbacPolicy, subject: &AccessSubject, action: &str, resource: &AccessResource) -> AccessDecision {
    check_policy(policy);
    if subject.id.is_empty() {
        panic!("subject.id must be a non-empty string");
    }
    let grants = grants_of(policy, &expand_roles(policy, &subject.roles));
    let (rtype, act, _) = parse_permission(&format!("{}:{}", resource.resource_type, action), false);
    let mut own_grant: Option<String> = None;
    for grant in &grants {
        let (r, a, own_only) = parse_grant(grant);
        if (r == "*" || r == rtype) && (a == "*" || a == act) {
            if !own_only {
                return decision(true, "granted", Some(grant.clone()));
            }
            if own_grant.is_none() {
                own_grant = Some(grant.clone());
            }
        }
    }
    if own_grant.is_some() {
        if resource.owner_id.as_deref() == Some(subject.id.as_str()) {
            return decision(true, "granted_own", own_grant);
        }
        return decision(false, "not_owner", None);
    }
    decision(false, "denied", None)
}

pub fn fune_vector(args: &[Value]) -> Value {
    let policy = rbac_policy_from_value(&args[0]);
    let subject = AccessSubject {
        id: rbac_text_from_value(args[1].get("id"), "subject.id"),
        roles: rbac_strings_from_value(args[1].get("roles"), "subject.roles"),
    };
    let action = rbac_text_from_value(&args[2], "action");
    let resource = AccessResource {
        resource_type: rbac_text_from_value(args[3].get("resourceType"), "resource.resourceType"),
        id: rbac_text_from_value(args[3].get("id"), "resource.id"),
        owner_id: match args[3].get("ownerId") {
            Value::Null => None,
            other => Some(rbac_text_from_value(other, "resource.ownerId")),
        },
    };
    let d = check_access(&policy, &subject, &action, &resource);
    Value::obj(vec![
        ("allowed", Value::Bool(d.allowed)),
        ("reason", Value::str(&d.reason)),
        ("grant", match &d.grant {
            Some(g) => Value::str(g),
            None => Value::Null,
        }),
    ])
}

access_matrix throws on bad input 10 tests

pub fn access_matrix(policy: &RbacPolicy) -> Vec<AccessTestCase>
policyRbacPolicy
returnsAccessTestCase[]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 posts
  • access_matrix(roles , permissions ) → an empty policy has no cases
  • access_matrix(roles ×1, permissions ) → roles without permissions have no cases
fune!(auth.rbac@^1);  // then call access_matrix(…)
impl/rust/access_matrix.rs · 62 lines · open · raw

Imports name this capability’s declared dependencies, which fune builds next to it in your project; each one links to its page.

use super::auth_rbac_check_access::check_access;  ← checkAccess, another function of this group · built into the same file, even by a slim install
use super::auth_rbac_resolve_roles::{check_policy, parse_permission, rbac_policy_from_value};  ← resolveRoles, another function of this group · built into the same file, even by a slim install
use super::funejson::Value;  ← the fune runtime: the JSON value the test vectors use; fune build keeps it only where a signature takes one

/// 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.
///
/// # Panics
/// Panics on a malformed policy.
pub fn access_matrix(policy: &RbacPolicy) -> Vec<AccessTestCase> {
    check_policy(policy);
    let mut cases = Vec::new();
    for role in &policy.roles {
        for permission in &policy.permissions {
            let (resource_type, action, _) = parse_permission(permission, false);
            for own in [false, true] {
                let subject = AccessSubject { id: "subject".to_string(), roles: vec![role.name.clone()] };
                let resource = AccessResource {
                    resource_type: resource_type.clone(),
                    id: "resource".to_string(),
                    owner_id: Some(if own { "subject" } else { "someone-else" }.to_string()),
                };
                let allowed = check_access(policy, &subject, &action, &resource).allowed;
                let verb = if allowed { "may" } else { "may not" };
                let name = if own {
                    format!("{} {} {} {} they own", role.name, verb, action, resource_type)
                } else {
                    format!("{} {} {} any {}", role.name, verb, action, resource_type)
                };
                cases.push(AccessTestCase {
                    name,
                    role: role.name.clone(),
                    resource_type: resource_type.clone(),
                    action: action.clone(),
                    own,
                    allowed,
                });
            }
        }
    }
    cases
}

pub fn fune_vector(args: &[Value]) -> Value {
    let policy = rbac_policy_from_value(&args[0]);
    Value::Arr(
        access_matrix(&policy)
            .iter()
            .map(|c| {
                Value::obj(vec![
                    ("name", Value::str(&c.name)),
                    ("role", Value::str(&c.role)),
                    ("resourceType", Value::str(&c.resource_type)),
                    ("action", Value::str(&c.action)),
                    ("own", Value::Bool(c.own)),
                    ("allowed", Value::Bool(c.allowed)),
                ])
            })
            .collect(),
    )
}

Install

fune build

With that line in your source, in a Rust project (language rust in fune.project), fune build resolves it and nothing else, pins them in fune.lock, downloads only the Rust 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. A crate’s build.rs runs it before every compile. 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
Download for Rust auth.rbac-1.0.0-rust.fune · 77,355 bytes sha256 97268652002569123528ad5772faae3e8c6260fef961973fe1a432e09becb47e

The manifest, vectors and README with only the Rust implementation. Install it without the registry with fune add ./auth.rbac-1.0.0-rust.fune, or fetch it from a terminal with fune pull auth.rbac@1.0.0:rust.

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

CaseArgumentsExpected
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
CaseArgumentsExpected
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

CaseArgumentsExpected
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
CaseArgumentsExpected
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

CaseArgumentsExpected
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
CaseArgumentsExpected
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

CaseArgumentsExpected
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.

Files

PathBytes
README.md5,508
impl/python/access_matrix.py1,586
impl/python/check_access.py1,551
impl/python/has_permission.py866
impl/python/resolve_roles.py3,942
impl/rust/access_matrix.rs2,518
impl/rust/check_access.rs2,826
impl/rust/has_permission.rs1,266
impl/rust/resolve_roles.rs7,010
impl/typescript/access_matrix.ts1,348
impl/typescript/check_access.ts1,492
impl/typescript/has_permission.ts867
impl/typescript/resolve_roles.ts4,416
vectors.json42,103