"Fossies" - the Fresh Open Source Software Archive  

Source code changes of the file "keystone/common/utils.py" between
keystone-16.0.1.tar.gz and keystone-17.0.0.tar.gz

About: OpenStack Keystone (Core Service: Identity) provides an authentication and authorization service for other OpenStack services. Provides a catalog of endpoints for all OpenStack services.
The "Ussuri" series (latest release).

utils.py  (keystone-16.0.1):utils.py  (keystone-17.0.0)
skipping to change at line 32 skipping to change at line 32
import itertools import itertools
import os import os
import pwd import pwd
import uuid import uuid
from oslo_log import log from oslo_log import log
from oslo_serialization import jsonutils from oslo_serialization import jsonutils
from oslo_utils import reflection from oslo_utils import reflection
from oslo_utils import strutils from oslo_utils import strutils
from oslo_utils import timeutils from oslo_utils import timeutils
import six import urllib
from six import moves
from keystone.common import password_hashing from keystone.common import password_hashing
import keystone.conf import keystone.conf
from keystone import exception from keystone import exception
from keystone.i18n import _ from keystone.i18n import _
CONF = keystone.conf.CONF CONF = keystone.conf.CONF
LOG = log.getLogger(__name__) LOG = log.getLogger(__name__)
WHITELISTED_PROPERTIES = [ WHITELISTED_PROPERTIES = [
'tenant_id', 'project_id', 'user_id', 'tenant_id', 'project_id', 'user_id',
skipping to change at line 66 skipping to change at line 65
hash_user_password = password_hashing.hash_user_password hash_user_password = password_hashing.hash_user_password
check_password = password_hashing.check_password check_password = password_hashing.check_password
def resource_uuid(value): def resource_uuid(value):
"""Convert input to valid UUID hex digits.""" """Convert input to valid UUID hex digits."""
try: try:
uuid.UUID(value) uuid.UUID(value)
return value return value
except ValueError: except ValueError:
if len(value) <= 64: if len(value) <= 64:
if six.PY2 and isinstance(value, six.text_type):
value = value.encode('utf-8')
return uuid.uuid5(RESOURCE_ID_NAMESPACE, value).hex return uuid.uuid5(RESOURCE_ID_NAMESPACE, value).hex
raise ValueError(_('Length of transformable resource id > 64, ' raise ValueError(_('Length of transformable resource id > 64, '
'which is max allowed characters')) 'which is max allowed characters'))
def flatten_dict(d, parent_key=''): def flatten_dict(d, parent_key=''):
"""Flatten a nested dictionary. """Flatten a nested dictionary.
Converts a dictionary with nested values to a single level flat Converts a dictionary with nested values to a single level flat
dictionary, with dotted notation for each key. dictionary, with dotted notation for each key.
skipping to change at line 98 skipping to change at line 95
class SmarterEncoder(jsonutils.json.JSONEncoder): class SmarterEncoder(jsonutils.json.JSONEncoder):
"""Help for JSON encoding dict-like objects.""" """Help for JSON encoding dict-like objects."""
def default(self, obj): def default(self, obj):
if not isinstance(obj, dict) and hasattr(obj, 'items'): if not isinstance(obj, dict) and hasattr(obj, 'items'):
return dict(obj.items()) return dict(obj.items())
return super(SmarterEncoder, self).default(obj) return super(SmarterEncoder, self).default(obj)
def hash_access_key(access): def hash_access_key(access):
hash_ = hashlib.sha256() hash_ = hashlib.sha256()
if not isinstance(access, six.binary_type): if not isinstance(access, bytes):
access = access.encode('utf-8') access = access.encode('utf-8')
hash_.update(access) hash_.update(access)
return hash_.hexdigest() return hash_.hexdigest()
def attr_as_boolean(val_attr): def attr_as_boolean(val_attr):
"""Return the boolean value, decoded from a string. """Return the boolean value, decoded from a string.
We test explicitly for a value meaning False, which can be one of We test explicitly for a value meaning False, which can be one of
several formats as specified in oslo strutils.FALSE_STRINGS. several formats as specified in oslo strutils.FALSE_STRINGS.
All other string values (including an empty string) are treated as All other string values (including an empty string) are treated as
skipping to change at line 131 skipping to change at line 128
This function takes two strings and compares them. It is intended to be This function takes two strings and compares them. It is intended to be
used when doing a comparison for authentication purposes to help guard used when doing a comparison for authentication purposes to help guard
against timing attacks. When using the function for this purpose, always against timing attacks. When using the function for this purpose, always
provide the user-provided password as the first argument. The time this provide the user-provided password as the first argument. The time this
function will take is always a factor of the length of this string. function will take is always a factor of the length of this string.
""" """
result = 0 result = 0
p_len = len(provided) p_len = len(provided)
k_len = len(known) k_len = len(known)
for i in moves.range(p_len): for i in range(p_len):
a = ord(provided[i]) if i < p_len else 0 a = ord(provided[i]) if i < p_len else 0
b = ord(known[i]) if i < k_len else 0 b = ord(known[i]) if i < k_len else 0
result |= a ^ b result |= a ^ b
return (p_len == k_len) & (result == 0) return (p_len == k_len) & (result == 0)
def setup_remote_pydev_debug(): def setup_remote_pydev_debug():
if CONF.pydev_debug_host and CONF.pydev_debug_port: if CONF.pydev_debug_host and CONF.pydev_debug_port:
try: try:
try: try:
from pydev import pydevd from pydev import pydevd
skipping to change at line 186 skipping to change at line 183
If the input is a valid type but no user is found a KeyError is If the input is a valid type but no user is found a KeyError is
raised. If the input is not a valid type a TypeError is raised. raised. If the input is not a valid type a TypeError is raised.
:param object user: string, int or None specifying the user to :param object user: string, int or None specifying the user to
lookup. lookup.
:returns: tuple of (uid, name) :returns: tuple of (uid, name)
""" """
if isinstance(user, six.string_types): if isinstance(user, str):
try: try:
user_info = pwd.getpwnam(user) user_info = pwd.getpwnam(user)
except KeyError: except KeyError:
try: try:
i = int(user) i = int(user)
except ValueError: except ValueError:
raise KeyError("user name '%s' not found" % user) raise KeyError("user name '%s' not found" % user)
try: try:
user_info = pwd.getpwuid(i) user_info = pwd.getpwuid(i)
except KeyError: except KeyError:
skipping to change at line 242 skipping to change at line 239
If the input is a valid type but no group is found a KeyError is If the input is a valid type but no group is found a KeyError is
raised. If the input is not a valid type a TypeError is raised. raised. If the input is not a valid type a TypeError is raised.
:param object group: string, int or None specifying the group to :param object group: string, int or None specifying the group to
lookup. lookup.
:returns: tuple of (gid, name) :returns: tuple of (gid, name)
""" """
if isinstance(group, six.string_types): if isinstance(group, str):
try: try:
group_info = grp.getgrnam(group) group_info = grp.getgrnam(group)
except KeyError: except KeyError:
# Was an int passed as a string? # Was an int passed as a string?
# Try converting to int and lookup by id instead. # Try converting to int and lookup by id instead.
try: try:
i = int(group) i = int(group)
except ValueError: except ValueError:
raise KeyError("group name '%s' not found" % group) raise KeyError("group name '%s' not found" % group)
try: try:
skipping to change at line 357 skipping to change at line 354
for i in name: for i in name:
if i in URL_RESERVED_CHARS: if i in URL_RESERVED_CHARS:
reserved_chars += i reserved_chars += i
return reserved_chars return reserved_chars
def lower_case_hostname(url): def lower_case_hostname(url):
"""Change the URL's hostname to lowercase.""" """Change the URL's hostname to lowercase."""
# NOTE(gyee): according to # NOTE(gyee): according to
# https://www.w3.org/TR/WD-html40-970708/htmlweb.html, the netloc portion # https://www.w3.org/TR/WD-html40-970708/htmlweb.html, the netloc portion
# of the URL is case-insensitive # of the URL is case-insensitive
parsed = moves.urllib.parse.urlparse(url) parsed = urllib.parse.urlparse(url)
# Note: _replace method for named tuples is public and defined in docs # Note: _replace method for named tuples is public and defined in docs
replaced = parsed._replace(netloc=parsed.netloc.lower()) replaced = parsed._replace(netloc=parsed.netloc.lower())
return moves.urllib.parse.urlunparse(replaced) return urllib.parse.urlunparse(replaced)
def remove_standard_port(url): def remove_standard_port(url):
# remove the default ports specified in RFC2616 and 2818 # remove the default ports specified in RFC2616 and 2818
o = moves.urllib.parse.urlparse(url) o = urllib.parse.urlparse(url)
separator = ':' separator = ':'
(host, separator, port) = o.netloc.partition(separator) (host, separator, port) = o.netloc.partition(separator)
if o.scheme.lower() == 'http' and port == '80': if o.scheme.lower() == 'http' and port == '80':
# NOTE(gyee): _replace() is not a private method. It has # NOTE(gyee): _replace() is not a private method. It has
# an underscore prefix to prevent conflict with field names. # an underscore prefix to prevent conflict with field names.
# See https://docs.python.org/2/library/collections.html# # See https://docs.python.org/2/library/collections.html#
# collections.namedtuple # collections.namedtuple
o = o._replace(netloc=host) o = o._replace(netloc=host)
if o.scheme.lower() == 'https' and port == '443': if o.scheme.lower() == 'https' and port == '443':
o = o._replace(netloc=host) o = o._replace(netloc=host)
return moves.urllib.parse.urlunparse(o) return urllib.parse.urlunparse(o)
def format_url(url, substitutions, silent_keyerror_failures=None): def format_url(url, substitutions, silent_keyerror_failures=None):
"""Format a user-defined URL with the given substitutions. """Format a user-defined URL with the given substitutions.
:param string url: the URL to be formatted :param string url: the URL to be formatted
:param dict substitutions: the dictionary used for substitution :param dict substitutions: the dictionary used for substitution
:param list silent_keyerror_failures: keys for which we should be silent :param list silent_keyerror_failures: keys for which we should be silent
if there is a KeyError exception on substitution attempt if there is a KeyError exception on substitution attempt
:returns: a formatted URL :returns: a formatted URL
 End of changes. 10 change blocks. 
12 lines changed or deleted 9 lines changed or added

Home  |  About  |  Features  |  All  |  Newest  |  Dox  |  Diffs  |  RSS Feeds  |  Screenshots  |  Comments  |  Imprint  |  Privacy  |  HTTP(S)