Skip to main content

Pythonic builder for Oso's Polar policies

Project description

Oso Policy Builder

⚠️ Experimental Release: This is an early experimental library for building Oso's Polar policies in Python. It's far from feature-complete and has many limitations. Not intended for production use. Use at your own discretion.

💬 We want your feedback! Have a comment or feature request? Email the Oso engineer who worked on this library directly: connor@osohq.com

Python 3.13+

A python library for building Oso Cloud authorization policies. Write your authorization logic in clean Python syntax and automatically generate Polar code.

Installation

pip install oso-policy-builder

Quick Start

from oso_policy_builder import PolicyBuilder, User, Resource

# Define resources with permissions and roles by creating a subclass of `Resource`
# You must declare all permissions, roles, and relations used in your policy as resource fields.
class Document(Resource):
    permissions = ["read", "write", "delete"]
    roles = ["viewer", "editor"]
    relations={"project": Project}


# Define authorization rules using Python
User.with_role("viewer").can("read").on(Document)  # Anyone can read
User.with_role("editor").can("read", "write", "delete").on(Document)  # Editors can read, write or delete

# Generate Polar policy
policy = PolicyBuilder()
print(policy.generate())

This generates valid Polar code:

# Generated by Oso Policy Builder

actor User {}

resource Document {
  permissions = ["read", "write", "delete"];
  roles = ["viewer", "editor"];

  "read" if "viewer";
  "read" if "editor"
  "write" if "editor";
  "delete" if "editor";
}

Complex Conditions

You can build complex authorization logic with conditions:

from oso_policy_builder import and_, or_, not_

# Complex conditional permissions
User.can("publish").on(Document).when(
    and_(
        User.has_role("editor"),
        not_(Document.has_attribute("is_archived")),
        or_(
            Document.has_attribute("is_reviewed"),
            User.has_permission("admin_override")
        )
    )
)

Role Inheritance

Set up role hierarchies and cross-resource permissions:

class Project(Resource):
    permissions = ["read", "manage"]
    roles = ["member", "admin"]

class Document(Resource):
    permissions = ["read", "write"]
    roles = ["viewer", "editor"]
    relations = {"project": Project}

# Role inheritance
User.with_role("editor").inherits_role("viewer").on(Document)

# Cross-resource permissions
User.with_role("admin").on(Project).can("write").on(Document)

Global Permissions

Define application-wide permissions that aren't tied to specific resources:

from oso_policy_builder import BaseGlobal, attribute

# Define global permissions and roles
class Global(BaseGlobal):
    roles = ["admin", "moderator"]
    permissions = [
        "view_analytics",
        "manage_users",
        "system_settings",
        "audit_logs"
    ]

# Create custom global attributes with the @attribute decorator
@attribute(User)
def is_privileged(user: User):
    """
    returns: is_privileged(user: User) if
               role matches String and
               role in ["admin", "moderator"] and
               has_role(user, role);
    """
    return user.has_role_in(["admin", "moderator"])

# Grant global permissions based on custom attributes
Global.can("view_analytics").when(is_privileged(User))

# Or grant multiple permissions at once
for permission in Global.permissions:
    Global.can(permission).when(is_privileged(User))

Save Your Policy

# Save to file for use with Oso Cloud
policy = PolicyBuilder()
policy.save("authorization.polar")  # Saves to current directory
policy.save("my-policy.polar", directory="./policies")  # Custom location

Fluent API Reference

The library provides a fluent, chainable API for building authorization rules:

User/Actor Methods

# Permission rules
User.can("read")                    # Start a permission rule
User.can("read").on(Resource)       # Grant permission on a resource
User.can("read").on(Resource).when(condition)  # Add conditions

# Role-based rules
User.with_role("editor")            # Start a role-based rule
User.with_role("editor").can("write").on(Resource)  # Grant permissions to a role
User.with_role("editor").inherits_role("viewer").on(Resource)  # Role inheritance

# Condition helpers
User.has_role("admin")              # Check if user has a role
User.has_permission("manage")       # Check if user has a permission
User.has_relation("owner")          # Check if user has a relation
User.has_role_in(["admin", "mod"])  # Check if user has any role from list

Resource Methods

# Attribute conditions
Document.has_attribute("is_public")     # Check resource attributes

Logical Operators

from oso_policy_builder import and_, or_, not_

# Combine conditions
and_(condition1, condition2, condition3)   # All must be true
or_(condition1, condition2)               # Any must be true
not_(condition)                           # Negation

Method Chaining Examples

# Chain role permissions
User.with_role("admin").can("read", "write", "delete").on(Document)

# Chain role inheritance
User.with_role("editor").inherits_role("viewer").on(Document)

# Chain multiple permission grants
(User.with_role("editor").on(Project)
    .can("write").on(Document)
    .can("delete").on(Comment))

# Chain conditions
User.can("publish").on(Document).when(
    or_(
        and_(
            User.has_role("editor"),
            Document.has_attribute("is_reviewed")
        )
        User.has_permission("admin_override"))
)

Integration with Oso Cloud

Use your generated policies with Oso Cloud:

  1. Generate your policy with this library
  2. Upload the .polar file to Oso Cloud
  3. Use Oso's SDKs to make authorization decisions in your application

For complete Oso Cloud documentation, visit osohq.com/docs.

Current Limitations

This is an experimental library with several limitations:

  • Limited Polar feature coverage - Not all Polar language features are supported
  • Basic validation - Limited error checking and validation
  • Experimental API - This library's API may change in future versions
  • No backward compatibility guarantees - This is an experimental proof-of-concept

Requirements

  • Python 3.13+

Feedback & Feature Requests

This is an experimental project and we'd love your feedback! If you:

  • Find bugs or limitations
  • Have ideas for new features
  • Want to discuss authorization patterns
  • Need help with complex use cases

Please reach out directly to the engineer who worked on this library: connor@osohq.com


Built by the team at Oso - Authorization as a Service

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

oso_policy_builder-0.1.0.tar.gz (12.5 kB view details)

Uploaded Source

Built Distribution

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

oso_policy_builder-0.1.0-py3-none-any.whl (14.5 kB view details)

Uploaded Python 3

File details

Details for the file oso_policy_builder-0.1.0.tar.gz.

File metadata

  • Download URL: oso_policy_builder-0.1.0.tar.gz
  • Upload date:
  • Size: 12.5 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.12.9

File hashes

Hashes for oso_policy_builder-0.1.0.tar.gz
Algorithm Hash digest
SHA256 e2f3a06b4846345b9853ce439c21198cd4dea263ae61adf36a3570b98a65595f
MD5 a118e12b255ed649bbab69400606e8d7
BLAKE2b-256 6f7d31ddad3827dfb69ebae16106961be584b808cf5d1c5b62c5ad65889e3f05

See more details on using hashes here.

Provenance

The following attestation bundles were made for oso_policy_builder-0.1.0.tar.gz:

Publisher: publish.yml on osohq/ossso

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file oso_policy_builder-0.1.0-py3-none-any.whl.

File metadata

File hashes

Hashes for oso_policy_builder-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 8037cac30efea29d54e17a901d1a002e0a067cb8aba8942f14a100bcd9139b44
MD5 643dbbf6ab98a6d131282f0e1fdb0640
BLAKE2b-256 08383f7ea3fdcdfb1154aa520195b21d3053e764871e23d4fb4f0662d3b03974

See more details on using hashes here.

Provenance

The following attestation bundles were made for oso_policy_builder-0.1.0-py3-none-any.whl:

Publisher: publish.yml on osohq/ossso

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

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