oslo_policy package

Submodules

oslo_policy.fixture module

class oslo_policy.fixture.HttpCheckFixture(return_value=True)

Bases: Fixture

Helps short circuit the external http call

setUp()

Prepare the Fixture for use.

This should not be overridden. Concrete fixtures should implement _setUp. Overriding of setUp is still supported, just not recommended.

After setUp has completed, the fixture will have one or more attributes which can be used (these depend totally on the concrete subclass).

Raises:

MultipleExceptions if _setUp fails. The last exception captured within the MultipleExceptions will be a SetupError exception.

Returns:

None.

Changed in 1.3:

The recommendation to override setUp has been reversed - before 1.3, setUp() should be overridden, now it should not be.

Changed in 1.3.1:

BaseException is now caught, and only subclasses of Exception are wrapped in MultipleExceptions.

class oslo_policy.fixture.HttpsCheckFixture(return_value=True)

Bases: Fixture

Helps short circuit the external http call

setUp()

Prepare the Fixture for use.

This should not be overridden. Concrete fixtures should implement _setUp. Overriding of setUp is still supported, just not recommended.

After setUp has completed, the fixture will have one or more attributes which can be used (these depend totally on the concrete subclass).

Raises:

MultipleExceptions if _setUp fails. The last exception captured within the MultipleExceptions will be a SetupError exception.

Returns:

None.

Changed in 1.3:

The recommendation to override setUp has been reversed - before 1.3, setUp() should be overridden, now it should not be.

Changed in 1.3.1:

BaseException is now caught, and only subclasses of Exception are wrapped in MultipleExceptions.

oslo_policy.generator module

oslo_policy.generator.convert_policy_json_to_yaml(args=None, conf=None)
oslo_policy.generator.generate_policy(args=None)
oslo_policy.generator.generate_sample(args=None, conf=None)
oslo_policy.generator.get_policies_dict(namespaces)

Find the options available via the given namespaces.

Parameters:

namespaces – a list of namespaces registered under ‘oslo.policy.policies’

Returns:

a dict of {namespace1: [rule_default_1, rule_default_2], namespace2: [rule_default_3]…}

oslo_policy.generator.list_redundant(args=None)
oslo_policy.generator.on_load_failure_callback(*args, **kwargs)
oslo_policy.generator.upgrade_policy(args=None, conf=None)
oslo_policy.generator.validate_policy(args=None)

oslo_policy.opts module

oslo_policy.opts.list_opts()

Return a list of oslo.config options available in the library.

The returned list includes all oslo.config options which may be registered at runtime by the library. Each element of the list is a tuple. The first element is the name of the group under which the list of elements in the second element will be registered. A group name of None corresponds to the [DEFAULT] group in config files. This function is also discoverable via the ‘oslo_messaging’ entry point under the ‘oslo.config.opts’ namespace. The purpose of this is to allow tools like the Oslo sample config file generator to discover the options exposed to users by this library.

Returns:

a list of (group_name, opts) tuples

oslo_policy.opts.set_defaults(conf, policy_file=None, **kwargs)

Set defaults for configuration variables.

Overrides default options values.

Parameters:
  • conf (oslo.config.cfg.ConfigOpts) – Configuration object, managed by the caller.

  • policy_file (unicode) – The base filename for the file that defines policies.

  • kwargs – Any other configuration variable and their new default value.

oslo_policy.policy module

Common Policy Engine Implementation

Policies are expressed as a target and an associated rule:

"<target>": <rule>

The target is specific to the service that is conducting policy enforcement. Typically, the target refers to an API call.

For the <rule> part, see Policy Rule Expressions.

Policy Rule Expressions

Policy rules can be expressed in one of two forms: a string written in the new policy language or a list of lists. The string format is preferred since it’s easier for most people to understand.

In the policy language, each check is specified as a simple “a:b” pair that is matched to the correct class to perform that check:

TYPE

SYNTAX

User’s Role

role:admin

Rules already defined on policy

rule:admin_required

Against URLs¹

http://my-url.org/check

User attributes²

project_id:%(target.project.id)s

Strings

  • <variable>:’xpto2035abc’

  • ‘myproject’:<variable>

Literals

  • project_id:xpto2035abc

  • domain_id:20

  • True:%(user.enabled)s

¹URL checking must return True to be valid

²User attributes (obtained through the token): user_id, domain_id or project_id

Conjunction operators and and or are available, allowing for more expressiveness in crafting policies. For example:

"role:admin or (project_id:%(project_id)s and role:projectadmin)"

