Skip to main content

A simple, hierarchical Role-Based Access Control (RBAC) package for Python.

Project description

Simple Python RBAC

A lightweight, hierarchical Role-Based Access Control (RBAC) package for Python. It is designed to be framework-agnostic, with no third-party dependencies.

Features

  • Hierarchical Permissions: Supports wildcards (e.g., app.* matches app.home, app.settings).
  • Permission Sets: Group permissions into named sets (like AWS Permission Sets) for easier role management.
  • Global Fail Handler: Define a default behavior for when permissions are denied.
  • YAML Configuration: Load roles and permission sets directly from YAML files.
  • Framework Agnostic: Easy integration with Streamlit, Flask, FastAPI, etc.
  • Generic Decorators: Protect functions with simple decorators.
  • Object-Level Restrictions: Hooks to implement data-level security.
  • Zero Dependencies: Pure Python, no external requirements (YAML support requires pyyaml).

Installation

You can install the package directly from PyPI:

pip install simple-python-rbac

Core Concepts

1. Defining Permissions

Use the Permissions class to organize your permissions hierarchically.

from simple_python_rbac import Permissions

class AppPermissions(Permissions):
    class Documents:
        _prefix = "docs"
        VIEW = f"{_prefix}.view"
        EDIT = f"{_prefix}.edit"
        DELETE = f"{_prefix}.delete"
    
    class Admin:
        ALL = "admin.*"

2. Permission Sets

Group permissions into sets that can be assigned to roles.

from simple_python_rbac import RBACManager

rbac = RBACManager()

permission_sets = {
    "viewer_set": ["docs.view", "profile.view"],
    "editor_set": ["docs.*", "profile.edit"]
}

rbac.set_permission_sets(permission_sets)

3. Configuring Roles

Roles can have direct permissions and/or inherit from permission sets.

roles = [
    {
        "role_name": "viewer",
        "permission_sets": ["viewer_set"]
    },
    {
        "role_name": "editor",
        "permissions": ["audit.log"],
        "permission_sets": ["viewer_set", "editor_set"]
    },
    {
        "role_name": "admin",
        "permissions": ["*"]
    }
]

rbac.set_roles(roles)

4. Global On-Fail Handler

You can define a global handler for permission denials that will be used if no specific handler is provided in the decorator.

def my_default_fail(permission):
    print(f"User lacks {permission}")
    return False

rbac.default_on_fail = my_default_fail

@rbac.require("admin.all")
def secret_admin_task():
    return "Top Secret"

5. YAML Configuration

Load roles and permission sets from YAML files for better organization.

# Load all YAMLs from a folder
rbac.load_roles_from_yaml("config/roles/*.yaml")

# Load permission sets from a specific file
rbac.load_permission_sets_from_yaml("config/permission_sets.yaml")

6. Custom Exceptions

The package provides a custom PermissionError (exported from the main package) that is raised when access is denied and no fail handler is provided.

from simple_python_rbac import PermissionError

try:
    @rbac.require("missing.perm")
    def my_func():
        pass
    my_func()
except PermissionError as e:
    print(f"Caught expected error: {e}")

Overloading Object Restrictions

One of the powerful features of simple-python-rbac is the ability to define restrictions on objects based on roles. To do this, you can inherit from RBACManager and override the get_object_restrictions method.

from simple_python_rbac import RBACManager

class MyRBACManager(RBACManager):
    def get_object_restrictions(self, role_name: str, object_type: str):
        """
        Returns a filter or a set of rules for the given object type.
        """
        if object_type == "document":
            if role_name == "viewer":
                return {"status": "published"}
            if role_name == "editor":
                return {"owner_id": 123} # example: only their own docs
        return None

rbac = MyRBACManager()

Test Coverage

The package is thoroughly tested. Current coverage:

Module Coverage
simple_python_rbac/core.py 97%
simple_python_rbac/exceptions.py 100%
simple_python_rbac/permissions.py 100%
Total 97%

Running Tests

python -m unittest discover tests

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

simple_python_rbac-0.3.0.tar.gz (10.0 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

simple_python_rbac-0.3.0-py3-none-any.whl (8.1 kB view details)

Uploaded Python 3

File details

Details for the file simple_python_rbac-0.3.0.tar.gz.

File metadata

  • Download URL: simple_python_rbac-0.3.0.tar.gz
  • Upload date:
  • Size: 10.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.7

File hashes

Hashes for simple_python_rbac-0.3.0.tar.gz
Algorithm Hash digest
SHA256 92c1a7161339fbd61d236e7921befd9d07d0e29c685dacf5d2e1766c1aac730d
MD5 645f4b10d100a6af98822483f620c8b0
BLAKE2b-256 432e485953e11dc3d28dadba3e9799ea16eac63e5dfd3db9368a64b5854fb4a2

See more details on using hashes here.

File details

Details for the file simple_python_rbac-0.3.0-py3-none-any.whl.

File metadata

File hashes

Hashes for simple_python_rbac-0.3.0-py3-none-any.whl
Algorithm Hash digest
SHA256 182f538d5c2b8504ba5fad66526ba82d0a5a0a73616b13153e515d385c9acd00
MD5 65a12f8ee155ad7840a88c12faa5415c
BLAKE2b-256 5f0d3cf398f09ace22e47f82fa804761c5e738490def2d411d9937c6b9494f9b

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page