Functional Weave
Code in Python

auth.rbac@1.0.0

impl/python/access_matrix.py

1,586 bytes · the Python 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.

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 cases