Functional Weave
Code in Rust

auth.rbac@1.0.0

impl/rust/has_permission.rs

1,266 bytes · the Rust implementation · view 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))
}