Python API

Classes

class oso.Oso(*, forbidden_error=<class 'oso.exceptions.ForbiddenError'>, not_found_error=<class 'oso.exceptions.NotFoundError'>, read_action='read')

The central object to manage application policy state, e.g. the policy data, and verify requests.

>>> from oso import Oso
>>> Oso()
<oso.oso.Oso object at 0x...>
__init__(*, forbidden_error=<class 'oso.exceptions.ForbiddenError'>, not_found_error=<class 'oso.exceptions.NotFoundError'>, read_action='read')

Create an Oso object.

Parameters
  • forbidden_error – Optionally override the error class that is raised when an action is unauthorized.

  • not_found_error – Optionally override the error class that is raised by the authorize method when an action is unauthorized AND the actor does not have permission to "read" the resource (and thus should not know it exists).

  • read_action – The action used by the authorize method to determine whether an authorization failure should raise a NotFoundError or a ForbiddenError.

authorize(actor, action, resource, *, check_read=True)

Ensure that actor is allowed to perform action on resource.

If the action is permitted with an allow rule in the policy, then this method returns None. If the action is not permitted by the policy, this method will raise an error.

The error raised by this method depends on whether the actor can perform the "read" action on the resource. If they cannot read the resource, then a NotFound error is raised. Otherwise, a ForbiddenError is raised.

Parameters
  • actor – The actor performing the request.

  • action – The action the actor is attempting to perform.

  • resource – The resource being accessed.

  • check_read (bool) – If set to False, a ForbiddenError is always thrown on authorization failures, regardless of whether the actor can read the resource. Default is True.

authorize_field(actor, action, resource, field)

Ensure that actor is allowed to perform action on a given resource’s field.

If the action is permitted by an allow_field rule in the policy, then this method returns None. If the action is not permitted by the policy, this method will raise a ForbiddenError.

Parameters
  • actor – The actor performing the request.

  • action – The action the actor is attempting to perform on the field.

  • resource – The resource being accessed.

  • field – The name of the field being accessed.

authorize_request(actor, request)

Ensure that actor is allowed to send request to the server.

Checks the allow_request rule of a policy.

If the request is permitted with an allow_request rule in the policy, then this method returns None. Otherwise, this method raises a ForbiddenError.

Parameters
  • actor – The actor performing the request.

  • request – An object representing the request that was sent by the actor.

authorized_actions(actor, resource, allow_wildcard=False) Set[Any]

Determine the actions actor is allowed to take on resource.

Collects all actions allowed by allow rules in the Polar policy for the given combination of actor and resource.

Identical to Oso.get_allowed_actions.

Parameters
  • actor – The actor for whom to collect allowed actions

  • resource – The resource being accessed

  • allow_wildcard (bool) – Flag to determine behavior if the policy contains an “unconstrained” action that could represent any action: allow(_actor, _action, _resource). If True, the method will return ["*"], if False (the default), the method will raise an exception.

Returns

A set containing all allowed actions.

authorized_fields(actor, action, resource, allow_wildcard=False) Set[Any]

Determine the fields of resource on which actor is allowed to perform action.

Uses allow_field rules in the policy to find all allowed fields.

Parameters
  • actor – The actor for whom to collect allowed fields.

  • action – The action being taken on the fields.

  • resource – The resource being accessed.

  • allow_wildcard (bool) – Flag to determine behavior if the policy includes a wildcard field. E.g., a rule allowing any field: allow_field(_actor, _action, _resource, _field). If True, the method will return ["*"], if False, the method will raise an exception.

Returns

A set containing all allowed fields.

authorized_query(actor, action, resource_cls)

Create a query for resources of type resource_cls that actor is allowed to perform action on. The query is built by using the build_query and combine_query functions registered for the resource_cls.

Parameters
  • actor – The actor for whom to collect allowed resources.

  • action – The action that user wants to perform.

  • resource_cls – The type of the resources.

Returns

A query to fetch the resources,

authorized_resources(actor, action, resource_cls) List[Any]

Determine the resources of type resource_cls that actor is allowed to perform action on.

