keystone.common package

Subpackages

Submodules

keystone.common.authorization module

keystone.common.context module

class keystone.common.context.RequestContext(**kwargs)[source]

Bases: oslo_context.context.RequestContext

to_policy_values()[source]

Add keystone-specific policy values to policy representation.

This method converts generic policy values to a dictionary form using the base implementation from oslo_context.context.RequestContext. Afterwards, it is going to pull keystone-specific values off the context and represent them as items in the policy values dictionary. This is because keystone uses default policies that rely on these values, so we need to guarantee they are present during policy enforcement if they are present on the context object.

This method is automatically called in oslo_policy.policy.Enforcer.enforce() if oslo.policy knows it’s dealing with a context object.

keystone.common.driver_hints module

class keystone.common.driver_hints.Hints[source]

Bases: object

Encapsulate driver hints for listing entities.

Hints are modifiers that affect the return of entities from a list_<entities> operation. They are typically passed to a driver to give direction as to what filtering, pagination or list limiting actions are being requested.

It is optional for a driver to action some or all of the list hints, but any filters that it does satisfy must be marked as such by calling removing the filter from the list.

A Hint object contains filters, which is a list of dicts that can be accessed publicly. Also it contains a dict called limit, which will indicate the amount of data we want to limit our listing to.

If the filter is discovered to never match, then cannot_match can be set to indicate that there will not be any matches and the backend work can be short-circuited.

Each filter term consists of:

  • name: the name of the attribute being matched

  • value: the value against which it is being matched

  • comparator: the operation, which can be one of equals,

    contains, startswith or endswith

  • case_sensitive: whether any comparison should take account of

    case

add_filter(name, value, comparator='equals', case_sensitive=False)[source]

Add a filter to the filters list, which is publicly accessible.

get_exact_filter_by_name(name)[source]

Return a filter key and value if exact filter exists for name.

set_limit(limit, truncated=False)[source]

Set a limit to indicate the list should be truncated.

keystone.common.driver_hints.truncated(f)[source]

Ensure list truncation is detected in Driver list entity methods.

This is designed to wrap Driver list_{entity} methods in order to calculate if the resultant list has been truncated. Provided a limit dict is found in the hints list, we increment the limit by one so as to ask the wrapped function for one more entity than the limit, and then once the list has been generated, we check to see if the original limit has been exceeded, in which case we truncate back to that limit and set the ‘truncated’ boolean to ‘true’ in the hints limit dict.

keystone.common.fernet_utils module

class keystone.common.fernet_utils.FernetUtils(key_repository=None, max_active_keys=None, config_group=None)[source]

Bases: object

create_key_directory(keystone_user_id=None, keystone_group_id=None)[source]

Attempt to create the key directory if it doesn’t exist.

initialize_key_repository(keystone_user_id=None, keystone_group_id=None)[source]

Create a key repository and bootstrap it with a key.

Parameters
  • keystone_user_id – User ID of the Keystone user.

  • keystone_group_id – Group ID of the Keystone user.

load_keys(use_null_key=False)[source]

Load keys from disk into a list.

The first key in the list is the primary key used for encryption. All other keys are active secondary keys that can be used for decrypting tokens.

Parameters

use_null_key – If true, a known key containing null bytes will be appended to the list of returned keys.

rotate_keys(keystone_user_id=None, keystone_group_id=None)[source]

Create a new primary key and revoke excess active keys.

Parameters
  • keystone_user_id – User ID of the Keystone user.

  • keystone_group_id – Group ID of the Keystone user.

Key rotation utilizes the following behaviors:

  • The highest key number is used as the primary key (used for encryption).

  • All keys can be used for decryption.

  • New keys are always created as key “0,” which serves as a placeholder before promoting it to be the primary key.

This strategy allows you to safely perform rotation on one node in a cluster, before syncing the results of the rotation to all other nodes (during both key rotation and synchronization, all nodes must recognize all primary keys).

validate_key_repository(requires_write=False)[source]

Validate permissions on the key repository directory.