The policy language also has the not operator, allowing a richer policy rule:

"project_id:%(project_id)s and not role:dunce"

Operator precedence is below:

PRECEDENCE

TYPE

EXPRESSION

4

Grouping

(…)

3

Logical NOT

not …

2

Logical AND

… and …

1

Logical OR

… or …

Operator with larger precedence number precedes others with smaller numbers.

In the list-of-lists representation, each check inside the innermost list is combined as with an “and” conjunction – for that check to pass, all the specified checks must pass. These innermost lists are then combined as with an “or” conjunction. As an example, take the following rule, expressed in the list-of-lists representation:

[["role:admin"], ["project_id:%(project_id)s", "role:projectadmin"]]

Finally, two special policy checks should be mentioned; the policy check “@” will always accept an access, and the policy check “!” will always reject an access. (Note that if a rule is either the empty list ([]) or the empty string (""), this is equivalent to the “@” policy check.) Of these, the “!” policy check is probably the most useful, as it allows particular rules to be explicitly disabled.

Generic Checks

A generic check is used to perform matching against attributes that are sent along with the API calls. These attributes can be used by the policy engine (on the right side of the expression), by using the following syntax:

<some_attribute>:%(user.id)s

The value on the right-hand side is either a string or resolves to a string using regular Python string substitution. The available attributes and values are dependent on the program that is using the common policy engine.

All of these attributes (related to users, API calls, and context) can be checked against each other or against constants. It is important to note that these attributes are specific to the service that is conducting policy enforcement.

Generic checks can be used to perform policy checks on the following user attributes obtained through a token:

  • user_id

  • domain_id or project_id (depending on the token scope)

  • list of roles held for the given token scope

Note

Some resources which are exposed by the API do not support policy enforcement by user_id, and only support policy enforcement by project_id. Some global resources do not support policy enforcement by combination of user_id and project_id.

For example, a check on the user_id would be defined as:

user_id:<some_value>

Together with the previously shown example, a complete generic check would be:

user_id:%(user.id)s

It is also possible to perform checks against other attributes that represent the credentials. This is done by adding additional values to the creds dict that is passed to the enforce() method.

Special Checks

Special checks allow for more flexibility than is possible using generic checks. The built-in special check types are role, rule, and http checks.

Role Check

A role check is used to check if a specific role is present in the supplied credentials. A role check is expressed as:

"role:<role_name>"

Rule Check

A rule check is used to reference another defined rule by its name. This allows for common checks to be defined once as a reusable rule, which is then referenced within other rules. It also allows one to define a set of checks as a more descriptive name to aid in readability of policy. A rule check is expressed as:

"rule:<rule_name>"

The following example shows a role check that is defined as a rule, which is then used via a rule check:

"admin_required": "role:admin"
"<target>": "rule:admin_required"

HTTP Check

An http check is used to make an HTTP request to a remote server to determine the results of the check. The target and credentials are passed to the remote server for evaluation. The action is authorized if the remote server returns a response of True. An http check is expressed as:

"http:<target URI>"

It is expected that the target URI contains a string formatting keyword, where the keyword is a key from the target dictionary. An example of an http check where the name key from the target is used to construct the URL is would be defined as:

"http://server.test/%(name)s"

Registering New Special Checks

It is also possible for additional special check types to be registered using the register() function.

The following classes can be used as parents for custom special check types:

Default Rule

A default rule can be defined, which will be enforced when a rule does not exist for the target that is being checked. By default, the rule associated with the rule name of default will be used as the default rule. It is possible to use a different rule name as the default rule by setting the policy_default_rule configuration setting to the desired rule name.

class oslo_policy.policy.AndCheck(rules)

Bases: BaseCheck

add_check(rule)

Adds rule to be tested.

Allows addition of another rule to the list of rules that will be tested.

Returns:

self

Return type:

AndCheck

class oslo_policy.policy.Check(kind, match)

Bases: BaseCheck

class oslo_policy.policy.DeprecatedRule(name: str, check_str: str, *, deprecated_reason: str | None = None, deprecated_since: str | None = None)

Bases: _BaseRule

Represents a Deprecated policy or rule.

Here’s how you can use it to change a policy’s default role or rule. Assume the following policy exists in code:

from oslo_policy import policy

policy.DocumentedRuleDefault(
    name='foo:create_bar',
    check_str='role:fizz',
    description='Create a bar.',
    operations=[{'path': '/v1/bars', 'method': 'POST'}]
)

The next snippet will maintain the deprecated option, but allow foo:create_bar to default to role:bang instead of role:fizz:

deprecated_rule = policy.DeprecatedRule(
    name='foo:create_bar',
    check_str='role:fizz'
    deprecated_reason='role:bang is a better default',
    deprecated_since='N',
)

policy.DocumentedRuleDefault(
    name='foo:create_bar',
    check_str='role:bang',
    description='Create a bar.',
    operations=[{'path': '/v1/bars', 'method': 'POST'}],
    deprecated_rule=deprecated_rule,
)

DeprecatedRule can be used to change the policy name itself. Assume the following policy exists in code:

from oslo_policy import policy

policy.DocumentedRuleDefault(
    name='foo:post_bar',
    check_str='role:fizz',
    description='Create a bar.',
    operations=[{'path': '/v1/bars', 'method': 'POST'}]
)

For the sake of consistency, let’s say we want to replace foo:post_bar with foo:create_bar, but keep the same check_str as the default. We can accomplish this by doing:

deprecated_rule = policy.DeprecatedRule(
    name='foo:post_bar',
    check_str='role:fizz'
    deprecated_reason='foo:create_bar is more consistent',
    deprecated_since='N',
)

policy.DocumentedRuleDefault(
    name='foo:create_bar',
    check_str='role:fizz',
    description='Create a bar.',
    operations=[{'path': '/v1/bars', 'method': 'POST'}],
    deprecated_rule=deprecated_rule,
)

Finally, let’s use DeprecatedRule to break a policy into more granular policies. Let’s assume the following policy exists in code:

policy.DocumentedRuleDefault(
    name='foo:bar',
    check_str='role:bazz',
    description='Create, read, update, or delete a bar.',
    operations=[
        {
            'path': '/v1/bars',
            'method': 'POST'
        },
        {
            'path': '/v1/bars',
            'method': 'GET'
        },
        {
            'path': '/v1/bars/{bar_id}',
            'method': 'GET'
        },
        {
            'path': '/v1/bars/{bar_id}',
            'method': 'PATCH'
        },
        {
            'path': '/v1/bars/{bar_id}',
            'method': 'DELETE'
        }
    ]
)

Here we can see the same policy is used to protect multiple operations on bars. This prevents operators from being able to assign different roles to different actions that can be taken on bar. For example, what if an operator wanted to require a less restrictive role or rule to list bars but a more restrictive rule to delete them? The following will introduce a policy that helps achieve that and deprecate the original, overly-broad policy:

deprecated_rule = policy.DeprecatedRule(
    name='foo:bar',
    check_str='role:bazz'
    deprecated_reason=(
        'foo:bar has been replaced by more granular policies'
    ),
    deprecated_since='N',
)

policy.DocumentedRuleDefault(
    name='foo:create_bar',
    check_str='role:bang',
    description='Create a bar.',
    operations=[{'path': '/v1/bars', 'method': 'POST'}],
    deprecated_rule=deprecated_rule,
)
policy.DocumentedRuleDefault(
    name='foo:list_bars',
    check_str='role:bazz',
    description='List bars.',
    operations=[{'path': '/v1/bars', 'method': 'GET'}],
    deprecated_rule=deprecated_rule,
)
policy.DocumentedRuleDefault(
    name='foo:get_bar',
    check_str='role:bazz',
    description='Get a bar.',
    operations=[{'path': '/v1/bars/{bar_id}', 'method': 'GET'}],
    deprecated_rule=deprecated_rule,
)
policy.DocumentedRuleDefault(
    name='foo:update_bar',
    check_str='role:bang',
    description='Update a bar.',
    operations=[{'path': '/v1/bars/{bar_id}', 'method': 'PATCH'}],
    deprecated_rule=deprecated_rule,
)
policy.DocumentedRuleDefault(
    name='foo:delete_bar',
    check_str='role:bang',
    description='Delete a bar.',
    operations=[{'path': '/v1/bars/{bar_id}', 'method': 'DELETE'}],
    deprecated_rule=deprecated_rule,
)
Parameters:
  • name – The name of the policy. This is used when referencing it from another rule or during policy enforcement.

  • check_str – The policy. This is a string defining a policy that conforms to the policy language outlined at the top of the file.

  • deprecated_reason – indicates why this policy is planned for removal in a future release.

  • deprecated_since – indicates which release this policy was deprecated in. Accepts any string, though valid version strings are encouraged.

Changed in version 1.29: Added DeprecatedRule object.

Changed in version 3.4: Added deprecated_reason parameter.

Changed in version 3.4: Added deprecated_since parameter.