Parameters
  • actor – The actor for whom to collect allowed resources.

  • action – The action that user wants to perform.

  • resource_cls – The type of the resources.

Returns

The requested resources.

get_allowed_actions(actor, resource, allow_wildcard=False) List[Any]

Determine the actions actor is allowed to take on resource.

Deprecated. Use authorized_actions instead.

is_allowed(actor, action, resource) bool

Evaluate whether actor is allowed to perform action on resource.

Uses allow rules in the Polar policy to determine whether a request is permitted. actor and resource should be classes that have been registered with Polar using the register_class() function or the polar_class decorator.

Parameters
  • actor – The actor performing the request.

  • action – The action the actor is attempting to perform.

  • resource – The resource being accessed.

Returns

True if the request is allowed, False otherwise.

load_file(filename: Union[pathlib.Path, str])

Load Polar policy from a “.polar” file.

Oso.load_file has been deprecated in favor of Oso.load_files as of the 0.20 release. Please see changelog for migration instructions: https://docs.osohq.com/project/changelogs/2021-09-15.html

load_files(filenames: List[Union[pathlib.Path, str]] = [])

Load Polar policy from “.polar” files.

load_str(string: str)

Load a Polar string, checking that all inline queries succeed.

query(query, *, bindings=None, accept_expression=False)

Query for a predicate, parsing it if necessary.

Parameters

query – The predicate to query for.

Returns

The result of the query.

query_rule(name, *args, **kwargs)

Query for rule with name name and arguments args.

Parameters
  • name – The name of the predicate to query.

  • args – Arguments for the predicate.

Returns

The result of the query.

register_class(cls, *, name=None, types=None, build_query=None, exec_query=None, combine_query=None)

Register cls as a class accessible by Polar.

Parameters
  • name – Optionally specify the name for the class inside of Polar. Defaults to cls.__name__

  • types – Optional dict mapping field names to types or Relation objects for data filtering.

  • build_query – Optional function to generate a query for resources of type cls from a list of Filters.

  • exec_query – Optional function to execute a query produced by build_query.

  • combine_query – Optional function to merge two queries produced by build_query.

set_data_filtering_query_defaults(build_query=None, exec_query=None, combine_query=None)

Register default values for data filtering query functions. These can be overridden by passing specific implementations to register_class

class oso.Variable

An unbound variable type, can be used to query the KB for information

class oso.Predicate(name: str, args: Sequence[Any])

Represent a predicate in Polar (name(args, …)).

class polar.Relation(kind: str, other_type: str, my_field: str, other_field: str)

An object representing a relation between two types registered with Oso.

class polar.Filter(kind: str, field: str, value: Any)

An object representing a predicate on a type registered with Oso.

Decorator Functions

oso.polar_class(_cls=None, *, name=None)

Decorator to register a Python class with Polar. An alternative to register_class().

Exceptions

exception oso.exceptions.AuthorizationError(message=None, details=None)

Bases: polar.exceptions.OsoError

exception oso.exceptions.ForbiddenError

Bases: oso.exceptions.AuthorizationError

Thrown by the authorize, authorize_field, and authorize_request methods when the action is not allowed.

Most of the time, your app should handle this error by returning a 403 HTTP error to the client.

exception oso.exceptions.NotFoundError

Bases: oso.exceptions.AuthorizationError

Thrown by the authorize method of an Oso instance. This error indicates that the actor is not only not allowed to perform the given action but also is not allowed to "read" the given resource.

Most of the time, your app should handle this error by returning a 404 HTTP error to the client.

To control which action is used for the distinction between NotFoundError and ForbiddenError, you can customize the read_action on your Oso instance.

Exceptions used within Oso.

exception polar.exceptions.DuplicateClassAliasError(name, old, new)

Bases: polar.exceptions.PolarRuntimeError

Raised on attempts to register a class with the same name as a class that has already been registered

exception polar.exceptions.DuplicateInstanceRegistrationError(message=None, details=None)

Bases: polar.exceptions.PolarRuntimeError

exception polar.exceptions.ExtraToken(message=None, details=None)

Bases: polar.exceptions.ParserError