keystone.common.json_home module

class keystone.common.json_home.JsonHomeResources[source]

Bases: object

JSON Home resource data.

classmethod append_resource(rel, data)[source]
classmethod resources()[source]
class keystone.common.json_home.Parameters[source]

Bases: object

Relationships for Common parameters.

ACCESS_RULE_ID = 'https://docs.openstack.org/api/openstack-identity/3/param/access_rule_id'
APPLICATION_CRED_ID = 'https://docs.openstack.org/api/openstack-identity/3/param/application_credential_id'
DOMAIN_ID = 'https://docs.openstack.org/api/openstack-identity/3/param/domain_id'
ENDPOINT_ID = 'https://docs.openstack.org/api/openstack-identity/3/param/endpoint_id'
GROUP_ID = 'https://docs.openstack.org/api/openstack-identity/3/param/group_id'
LIMIT_ID = 'https://docs.openstack.org/api/openstack-identity/3/param/limit_id'
POLICY_ID = 'https://docs.openstack.org/api/openstack-identity/3/param/policy_id'
PROJECT_ID = 'https://docs.openstack.org/api/openstack-identity/3/param/project_id'
REGION_ID = 'https://docs.openstack.org/api/openstack-identity/3/param/region_id'
REGISTERED_LIMIT_ID = 'https://docs.openstack.org/api/openstack-identity/3/param/registered_limit_id'
ROLE_ID = 'https://docs.openstack.org/api/openstack-identity/3/param/role_id'
SERVICE_ID = 'https://docs.openstack.org/api/openstack-identity/3/param/service_id'
TAG_VALUE = 'https://docs.openstack.org/api/openstack-identity/3/param/tag_value'
USER_ID = 'https://docs.openstack.org/api/openstack-identity/3/param/user_id'
class keystone.common.json_home.Status[source]

Bases: object

Status values supported.

DEPRECATED = 'deprecated'
EXPERIMENTAL = 'experimental'
STABLE = 'stable'
classmethod update_resource_data(resource_data, status)[source]
keystone.common.json_home.build_v3_extension_parameter_relation(extension_name, extension_version, parameter_name)[source]
keystone.common.json_home.build_v3_extension_resource_relation(extension_name, extension_version, resource_name)[source]
keystone.common.json_home.build_v3_parameter_relation(parameter_name)[source]
keystone.common.json_home.build_v3_resource_relation(resource_name)[source]
keystone.common.json_home.translate_urls(json_home, new_prefix)[source]

Given a JSON Home document, sticks new_prefix on each of the urls.

keystone.common.jwt_utils module

keystone.common.jwt_utils.create_jws_keypair(private_key_path, public_key_path)[source]

Create an ECDSA key pair using an secp256r1, or NIST P-256, curve.

Parameters
  • private_key_path – location to save the private key

  • public_key_path – location to save the public key

keystone.common.manager module

class keystone.common.manager.Manager(driver_name)[source]

Bases: object

Base class for intermediary request layer.

The Manager layer exists to support additional logic that applies to all or some of the methods exposed by a service that are not specific to the HTTP interface.

It also provides a stable entry point to dynamic backends.

An example of a probable use case is logging all the calls.

driver_namespace = None
keystone.common.manager.load_driver(namespace, driver_name, *args)[source]
keystone.common.manager.response_truncated(f)[source]

Truncate the list returned by the wrapped function.

This is designed to wrap Manager list_{entity} methods to ensure that any list limits that are defined are passed to the driver layer. If a hints list is provided, the wrapper will insert the relevant limit into the hints so that the underlying driver call can try and honor it. If the driver does truncate the response, it will update the ‘truncated’ attribute in the ‘limit’ entry in the hints list, which enables the caller of this function to know if truncation has taken place. If, however, the driver layer is unable to perform truncation, the ‘limit’ entry is simply left in the hints list for the caller to handle.

A _get_list_limit() method is required to be present in the object class hierarchy, which returns the limit for this backend to which we will truncate.