property deprecated_reason
property deprecated_since
class oslo_policy.policy.DocumentedRuleDefault(name, check_str, description, operations, deprecated_rule=None, deprecated_for_removal=False, deprecated_reason=None, deprecated_since=None, scope_types=None)

Bases: RuleDefault

A class for holding policy-in-code policy objects definitions

This class provides the same functionality as the RuleDefault class, but it also requires additional data about the policy rule being registered. This is necessary so that proper documentation can be rendered based on the attributes of this class. Eventually, all usage of RuleDefault should be converted to use DocumentedRuleDefault.

Parameters:

operations

List of dicts containing each API URL and corresponding http request method.

Example:

operations=[{'path': '/foo', 'method': 'GET'},
            {'path': '/some', 'method': 'POST'}]

property description
property operations
exception oslo_policy.policy.DuplicatePolicyError(name)

Bases: Exception

class oslo_policy.policy.Enforcer(conf, policy_file=None, rules=None, default_rule=None, use_conf=True, overwrite=True, fallback_to_json_file=True)

Bases: object

Responsible for loading and enforcing rules.

Parameters:
  • conf – A configuration object.

  • policy_file – Custom policy file to use, if none is specified, conf.oslo_policy.policy_file will be used.

  • rules – Default dictionary / Rules to use. It will be considered just in the first instantiation. If load_rules() with force_reload=True, clear() or set_rules() with overwrite=True is called this will be overwritten.

  • default_rule – Default rule to use, conf.default_rule will be used if none is specified.

  • use_conf – Whether to load rules from cache or config file.

  • overwrite – Whether to overwrite existing rules when reload rules from config file.

authorize(rule, target, creds, do_raise=False, exc=None, *args, **kwargs)

A wrapper around ‘enforce’ that checks for policy registration.

To ensure that a policy being checked has been registered this method should be used rather than enforce. By doing so a project can be sure that all of it’s used policies are registered and therefore available for sample file generation.

The parameters match the enforce method and a description of them can be found there.

check_rules(raise_on_violation=False)

Look for rule definitions that are obviously incorrect.

clear()

Clears Enforcer contents.

This will clear this instances rules, policy’s cache, file cache and policy’s path.

enforce(rule, target, creds, do_raise=False, exc=None, *args, **kwargs)

Checks authorization of a rule against the target and credentials.

Parameters:
  • rule – The rule to evaluate as a string or BaseCheck.

  • target – As much information about the object being operated on as possible. The target argument should be a dict instance or an instance of a class that fully supports the Mapping abstract base class.

  • creds – As much information about the user performing the action as possible. This parameter can also be an instance of oslo_context.context.RequestContext.

  • do_raise – Whether to raise an exception or not if check fails.

  • exc – Class of the exception to raise if the check fails. Any remaining arguments passed to enforce() (both positional and keyword arguments) will be passed to the exception class. If not specified, PolicyNotAuthorized will be used.

Returns:

False if the policy does not allow the action and exc is not provided; otherwise, returns a value that evaluates to True. Note: for rules using the “case” expression, this True value will be the specified string from the expression.

load_rules(force_reload=False)

Loads policy_path’s rules.

Policy file is cached and will be reloaded if modified.

Parameters:

force_reload – Whether to reload rules from config file.

register_default(default)

Registers a RuleDefault.

Adds a RuleDefault to the list of registered rules. Rules must be registered before using the Enforcer.authorize method.

Parameters:

default – A RuleDefault object to register.

register_defaults(defaults)

Registers a list of RuleDefaults.

Adds each RuleDefault to the list of registered rules. Rules must be registered before using the Enforcer.authorize method.

Parameters:

default – A list of RuleDefault objects to register.

set_rules(rules, overwrite=True, use_conf=False)

Create a new Rules based on the provided dict of rules.

Parameters:
  • rules – New rules to use.

  • overwrite – Whether to overwrite current rules or update them with the new rules.

  • use_conf – Whether to reload rules from cache or config file.

exception oslo_policy.policy.InvalidContextObject(error)

Bases: Exception

exception oslo_policy.policy.InvalidDefinitionError(names)

Bases: Exception

exception oslo_policy.policy.InvalidRuleDefault(error)

Bases: Exception

exception oslo_policy.policy.InvalidScope(rule, operation_scopes, token_scope)

Bases: Exception

Raised when the scope of the request mismatches the policy scope.

class oslo_policy.policy.NotCheck(rule)

Bases: BaseCheck

class oslo_policy.policy.OrCheck(rules)

Bases: BaseCheck