exception polar.exceptions.FFIErrorNotFound(message=None, details=None)

Bases: polar.exceptions.OsoError

Raised when an error is generated by the Oso Rust core, but the error type is not found.

exception polar.exceptions.FileLoadingError(message=None, details=None)

Bases: polar.exceptions.PolarRuntimeError

Error loading a Polar file

exception polar.exceptions.InlineQueryFailedError(source)

Bases: polar.exceptions.PolarRuntimeError

exception polar.exceptions.IntegerOverflow(message=None, details=None)

Bases: polar.exceptions.ParserError

exception polar.exceptions.InvalidCallError(message=None, details=None)

Bases: polar.exceptions.PolarRuntimeError

Invalid attempt to call a field or method on an object in Polar

exception polar.exceptions.InvalidConstructorError(message=None, details=None)

Bases: polar.exceptions.PolarRuntimeError

exception polar.exceptions.InvalidIteratorError(message=None, details=None)

Bases: polar.exceptions.PolarRuntimeError

Invalid attempt to iterate over a non-iterable value

exception polar.exceptions.InvalidQueryTypeError(message=None, details=None)

Bases: polar.exceptions.PolarRuntimeError

exception polar.exceptions.InvalidToken(message=None, details=None)

Bases: polar.exceptions.ParserError

exception polar.exceptions.InvalidTokenCharacter(message=None, details=None)

Bases: polar.exceptions.ParserError

exception polar.exceptions.OperationalError(message=None, details=None)

Bases: polar.exceptions.OsoError

Errors from polar that are not necessarily the user’s fault. OOM etc…

exception polar.exceptions.OsoError(message=None, details=None)

Bases: Exception

Base exception class for Oso.

exception polar.exceptions.ParameterError(message=None, details=None)

Bases: polar.exceptions.PolarApiError

exception polar.exceptions.ParserError(message=None, details=None)

Bases: polar.exceptions.OsoError

Parse time errors.

exception polar.exceptions.PolarApiError(message=None, details=None)

Bases: polar.exceptions.OsoError

Errors coming from the python bindings to polar, not the engine itself.

exception polar.exceptions.PolarFileExtensionError(file)

Bases: polar.exceptions.PolarRuntimeError

exception polar.exceptions.PolarFileNotFoundError(file)

Bases: polar.exceptions.PolarRuntimeError

exception polar.exceptions.PolarRuntimeError(message=None, details=None)

Bases: polar.exceptions.OsoError

Errors generated by Oso at runtime

exception polar.exceptions.PolarTypeError(message=None, details=None)

Bases: polar.exceptions.PolarRuntimeError

Error related to the type of a Polar object, generated by the Rust core

exception polar.exceptions.SerializationError(message=None, details=None)

Bases: polar.exceptions.PolarRuntimeError

Error serializing data across the FFI boundary

exception polar.exceptions.StackOverflowError(message=None, details=None)

Bases: polar.exceptions.PolarRuntimeError

Polar stack overflow error, generated by the Rust core

exception polar.exceptions.UnexpectedPolarTypeError(message=None, details=None)

Bases: polar.exceptions.PolarRuntimeError

exception polar.exceptions.UnknownError(message=None, details=None)

Bases: polar.exceptions.OperationalError

exception polar.exceptions.UnrecognizedEOF(message=None, details=None)

Bases: polar.exceptions.ParserError

exception polar.exceptions.UnrecognizedToken(message=None, details=None)

Bases: polar.exceptions.ParserError

exception polar.exceptions.UnregisteredClassError(message=None, details=None)

Bases: polar.exceptions.PolarRuntimeError

Raised on attempts to reference unregistered Python classes from a Polar policy.

exception polar.exceptions.UnregisteredInstanceError(message=None, details=None)

Bases: polar.exceptions.PolarRuntimeError

exception polar.exceptions.UnsupportedError(message=None, details=None)

Bases: polar.exceptions.PolarRuntimeError

Unsupported action error generated by the Rust core

exception polar.exceptions.ValidationError(message=None, details=None)

Bases: polar.exceptions.PolarApiError