If a hints list is not provided in the arguments of the wrapped call then any limits set in the config file are ignored. This allows internal use of such wrapped methods where the entire data set is needed as input for the calculations of some other API (e.g. get role assignments for a given project).

keystone.common.password_hashing module

keystone.common.password_hashing.check_password(password, hashed)[source]

Check that a plaintext password matches hashed.

hashpw returns the salt value concatenated with the actual hash value. It extracts the actual salt if this value is then passed as the salt.

keystone.common.password_hashing.hash_password(password)[source]

Hash a password. Harder.

keystone.common.password_hashing.hash_user_password(user)[source]

Hash a user dict’s password without modifying the passed-in dict.

keystone.common.password_hashing.verify_length_and_trunc_password(password)[source]

Verify and truncate the provided password to the max_password_length.

keystone.common.profiler module

keystone.common.profiler.setup(name, host='0.0.0.0')[source]

Setup OSprofiler notifier and enable profiling.

Parameters
  • name – name of the service that will be profiled

  • host – hostname or host IP address that the service will be running on. By default host will be set to 0.0.0.0, but more specified host name / address usage is highly recommended.

keystone.common.provider_api module

exception keystone.common.provider_api.DuplicateProviderError[source]

Bases: Exception

Attempting to register a duplicate API provider.

class keystone.common.provider_api.ProviderAPIMixin[source]

Bases: object

Allow referencing provider apis on self via __getattr__.

Be sure this class is first in the class definition for inheritance.

class keystone.common.provider_api.ProviderAPIRegistry[source]

Bases: object

deferred_provider_lookup(api, method)[source]

Create descriptor that performs lookup of api and method on demand.

For specialized cases, such as the enforcer “get_member_from_driver” which needs to be effectively a “classmethod”, this method returns a smart descriptor object that does the lookup at runtime instead of at import time.

Parameters
  • api (str) – The api to use, e.g. “identity_api”

  • method (str) – the method on the api to return

lock_provider_registry()[source]
locked = False

keystone.common.render_token module

keystone.common.render_token.render_token_response_from_model(token, include_catalog=True)[source]

keystone.common.tokenless_auth module

class keystone.common.tokenless_auth.TokenlessAuthHelper(env)[source]

Bases: keystone.common.provider_api.ProviderAPIMixin, object

get_mapped_user(project_id=None, domain_id=None)[source]

Map client certificate to an existing user.

If user is ephemeral, there is no validation on the user himself; however it will be mapped to a corresponding group(s) and the scope of this ephemeral user is the same as what is assigned to the group.

Parameters
  • project_id – Project scope of the mapped user.

  • domain_id – Domain scope of the mapped user.

Returns

A dictionary that contains the keys, such as user_id, user_name, domain_id, domain_name

Return type

dict

get_scope()[source]

keystone.common.utils module

class keystone.common.utils.SmarterEncoder(*, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, default=None)[source]

Bases: json.encoder.JSONEncoder

Help for JSON encoding dict-like objects.

default(obj)[source]

Implement this method in a subclass such that it returns a serializable object for o, or calls the base implementation (to raise a TypeError).

For example, to support arbitrary iterators, you could implement default like this:

def default(self, o):
    try:
        iterable = iter(o)
    except TypeError:
        pass
    else:
        return list(iterable)
    # Let the base class default method raise the TypeError
    return JSONEncoder.default(self, o)
class keystone.common.utils.WhiteListedItemFilter(whitelist, data)[source]

Bases: object

keystone.common.utils.attr_as_boolean(val_attr)[source]

Return the boolean value, decoded from a string.

We test explicitly for a value meaning False, which can be one of several formats as specified in oslo strutils.FALSE_STRINGS. All other string values (including an empty string) are treated as meaning True.

keystone.common.utils.auth_str_equal(provided, known)[source]

Constant-time string comparison.

Params provided

the first string

Params known

the second string

Returns

True if the strings are equal.

This function takes two strings and compares them. It is intended to be used when doing a comparison for authentication purposes to help guard against timing attacks. When using the function for this purpose, always 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.

