Cerbos Python SDK

0.15.1 · active · verified Fri Apr 17

The Cerbos Python SDK (current version 0.15.1) provides a client library for interacting with the Cerbos Policy Decision Point (PDP). It enables Python applications to perform authorization checks, manage policies, and integrate with the open-core Cerbos authorization solution. Releases generally follow the main Cerbos project, with independent patch versions for the SDK.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to create a `CerbosClient`, define a `Principal` and `Resource`, and perform a basic `is_allowed` authorization check. It also shows a simple batch check using `client.check` and `client.check_input`. Ensure a Cerbos PDP instance is running at the specified address (defaulting to `localhost:3593`) for the example to connect successfully.

from cerbos.sdk.client import CerbosClient
from cerbos.sdk.model import Principal, Resource
import os

# Configure Cerbos PDP address (e.g., local server or Cerbos Cloud)
# For local development, Cerbos usually runs on localhost:3593
CERBOS_PDP_ADDR = os.environ.get('CERBOS_PDP_ADDR', 'localhost:3593')

def run_check():
    client = CerbosClient(CERBOS_PDP_ADDR)

    # Define the principal (user) making the request
    principal = Principal(
        id="john.doe",
        roles=["employee"],
        attributes={
            "department": "marketing",
            "geography": "EU"
        }
    )

    # Define the resource being accessed
    resource = Resource(
        id="leave_request_123",
        kind="leave_request",
        attributes={
            "owner": "john.doe",
            "status": "pending",
            "geography": "EU"
        }
    )

    # Perform an authorization check
    if client.is_allowed("view", principal, resource):
        print(f"Principal '{principal.id}' IS ALLOWED to 'view' resource '{resource.id}'.")
    else:
        print(f"Principal '{principal.id}' IS NOT ALLOWED to 'view' resource '{resource.id}'.")

    # Example of a batch check
    # You can also use client.check(inputs) for multiple checks at once
    check_result = client.check(
        inputs=[
            client.check_input("view", principal, resource),
            client.check_input("edit", principal, resource)
        ]
    )
    print(f"\nBatch check results: {check_result.resource_instances['leave_request_123'].actions}")

if __name__ == '__main__':
    print(f"Attempting to connect to Cerbos PDP at: {CERBOS_PDP_ADDR}")
    try:
        run_check()
    except Exception as e:
        print(f"An error occurred. Is the Cerbos PDP running at {CERBOS_PDP_ADDR}? Error: {e}")

view raw JSON →