add_check(rule)

Adds rule to be tested.

Allows addition of another rule to the list of rules that will be tested. Returns the OrCheck object for convenience.

pop_check()

Pops the last check from the list and returns them

Returns:

self, the popped check

Return type:

OrCheck, class:.Check

exception oslo_policy.policy.PolicyNotAuthorized(rule, target, creds)

Bases: Exception

Default exception raised for policy enforcement failure.

exception oslo_policy.policy.PolicyNotRegistered(name)

Bases: Exception

class oslo_policy.policy.RuleCheck(kind, match)

Bases: Check

class oslo_policy.policy.RuleDefault(name, check_str, description=None, deprecated_rule=None, deprecated_for_removal=False, deprecated_reason=None, deprecated_since=None, scope_types=None)

Bases: _BaseRule

A class for holding policy definitions.

It is required to supply a name and value at creation time. It is encouraged to also supply a description to assist operators.

Parameters:
  • name – The name of the policy. This is used when referencing it from another rule or during policy enforcement.

  • check_str – The policy. This is a string defining a policy that conforms to the policy language outlined at the top of the file.

  • description – A plain text description of the policy. This will be used to comment sample policy files for use by deployers.

  • deprecated_ruleDeprecatedRule

  • deprecated_for_removal – indicates whether the policy is planned for removal in a future release.

  • deprecated_reason – indicates why this policy is planned for removal in a future release. Silently ignored if deprecated_for_removal is False.

  • deprecated_since – indicates which release this policy was deprecated in. Accepts any string, though valid version strings are encouraged. Silently ignored if deprecated_for_removal is False.

  • scope_types – A list containing the intended scopes of the operation being done.

Changed in version 1.29: Added deprecated_rule parameter.

Changed in version 1.29: Added deprecated_for_removal parameter.

Changed in version 1.29: Added deprecated_reason parameter.

Changed in version 1.29: Added deprecated_since parameter.

Changed in version 1.31: Added scope_types parameter.

property deprecated_for_removal
property deprecated_reason
property deprecated_rule
property deprecated_since
property description
class oslo_policy.policy.Rules(rules=None, default_rule=None)

Bases: dict

A store for rules. Handles the default_rule setting directly.

classmethod from_dict(rules_dict, default_rule=None)

Allow loading of rule data from a dictionary.

classmethod load(data, default_rule=None)

Allow loading of YAML/JSON rule data.

Added in version 1.5.0.

classmethod load_json(data, default_rule=None)

Allow loading of YAML/JSON rule data.

Warning

This method is deprecated as of the 1.5.0 release in favor of load() and may be removed in the 2.0 release.

oslo_policy.policy.parse_file_contents(data)

Parse the raw contents of a policy file.

Parses the contents of a policy file which currently can be in either yaml or json format. Both can be parsed as yaml.

Parameters:

data – A string containing the contents of a policy file.

Returns:

A dict of the form {'policy_name1': 'policy1', 'policy_name2': 'policy2,...}

oslo_policy.policy.pick_default_policy_file(conf, fallback_to_json_file=True)
oslo_policy.policy.register(name, func=None)

Register a function or Check class as a policy check.

Parameters:
  • name – Gives the name of the check type, e.g., “rule”, “role”, etc. If name is None, a default check type will be registered.

  • func – If given, provides the function or class to register. If not given, returns a function taking one argument to specify the function or class to register, allowing use as a decorator.

oslo_policy.shell module

class oslo_policy.shell.FakeEnforcer(rules, config)

Bases: object

oslo_policy.shell.flatten(d, parent_key='')

Flatten a nested dictionary

Converts a dictionary with nested values to a single level flat dictionary, with dotted notation for each key.

oslo_policy.shell.main()
oslo_policy.shell.tool(policy_file, access_file, apply_rule, is_admin=False, target_file=None, enforcer_config=None)

oslo_policy.sphinxext module

Sphinx extension for pretty-formatting policy docs.

class oslo_policy.sphinxext.ShowPolicyDirective(name, arguments, options, content, lineno, content_offset, block_text, state, state_machine)

Bases: Directive

has_content = False

May the directive have content?

option_spec = {'config-file': <function unchanged>}

Mapping of option names to validator functions.

run()
oslo_policy.sphinxext.setup(app)

oslo_policy.sphinxpolicygen module

Generate a sample policy file.

oslo_policy.sphinxpolicygen.generate_sample(app)

Generate a sample policy file.

oslo_policy.sphinxpolicygen.setup(app)

oslo_policy.version module

Module contents