Casbin-CPP

repository·master·Indexed 42 days ago

https://github.com/apache/casbin-cpp

A C++ implementation of the Casbin authorization library for managing access control using the PERM metamodel. It supports various models including ACL, RBAC, and ABAC, and provides Python bindings via the pycasbin module. Features include a Management API, a specialized RBAC API, and integration options via CMake FetchContent or local installation.

Tokens
3.2K
Snippets
8
Records
11
Agent score
54%

What's inside Casbin-CPP

  1. How Casbin access control models work

    master

    Casbin abstracts access control into a configuration file (CONF) based on the PERM metamodel:

    1. Request definition (r): Defines the structure of the request (e.g., sub, obj, act for subject, object, action).
    2. Policy definition (p): Defines the structure of the stored policy rules.
    3. Policy effect (e): Defines how the results of the matchers are combined (e.g., some(where (p.eft == allow)) means if any policy allows, the result is allow).
    4. Matchers (m): Defines the logic used to match the request against the policies.

    By modifying the CONF file, you can switch between different authorization mechanisms like ACL, RBAC, or ABAC without changing your application code.

    # Request definition
    [request_definition]
    r = sub, obj, act
    
    # Policy definition
    [policy_definition]
    p = sub, obj, act
    
    # Policy effect
    [policy_effect]
    e = some(where (p.eft == allow))
    
    # Matchers
    [matchers]
    m = r.sub == p.sub && r.obj == p.obj && r.act == p.act
  2. Manage permissions with Casbin-CPP APIs

    master

    Casbin-CPP provides two primary ways to manage permissions programmatically:

    • Management API: A primitive API that provides full support for all Casbin policy management operations.
    • RBAC API: A higher-level, more user-friendly API specifically designed for Role-Based Access Control. It is a subset of the Management API and simplifies code for RBAC use cases.
  3. Supported Casbin access control models

    master

    Casbin supports a wide variety of access control models, including:

    • ACL (Access Control List): The simplest model.
    • ACL with superuser: Supports built-in roles like root that bypass explicit permissions.
    • RBAC (Role-Based Access Control): Users are assigned roles, and roles are assigned permissions.
    • RBAC with domains/tenants: Users have different roles within different domains.
    • ABAC (Attribute-Based Access Control): Uses attributes of the subject or object (e.g., resource.Owner) for matching.
    • RESTful: Supports path patterns (e.g., /res/*) and HTTP methods.
    • Deny-override: Supports both allow and deny rules, where deny takes precedence.
    • Priority: Allows policy rules to be prioritized like firewall rules.
  4. Build and Install Casbin-CPP from source

    master

    To build and install Casbin-CPP on Windows, Linux, or macOS:

    1. Clone the repository:
      git clone https://github.com/casbin/casbin-cpp.git
    2. Configure the build:
      cd casbin-cpp
      mkdir build
      cd build
      cmake ..
      Note: Use -DCMAKE_INSTALL_PREFIX=<path> to change the installation directory (defaults to /usr/local on Linux/macOS or C:/Program Files/casbin on Windows).
    3. Build:
      cmake --build .
    4. Install:
      cmake --build . --target install
    5. Run tests (Optional):
      ctest
    git clone https://github.com/casbin/casbin-cpp.git
    mkdir build && cd build
    cmake ..
    cmake --build . --target install
  5. Install the pycasbin module

    master

    To install the pycasbin Python bindings for casbin-cpp, you must have CMake >=v3.19 and Python >= 3.6 installed. Currently, pycasbin only supports local machine installation via pip from the source repository.

    Follow these steps:

    1. Clone the repository.
    2. Upgrade wheel and setuptools.
    3. Install the module using pip install . from the root directory.
    git clone https://github.com/casbin/casbin-cpp.git
    python -m pip install --upgrade wheel setuptools
    cd casbin-cpp && pip install --verbose .
  6. Get started with Casbin-CPP

    master

    To use Casbin-CPP in your C++ project, follow these steps:

    1. Setup Include Path: Add the project's include directory to your system's PATH environment variable so that #include <casbin/casbin.h> is resolvable.
    2. Initialize Enforcer: Create a casbin::Enforcer instance by providing paths to a model configuration file (.conf) and a policy file (.csv).
    3. Enforce Permissions: Use the Enforce method to check if a request (subject, object, action) is permitted based on your loaded model and policies.
    4. Runtime Management: Use the API to query permissions at runtime, such as retrieving implicit roles for a user.
    #include <casbin/casbin.h>
    #include <string>
    #include <vector>
    
    void IsAuthorized() {
        // 1. Initialize the enforcer with model and policy files
        casbin::Enforcer e("./path/to/model.conf", "./path/to/policy.csv");
    
        // 2. Define the request parameters
        std::string sub = "alice"; // the user
        std::string obj = "data1"; // the resource
        std::string act = "read"; // the operation
    
        // 3. Check permission
        if(e.Enforce({ sub, obj, act })) {
            // permit alice to read data1
        } else {
            // deny the request
        }
    
        // 4. Example of runtime permission management: get implicit roles
        std::vector<std::string> roles = e.GetImplicitRolesForUser(sub);
    }
  7. Use pycasbin for authorization enforcement

    master

    To perform authorization checks, import pycasbin and initialize a casbin.Enforcer with your model configuration and policy files. You can then call e.Enforce(req) to check if a request is authorized.

    Request Formats: The Enforce method accepts requests in two primary formats:

    • A list: ['subject', 'object', 'action']
    • A dictionary: {"sub": "subject", "obj": "object", "act": "action"}

    Enforcer Types:

    • casbin.Enforcer: The standard enforcer.
    • casbin.CachedEnforcer: An alternative for specific use cases requiring caching.
    import pycasbin as casbin
    
    # Initialize the enforcer with model and policy paths
    e = casbin.Enforcer('path/to/model.conf', 'path/to/policy.csv')
    
    # Check authorization using a list-based request
    result = e.Enforce(['subject1', 'object1', 'action1'])
    
    # Or using a dictionary-based request
    result = e.Enforce({"sub": "subject1", "obj": "object1", "act": "action1"})
    
    if result:
        print('Authorized')
    else:
        print('Not authorized!')
  8. Integrate Casbin-CPP using CMake FetchContent

    master

    If you do not want to install Casbin locally, you can integrate it directly into your project using CMake's FetchContent. This method automatically downloads and configures Casbin during your project's build process.

    Requirements:

    • CMake >= v3.19

    Note that you can disable optional components like tests, benchmarks, or language bindings using specific CMake variables to speed up your build.

    include(FetchContent)
    
    FetchContent_Declare(
            casbin
            GIT_REPOSITORY https://github.com/casbin/casbin-cpp.git
            GIT_TAG v1.38.1
    )
    
    set(CASBIN_BUILD_TEST OFF)            # If you don't need to build tests for casbin
    set(CASBIN_BUILD_BENCHMARK OFF)       # If you don't need to build benchmarks for casbin
    set(CASBIN_BUILD_BINDINGS OFF)        # If you don't need language bindings provided by casbin
    set(CASBIN_BUILD_PYTHON_BINDINGS OFF) # If you don't need python bindings for casbin
    
    # Making casbin and its targets accessible to our project
    FetchContent_MakeAvailable(casbin)
    
    FetchContent_GetProperties(casbin)
    
    # If casbin wasn't populated, then manually populate it
    if(NOT casbin_POPULATED)
        FetchContent_Populate(casbin)
        add_subdirectory(${casbin_SOURCE_DIR} ${casbin_BINARY_DIR})
    endif()
    
    # Link against casbin
    add_executable(myexec main.cpp)
    target_link_libraries(myexec PRIVATE casbin::casbin)
  9. Integrate Casbin-CPP via Local Installation

    master

    To use a locally installed version of Casbin, follow these steps:

    1. Build and Install Casbin:

      • Clone the repository.
      • Create a build directory and run cmake ...
      • Use -DCMAKE_INSTALL_PREFIX=<path> to specify a custom installation directory.
      • Build and install using cmake --build . --config Release --target install.
    2. Configure your project:

      • In your project's CMakeLists.txt, add find_package(casbin REQUIRED).
      • If you used a non-default prefix, point CMake to it using -DCMAKE_PREFIX_PATH=<path> during your project's configuration.
      • Link your target using target_link_libraries(YourTargetName PRIVATE casbin::casbin).

    Note: The casbin::casbin target automatically handles include directories.

    # In your project's CMakeLists.txt
    find_package(casbin REQUIRED)
    target_link_libraries(MyTargetName PRIVATE casbin::casbin)
  10. Use pycasbin for Casbin authorization in Python

    master

    The pycasbin module provides Python bindings for the Casbin authorization library. It exposes several core components to manage access control via models, policies, and enforcers.

    Key components available in the module include:

    • Enforcer: The primary interface for checking permissions.
    • CachedEnforcer: An enforcer with caching capabilities for improved performance.
    • SyncedEnforcer: An enforcer designed for thread-safe operations.
    • Model: Represents the RBAC/ABAC model configuration.
    • Config: Handles configuration settings.
    • Adapter: Interface for connecting to external policy storage (e.g., databases).
    import pycasbin
    
    # Access the version of the package
    print(pycasbin.__version__)
  11. Reference of Casbin Model and Policy Examples

    master

    The following table lists common access control models and their corresponding configuration and policy files available in the repository for reference:

    ModelModel filePolicy file
    ACLbasic_model.confbasic_policy.csv
    ACL with superuserbasic_model_with_root.confbasic_policy.csv
    ACL without usersbasic_model_without_users.confbasic_policy_without_users.csv
    ACL without resourcesbasic_model_without_resources.confbasic_policy_without_resources.csv
    RBACrbac_model.confrbac_policy.csv
    RBAC with resource rolesrbac_model_with_resource_roles.confrbac_policy_with_resource_roles.csv
    RBAC with domains/tenantsrbac_model_with_domains.confrbac_policy_with_domains.csv
    ABACabac_model.confN/A
    RESTfulkeymatch_model.confkeymatch_policy.csv
    Deny-overriderbac_model_with_deny.confrbac_policy_with_deny.csv
    Prioritypriority_model.confpriority_policy.csv