Python API

Classes

class oso.Oso(*, forbidden_error: ~typing.Type[BaseException] = <class 'oso.exceptions.ForbiddenError'>, not_found_error: ~typing.Type[BaseException] = <class 'oso.exceptions.NotFoundError'>, read_action: str = '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: ~typing.Type[BaseException] = <class 'oso.exceptions.ForbiddenError'>, not_found_error: ~typing.Type[BaseException] = <class 'oso.exceptions.NotFoundError'>, read_action: str = 'read') None

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: object, action: str, resource: object, *, check_read: bool = True) None

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: object, action: str, resource: object, field: str) None

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: object, request: object) None

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: object, resource: object, allow_wildcard: bool = 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: object, action: str, resource: object, allow_wildcard: bool = 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: object, action: str, resource_cls: Type[object])

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: object, action: str, resource_cls: Type[object]) 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: object, resource: object, allow_wildcard: bool = False) List[Any]

Determine the actions actor is allowed to take on resource.

Deprecated. Use authorized_actions instead.

is_allowed(actor: object, action: str, resource: object) 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.

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[Path, str]) None

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: Optional[List[Union[Path, str]]] = None) None

Load Polar policy from “.polar” files.

load_str(string: str) None

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, fields=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__

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

register_constant(value, name)

Register value as a Polar constant variable called name.

Parameters:
  • value – The value to register as a constant.

  • name – The name under which the constant will be visible in Polar.

set_data_filtering_adapter(adapter: DataAdapter) None

Set a global adapter for the new data filtering interface.

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.DataFilter(model, relations, conditions, types)

An object representing an abstract query over a particular data type

class polar.Condition(left, cmp, right)

An object representing a WHERE condition on a query.

cmp is an equality or inequality operator.

left and right may be Projections or literal data.

class polar.Projection(source, field)

An object representing a named property (field) of a particular data type (source). field may be None, which user code must translate to a field (usually the primary key column in a database) that uniquely identifies the record.

class polar.data.adapter.sqlalchemy_adapter.SqlAlchemyAdapter(session: Session)

Exceptions

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

Bases: OsoError

exception oso.exceptions.ForbiddenError

Bases: 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: 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: 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: PolarRuntimeError

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

Bases: ParserError

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

Bases: OsoError

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

exception polar.exceptions.InlineQueryFailedError(source)

Bases: PolarRuntimeError

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

Bases: ParserError

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

Bases: PolarRuntimeError

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

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

Bases: PolarRuntimeError

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

Bases: PolarRuntimeError

Invalid attempt to iterate over a non-iterable value

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

Bases: PolarRuntimeError

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

Bases: ParserError

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

Bases: ParserError

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

Bases: 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.ParserError(message=None, details=None)

Bases: OsoError

Parse time errors.

exception polar.exceptions.PolarFileExtensionError(file)

Bases: PolarRuntimeError

exception polar.exceptions.PolarFileNotFoundError(file)

Bases: PolarRuntimeError

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

Bases: OsoError

Errors generated by Oso at runtime

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

Bases: PolarRuntimeError

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

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

Bases: PolarRuntimeError

Polar stack overflow error, generated by the Rust core

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

Bases: PolarRuntimeError

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

Bases: OperationalError

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

Bases: ParserError

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

Bases: ParserError

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

Bases: PolarRuntimeError

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

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

Bases: PolarRuntimeError

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

Bases: PolarRuntimeError

Unsupported action error generated by the Rust core

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

Bases: OsoError