Functional Weave
Code in Rust

auth.rbac@1.0.0

impl/rust/resolve_roles.rs

7,010 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::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)),
    ])
}