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; fn decision(allowed: bool, reason: &str, grant: Option) -> 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 = 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, }), ]) }