keystone.common.utils.check_endpoint_url(url)[source]

Check substitution of url.

The invalid urls are as follows: urls with substitutions that is not in the whitelist

Check the substitutions in the URL to make sure they are valid and on the whitelist.

Parameters

url (str) – the URL to validate

Return type

None

Raises

keystone.exception.URLValidationError – if the URL is invalid

keystone.common.utils.create_directory(directory, keystone_user_id=None, keystone_group_id=None)[source]

Attempt to create a directory if it doesn’t exist.

Parameters
  • directory – string containing the path of the directory to create.

  • keystone_user_id – the system ID of the process running keystone.

  • keystone_group_id – the system ID of the group running keystone.

keystone.common.utils.flatten_dict(d, parent_key='')[source]

Flatten a nested dictionary.

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

keystone.common.utils.format_url(url, substitutions, silent_keyerror_failures=None)[source]

Format a user-defined URL with the given substitutions.

Parameters
  • url (string) – the URL to be formatted

  • substitutions (dict) – the dictionary used for substitution

  • silent_keyerror_failures (list) – keys for which we should be silent if there is a KeyError exception on substitution attempt

Returns

a formatted URL

keystone.common.utils.get_unix_group(group=None)[source]

Get the gid and group name.

This is a convenience utility which accepts a variety of input which might represent a unix group. If successful it returns the gid and name. Valid input is:

string

A string is first considered to be a group name and a lookup is attempted under that name. If no name is found then an attempt is made to convert the string to an integer and perform a lookup as a gid.

int

An integer is interpreted as a gid.

None

None is interpreted to mean use the current process’s effective group.

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.

Parameters

group (object) – string, int or None specifying the group to lookup.

Returns

tuple of (gid, name)

keystone.common.utils.get_unix_user(user=None)[source]

Get the uid and user name.

This is a convenience utility which accepts a variety of input which might represent a unix user. If successful it returns the uid and name. Valid input is:

string

A string is first considered to be a user name and a lookup is attempted under that name. If no name is found then an attempt is made to convert the string to an integer and perform a lookup as a uid.

int

An integer is interpreted as a uid.

None

None is interpreted to mean use the current process’s effective user.

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.

Parameters

user (object) – string, int or None specifying the user to lookup.

Returns

tuple of (uid, name)

keystone.common.utils.hash_access_key(access)[source]
keystone.common.utils.is_not_url_safe(name)[source]

Check if a string contains any url reserved characters.

keystone.common.utils.isotime(at=None, subsecond=False)[source]

Stringify time in ISO 8601 format.

Python provides a similar instance method for datetime.datetime objects called isoformat(). The format of the strings generated by isoformat() has a couple of problems:

1) The strings generated by isotime() are used in tokens and other public APIs that we can’t change without a deprecation period. The strings generated by isoformat() are not the same format, so we can’t just change to it.

2) The strings generated by isoformat() do not include the microseconds if the value happens to be 0. This will likely show up as random failures as parsers may be written to always expect microseconds, and it will parse correctly most of the time.

Parameters
  • at (datetime.datetime) – Optional datetime object to return at a string. If not provided, the time when the function was called will be used.

  • subsecond (bool) – If true, the returned string will represent microsecond precision, but only precise to the second. For example, a datetime.datetime(2016, 9, 14, 14, 1, 13, 970223) will be returned as 2016-09-14T14:01:13.000000Z.

Returns

A time string represented in ISO 8601 format.

Return type

str

keystone.common.utils.list_url_unsafe_chars(name)[source]

Return a list of the reserved characters.

keystone.common.utils.lower_case_hostname(url)[source]

Change the URL’s hostname to lowercase.

keystone.common.utils.parse_expiration_date(expiration_date)[source]
keystone.common.utils.remove_standard_port(url)[source]
keystone.common.utils.resource_uuid(value)[source]

Convert input to valid UUID hex digits.

keystone.common.utils.setup_remote_pydev_debug()[source]

Module contents