trivial: Tweak docstrings

There's no functional changes here other than moving the initializer
documentation for the 'DeprecatedRule' from the '__init__' docstring to
the class' docstring. This allows us to remove '__init__' entirely since
it was just calling the superclass.

Change-Id: I7437cf00b2ba5c02926dc8c2435e237ef730f2b1
Signed-off-by: Stephen Finucane <sfinucan@redhat.com>
This commit is contained in:
Stephen Finucane 2021-02-23 13:10:16 +00:00
parent 45249db86e
commit d8534850d9

View File

@ -391,8 +391,8 @@ def parse_file_contents(data):
yaml or json format. Both can be parsed as yaml. yaml or json format. Both can be parsed as yaml.
:param data: A string containing the contents of a policy file. :param data: A string containing the contents of a policy file.
:returns: A dict of the form {'policy_name1': 'policy1', :returns: A dict of the form ``{'policy_name1': 'policy1',
'policy_name2': 'policy2,...} 'policy_name2': 'policy2,...}``
""" """
try: try:
# NOTE(snikitin): jsonutils.loads() is much faster than # NOTE(snikitin): jsonutils.loads() is much faster than
@ -438,7 +438,6 @@ class Rules(dict):
.. warning:: .. warning::
This method is deprecated as of the 1.5.0 release in favor of This method is deprecated as of the 1.5.0 release in favor of
:meth:`load` and may be removed in the 2.0 release. :meth:`load` and may be removed in the 2.0 release.
""" """
warnings.warn( warnings.warn(
'The load_json() method is deprecated as of the 1.5.0 release in ' 'The load_json() method is deprecated as of the 1.5.0 release in '
@ -502,24 +501,24 @@ class Enforcer(object):
"""Responsible for loading and enforcing rules. """Responsible for loading and enforcing rules.
:param conf: A configuration object. :param conf: A configuration object.
:param policy_file: Custom policy file to use, if none is :param policy_file: Custom policy file to use, if none is specified,
specified, ``conf.oslo_policy.policy_file`` will be ``conf.oslo_policy.policy_file`` will be used.
used. :param rules: Default dictionary / Rules to use. It will be considered just
:param rules: Default dictionary / Rules to use. It will be in the first instantiation. If :meth:`load_rules` with
considered just in the first instantiation. If ``force_reload=True``, :meth:`clear` or :meth:`set_rules` with
:meth:`load_rules` with ``force_reload=True``, ``overwrite=True`` is called this will be overwritten.
:meth:`clear` or :meth:`set_rules` with ``overwrite=True`` :param default_rule: Default rule to use, conf.default_rule will be used if
is called this will be overwritten. none is specified.
:param default_rule: Default rule to use, conf.default_rule will
be used if none is specified.
:param use_conf: Whether to load rules from cache or config file. :param use_conf: Whether to load rules from cache or config file.
:param overwrite: Whether to overwrite existing rules when reload rules :param overwrite: Whether to overwrite existing rules when reload rules
from config file. from config file.
""" """
def __init__(self, conf, policy_file=None, rules=None, def __init__(
self, conf, policy_file=None, rules=None,
default_rule=None, use_conf=True, overwrite=True, default_rule=None, use_conf=True, overwrite=True,
fallback_to_json_file=True): fallback_to_json_file=True,
):
self.conf = conf self.conf = conf
opts._register(conf) opts._register(conf)
@ -552,7 +551,7 @@ class Enforcer(object):
def set_rules(self, rules, overwrite=True, use_conf=False): def set_rules(self, rules, overwrite=True, use_conf=False):
"""Create a new :class:`Rules` based on the provided dict of rules. """Create a new :class:`Rules` based on the provided dict of rules.
:param dict rules: New rules to use. :param rules: New rules to use.
:param overwrite: Whether to overwrite current rules or update them :param overwrite: Whether to overwrite current rules or update them
with the new rules. with the new rules.
:param use_conf: Whether to reload rules from cache or config file. :param use_conf: Whether to reload rules from cache or config file.
@ -729,8 +728,10 @@ class Enforcer(object):
# renamed to foo:create_bar then they need to be able to see that # renamed to foo:create_bar then they need to be able to see that
# before they roll out the next release. If the policy name is in # before they roll out the next release. If the policy name is in
# self.file_rules, we know that it's being overridden. # self.file_rules, we know that it's being overridden.
if deprecated_rule.name != default.name and ( if (
deprecated_rule.name in self.file_rules): deprecated_rule.name != default.name and
deprecated_rule.name in self.file_rules
):
if not self.suppress_deprecation_warnings: if not self.suppress_deprecation_warnings:
warnings.warn(deprecated_msg) warnings.warn(deprecated_msg)
@ -742,11 +743,12 @@ class Enforcer(object):
# we set the deprecated rule name to reference the new rule. If we # we set the deprecated rule name to reference the new rule. If we
# see that the deprecated override rule is just the new rule, then # see that the deprecated override rule is just the new rule, then
# we shouldn't mess with it. # we shouldn't mess with it.
if (self.file_rules[deprecated_rule.name].check file_rule = self.file_rules[deprecated_rule.name]
!= _parser.parse_rule(deprecated_rule.check_str) and if (
str(self.file_rules[deprecated_rule.name].check) file_rule.check != deprecated_rule.check and
!= 'rule:%s' % default.name): str(file_rule.check) != 'rule:%s' % default.name and
if default.name not in self.file_rules.keys(): default.name not in self.file_rules.keys()
):
return self.file_rules[deprecated_rule.name].check return self.file_rules[deprecated_rule.name].check
# In this case, the default check string is changing. We need to let # In this case, the default check string is changing. We need to let
@ -761,11 +763,15 @@ class Enforcer(object):
# support the new policy. # support the new policy.
# If the enforce_new_defaults flag is True, do not add OrCheck to the # If the enforce_new_defaults flag is True, do not add OrCheck to the
# old check_str and enforce only the new defaults. # old check_str and enforce only the new defaults.
if (not self.conf.oslo_policy.enforce_new_defaults if (
not self.conf.oslo_policy.enforce_new_defaults
and deprecated_rule.check_str != default.check_str and deprecated_rule.check_str != default.check_str
and default.name not in self.file_rules): and default.name not in self.file_rules
if not (self.suppress_deprecation_warnings ):
or self.suppress_default_change_warnings): if not (
self.suppress_deprecation_warnings
or self.suppress_default_change_warnings
):
warnings.warn(deprecated_msg) warnings.warn(deprecated_msg)
return OrCheck([default.check, deprecated_rule.check]) return OrCheck([default.check, deprecated_rule.check])
@ -773,7 +779,7 @@ class Enforcer(object):
return default.check return default.check
def _undefined_check(self, check): def _undefined_check(self, check):
'''Check if a RuleCheck references an undefined rule.''' """Check if a RuleCheck references an undefined rule."""
if isinstance(check, RuleCheck): if isinstance(check, RuleCheck):
if check.match not in self.rules: if check.match not in self.rules:
# Undefined rule # Undefined rule
@ -789,12 +795,16 @@ class Enforcer(object):
return False return False
def _cycle_check(self, check, seen=None): def _cycle_check(self, check, seen=None):
'''Check if RuleChecks cycle. """Check if RuleChecks cycle.
Looking for something like::
Looking for something like:
"foo": "rule:bar" "foo": "rule:bar"
"bar": "rule:foo" "bar": "rule:foo"
'''
:param check: The check to search for.
:param seen: A set of previously seen rules, else None.
"""
if seen is None: if seen is None:
seen = set() seen = set()
@ -884,11 +894,10 @@ class Enforcer(object):
def _load_policy_file(self, path, force_reload, overwrite=True): def _load_policy_file(self, path, force_reload, overwrite=True):
"""Load policy rules from the specified policy file. """Load policy rules from the specified policy file.
:param str path: A path of the policy file to load rules from. :param path: A path of the policy file to load rules from.
:param bool force_reload: Forcefully reload the policy file content. :param force_reload: Forcefully reload the policy file content.
:param bool overwrite: Replace policy rules instead of updating them. :param overwrite: Replace policy rules instead of updating them.
:return: A bool indicating whether rules have been changed or not. :return: A bool indicating whether rules have been changed or not.
:rtype: bool
""" """
rules_changed = False rules_changed = False
reloaded, data = _cache_handler.read_cached_file( reloaded, data = _cache_handler.read_cached_file(
@ -906,14 +915,12 @@ class Enforcer(object):
"""Locate the policy YAML/JSON data file/path. """Locate the policy YAML/JSON data file/path.
:param path: It's value can be a full path or related path. When :param path: It's value can be a full path or related path. When
full path specified, this function just returns the full full path specified, this function just returns the full path. When
path. When related path specified, this function will related path specified, this function will search configuration
search configuration directories to find one that exists. directories to find one that exists.
:returns: The policy path :returns: The policy path
:raises: ConfigFilesNotFoundError if the file/path couldn't be located.
:raises: ConfigFilesNotFoundError if the file/path couldn't
be located.
""" """
policy_path = self.conf.find_file(path) policy_path = self.conf.find_file(path)
@ -922,35 +929,30 @@ class Enforcer(object):
raise cfg.ConfigFilesNotFoundError((path,)) raise cfg.ConfigFilesNotFoundError((path,))
def enforce(self, rule, target, creds, do_raise=False, exc=None, def enforce(
*args, **kwargs): self, rule, target, creds, do_raise=False, exc=None, *args, **kwargs,
):
"""Checks authorization of a rule against the target and credentials. """Checks authorization of a rule against the target and credentials.
:param rule: The rule to evaluate. :param rule: The rule to evaluate as a string or :class:`BaseCheck`.
:type rule: string or :class:`BaseCheck` :param target: As much information about the object being operated on
:param dict target: As much information about the object being as possible. The target argument should be a dict instance or an
operated on as possible. The target instance of a class that fully supports the Mapping abstract base
argument should be a dict instance or an class.
instance of a class that fully supports :param creds: As much information about the user performing the action
the Mapping abstract base class. as possible. This parameter can also be an instance of
:param dict creds: As much information about the user performing the ``oslo_context.context.RequestContext``.
action as possible. This parameter can also be an
instance of ``oslo_context.context.RequestContext``.
:param do_raise: Whether to raise an exception or not if check :param do_raise: Whether to raise an exception or not if check
fails. fails.
:param exc: Class of the exception to raise if the check fails. :param exc: Class of the exception to raise if the check fails.
Any remaining arguments passed to :meth:`enforce` (both Any remaining arguments passed to :meth:`enforce` (both positional
positional and keyword arguments) will be passed to and keyword arguments) will be passed to the exception class. If
the exception class. If not specified, not specified, :class:`PolicyNotAuthorized` will be used.
:class:`PolicyNotAuthorized` will be used. :return: ``False`` if the policy does not allow the action and ``exc``
is not provided; otherwise, returns a value that evaluates to
:return: ``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``. Note: for rules using the "case" expression, this
``True`` value will be the specified string from the ``True`` value will be the specified string from the expression.
expression.
""" """
self.load_rules() self.load_rules()
if isinstance(creds, context.RequestContext): if isinstance(creds, context.RequestContext):
@ -1131,8 +1133,8 @@ class Enforcer(object):
""" """
if rule not in self.registered_rules: if rule not in self.registered_rules:
raise PolicyNotRegistered(rule) raise PolicyNotRegistered(rule)
return self.enforce(rule, target, creds, do_raise, exc, return self.enforce(
*args, **kwargs) rule, target, creds, do_raise, exc, *args, **kwargs)
class _BaseRule: class _BaseRule: