{"id":9576,"library":"cerbos","title":"Cerbos Python SDK","description":"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.","status":"active","version":"0.15.1","language":"en","source_language":"en","source_url":"https://github.com/cerbos/cerbos-sdk-python","tags":["authorization","access control","rbac","abac","grpc","security"],"install":[{"cmd":"pip install cerbos","lang":"bash","label":"Install Cerbos SDK"}],"dependencies":[{"reason":"Required for gRPC communication with the Cerbos Policy Decision Point (PDP).","package":"grpcio"},{"reason":"Required for serializing and deserializing data according to Protobuf definitions used by gRPC.","package":"protobuf"}],"imports":[{"symbol":"CerbosClient","correct":"from cerbos.sdk.client import CerbosClient"},{"note":"Use for asynchronous applications, `CerbosClient` is synchronous.","symbol":"AsyncCerbosClient","correct":"from cerbos.sdk.client import AsyncCerbosClient"},{"note":"Recommended for type-safe principal definitions, although dictionaries are also accepted by `is_allowed`.","symbol":"Principal","correct":"from cerbos.sdk.model import Principal"},{"note":"Recommended for type-safe resource definitions, although dictionaries are also accepted by `is_allowed`.","symbol":"Resource","correct":"from cerbos.sdk.model import Resource"},{"note":"Used for defining individual attributes, typically within Principal or Resource objects.","symbol":"Attribute","correct":"from cerbos.sdk.model import Attribute"}],"quickstart":{"code":"from cerbos.sdk.client import CerbosClient\nfrom cerbos.sdk.model import Principal, Resource\nimport os\n\n# Configure Cerbos PDP address (e.g., local server or Cerbos Cloud)\n# For local development, Cerbos usually runs on localhost:3593\nCERBOS_PDP_ADDR = os.environ.get('CERBOS_PDP_ADDR', 'localhost:3593')\n\ndef run_check():\n    client = CerbosClient(CERBOS_PDP_ADDR)\n\n    # Define the principal (user) making the request\n    principal = Principal(\n        id=\"john.doe\",\n        roles=[\"employee\"],\n        attributes={\n            \"department\": \"marketing\",\n            \"geography\": \"EU\"\n        }\n    )\n\n    # Define the resource being accessed\n    resource = Resource(\n        id=\"leave_request_123\",\n        kind=\"leave_request\",\n        attributes={\n            \"owner\": \"john.doe\",\n            \"status\": \"pending\",\n            \"geography\": \"EU\"\n        }\n    )\n\n    # Perform an authorization check\n    if client.is_allowed(\"view\", principal, resource):\n        print(f\"Principal '{principal.id}' IS ALLOWED to 'view' resource '{resource.id}'.\")\n    else:\n        print(f\"Principal '{principal.id}' IS NOT ALLOWED to 'view' resource '{resource.id}'.\")\n\n    # Example of a batch check\n    # You can also use client.check(inputs) for multiple checks at once\n    check_result = client.check(\n        inputs=[\n            client.check_input(\"view\", principal, resource),\n            client.check_input(\"edit\", principal, resource)\n        ]\n    )\n    print(f\"\\nBatch check results: {check_result.resource_instances['leave_request_123'].actions}\")\n\nif __name__ == '__main__':\n    print(f\"Attempting to connect to Cerbos PDP at: {CERBOS_PDP_ADDR}\")\n    try:\n        run_check()\n    except Exception as e:\n        print(f\"An error occurred. Is the Cerbos PDP running at {CERBOS_PDP_ADDR}? Error: {e}\")\n","lang":"python","description":"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."},"warnings":[{"fix":"Import `AsyncCerbosClient` instead of `CerbosClient` and use `await` before all client method calls, ensuring your application context supports async/await.","message":"The default `CerbosClient` is synchronous. For applications requiring non-blocking I/O (e.g., FastAPI, Sanic, Django with async views), you must explicitly use `AsyncCerbosClient` and `await` its methods.","severity":"gotcha","affected_versions":">=0.1.0"},{"fix":"Import and instantiate `Principal` and `Resource` from `cerbos.sdk.model` to construct your authorization request inputs, rather than relying on raw dictionaries.","message":"While `is_allowed` generally accepts plain dictionaries for principal and resource inputs, using `cerbos.sdk.model.Principal` and `cerbos.sdk.model.Resource` objects is recommended. These objects provide type-safety, better validation, and expose helpful methods (e.g., `with_attributes`).","severity":"gotcha","affected_versions":">=0.1.0"},{"fix":"Refactor multiple `is_allowed` calls into a single `client.check()` call with a list of `client.check_input()` objects, or consider `client.plan_resources()` for more complex scenarios involving filtering resource lists.","message":"The `is_allowed` method is for checking a single action on a single resource. For performing multiple checks efficiently in a single round trip to the Cerbos PDP, use the `check` method (which takes a list of `CheckInput` objects) or `plan_resources` for resource-based access decisions.","severity":"gotcha","affected_versions":">=0.1.0"},{"fix":"Ensure the Cerbos PDP is running and listening on the `CERBOS_PDP_ADDR` (default `localhost:3593`). Verify firewall rules and network connectivity if connecting to a remote server. Check Cerbos PDP logs for startup errors.","message":"Connecting to the Cerbos PDP requires the server to be running and accessible at the specified address. Network issues or an inactive PDP will result in connection errors.","severity":"gotcha","affected_versions":">=0.1.0"}],"env_vars":null,"last_verified":"2026-04-17T00:00:00.000Z","next_check":"2026-07-16T00:00:00.000Z","problems":[{"fix":"Ensure `cerbos` is installed in your active Python environment: `pip install cerbos`.","cause":"The `cerbos` library is not installed or the Python environment is incorrect.","error":"ModuleNotFoundError: No module named 'cerbos.sdk'"},{"fix":"Start your Cerbos PDP server. Verify that the `CERBOS_PDP_ADDR` environment variable or the address passed to `CerbosClient` (default `localhost:3593`) matches the PDP's listening address. Check firewall settings.","cause":"The Cerbos Policy Decision Point (PDP) server is not running or is inaccessible at the configured address and port.","error":"grpc.aio._channel._InactiveRpcError: <_InactiveRpcError of RPC that terminated with: status = StatusCode.UNAVAILABLE, details = \"Connect Failed\", debug_error_string = \"{\"created\":\"@1678881234.567890\",\"description\":\"Failed to connect to remote host: Connection refused\",\"file\":\"src/core/lib/transport/error_utils.cc\",\"file_line\":166,\"grpc_status\":14}\">"},{"fix":"Examine the `details` field in the error message for specific policy compilation failures. Review your Cerbos policies (`.yaml` files) and schema definitions. Ensure your `Principal` and `Resource` inputs conform to any defined schemas.","cause":"The Cerbos PDP encountered an error during policy evaluation, typically due to malformed policies, invalid schema definitions, or issues with the request structure that violate policy constraints.","error":"grpc.aio._channel._InactiveRpcError: <_InactiveRpcError of RPC that terminated with: status = StatusCode.FAILED_PRECONDITION, details = \"policy compilation failed: ...\", debug_error_string = \"...\">"},{"fix":"Always instantiate `Principal` and `Resource` objects from `cerbos.sdk.model` when you intend to use their object-oriented methods. For example: `principal = Principal(id='user').with_attributes(...)`.","cause":"You are attempting to use a method like `with_attributes()` (which belongs to `cerbos.sdk.model.Principal` or `Resource` objects) on a plain Python dictionary.","error":"AttributeError: 'dict' object has no attribute 'with_attributes'"}]}