keystone.common package

keystone.common package

Subpackages

Submodules

keystone.common.authorization module

keystone.common.authorization.AUTH_CONTEXT_ENV = 'KEYSTONE_AUTH_CONTEXT'

Environment variable used to convey the Keystone auth context.

Auth context is essentially the user credential used for policy enforcement. It is a dictionary with the following attributes:

  • token: Token from the request
  • user_id: user ID of the principal
  • user_domain_id (optional): Domain ID of the principal if the principal
    has a domain.
  • project_id (optional): project ID of the scoped project if auth is
    project-scoped
  • project_domain_id (optional): Domain ID of the scoped project if auth is
    project-scoped.
  • domain_id (optional): domain ID of the scoped domain if auth is
    domain-scoped
  • domain_name (optional): domain name of the scoped domain if auth is
    domain-scoped
  • is_delegated_auth: True if this is delegated (via trust or oauth)
  • trust_id: Trust ID if trust-scoped, or None
  • trustor_id: Trustor ID if trust-scoped, or None
  • trustee_id: Trustee ID if trust-scoped, or None
  • consumer_id: OAuth consumer ID, or None
  • access_token_id: OAuth access token ID, or None
  • roles (optional): list of role names for the given scope
  • group_ids (optional): list of group IDs for which the API user has
    membership if token was for a federated user
keystone.common.authorization.assert_admin(app, request)[source]

Ensure the user is an admin.

Raises:
keystone.common.authorization.check_policy(controller, request, action, filter_attr=None, input_attr=None, target_attr=None, *args, **kwargs)[source]
keystone.common.authorization.check_protection(controller, request, prep_info, target_attr=None, *args, **kwargs)[source]

Provide call protection for complex target attributes.

As well as including the standard parameters from the original API call (which is passed in prep_info), this call will add in any additional entities or attributes (passed in target_attr), so that they can be referenced by policy rules.

keystone.common.authorization.get_token_ref(context)[source]

Retrieve KeystoneToken object from the auth context and returns it.

Parameters:context (dict) – The request context.
Raises:keystone.exception.Unauthorized – If auth context cannot be found.
Returns:The KeystoneToken object.
keystone.common.authorization.token_to_auth_context(token)[source]
keystone.common.authorization.token_validation_window(request)[source]

keystone.common.clean module

keystone.common.clean.check_enabled(property_name, enabled)[source]
keystone.common.clean.check_length(property_name, value, min_length=1, max_length=64)[source]
keystone.common.clean.check_name(property_name, name, min_length=1, max_length=64)[source]
keystone.common.clean.check_type(property_name, value, expected_type, display_expected_type)[source]
keystone.common.clean.domain_enabled(enabled)[source]
keystone.common.clean.domain_name(name)[source]
keystone.common.clean.group_name(name)[source]
keystone.common.clean.project_enabled(enabled)[source]
keystone.common.clean.project_name(name)[source]
keystone.common.clean.user_enabled(enabled)[source]
keystone.common.clean.user_name(name)[source]

keystone.common.context module

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

Bases: oslo_context.context.RequestContext

classmethod from_environ(environ, **kwargs)[source]

keystone.common.controller module

class keystone.common.controller.V2Controller(*args, **kwargs)[source]

Bases: keystone.common.wsgi.Application

Base controller class for Identity API v2.

static filter_domain(ref)[source]

Remove domain since v2 calls are not domain-aware.

static filter_domain_id(ref)[source]

Remove domain_id since v2 calls are not domain-aware.

static filter_is_domain(ref)[source]

Remove is_domain field since v2 calls are not domain-aware.

static filter_project_parent_id(ref)[source]

Remove parent_id since v2 calls are not hierarchy-aware.

format_project_list(tenant_refs, **kwargs)[source]

Format a v2 style project list, including marker/limits.

static normalize_username_in_request(ref)[source]

Add name in incoming user refs to match the v2 spec.

Internally we use name to represent a user’s name. The v2 spec requires the use of username instead.

static normalize_username_in_response(ref)[source]

Add username to outgoing user refs to match the v2 spec.

Internally we use name to represent a user’s name. The v2 spec requires the use of username instead.

static v3_to_v2_project(ref)[source]

Convert a project_ref from v3 to v2.

  • v2.0 projects are not domain aware, and should have domain_id removed
  • v2.0 projects are not hierarchy aware, and should have parent_id removed

This method should only be applied to project_refs being returned from the v2.0 controller(s).

If ref is a list type, we will iterate through each element and do the conversion.

static v3_to_v2_user(ref)[source]

Convert a user_ref from v3 to v2 compatible.

  • v2.0 users are not domain aware, and should have domain_id removed
  • v2.0 users expect the use of tenantId instead of default_project_id
  • v2.0 users have a username attribute
  • v2.0 remove password_expires_at

If ref is a list type, we will iterate through each element and do the conversion.

class keystone.common.controller.V3Controller(*args, **kwargs)[source]

Bases: keystone.common.wsgi.Application

Base controller class for Identity API v3.

Child classes should set the collection_name and member_name class attributes, representing the collection of entities they are exposing to the API. This is required for supporting self-referential links, pagination, etc.

Class parameters:

  • _public_parameters - set of parameters that are exposed to the user.
    Usually used by cls.filter_params()
classmethod base_url(context, path=None)[source]
classmethod build_driver_hints(request, supported_filters)[source]

Build list hints based on the context query string.

Parameters:
  • request – the current request
  • supported_filters – list of filters supported, so ignore any keys in query_dict that are not in this list.
check_protection(request, prep_info, target_attr=None)[source]

Provide call protection for complex target attributes.

As well as including the standard parameters from the original API call (which is passed in prep_info), this call will add in any additional entities or attributes (passed in target_attr), so that they can be referenced by policy rules.

collection_name = 'entities'
classmethod filter_by_attributes(refs, hints)[source]

Filter a list of references by filter values.

static filter_domain_id(ref)[source]

Override v2 filter to let domain_id out for v3 calls.

classmethod filter_params(ref)[source]

Remove unspecified parameters from the dictionary.

This function removes unspecified parameters from the dictionary. This method checks only root-level keys from a ref dictionary.

Parameters:ref – a dictionary representing deserialized response to be serialized
classmethod full_url(context, path=None)[source]
get_member_from_driver = None
classmethod limit(refs, hints)[source]

Limit a list of entities.

The underlying driver layer may have already truncated the collection for us, but in case it was unable to handle truncation we check here.

Parameters:
  • refs – the list of members of the collection
  • hints – hints, containing, among other things, the limit requested
Returns:

boolean indicating whether the list was truncated, as well as the list of (truncated if necessary) entities.

member_name = 'entity'
classmethod query_filter_is_true(filter_value)[source]

Determine if bool query param is ‘True’.

We treat this the same way as we do for policy enforcement:

{bool_param}=0 is treated as False

Any other value is considered to be equivalent to True, including the absence of a value

classmethod wrap_collection(context, refs, hints=None)[source]

Wrap a collection, checking for filtering and pagination.

Returns the wrapped collection, which includes: - Executing any filtering not already carried out - Truncate to a set limit if necessary - Adds ‘self’ links in every member - Adds ‘next’, ‘self’ and ‘prev’ links for the whole collection.

Parameters:
  • context – the current context, containing the original url path and query string
  • refs – the list of members of the collection
  • hints – list hints, containing any relevant filters and limit. Any filters already satisfied by managers will have been removed
classmethod wrap_member(context, ref)[source]
keystone.common.controller.filterprotected(*filters, **callback)[source]

Wrap API list calls with role based access controls (RBAC).

This handles both the protection of the API parameters as well as any filters supplied.

More complex API list calls (for example that need to examine the contents of an entity referenced by one of the filters) should pass in a callback function, that will be subsequently called to check protection for these multiple entities. This callback function should gather the appropriate entities needed and then call check_protection() in the V3Controller class.

keystone.common.controller.protected(callback=None)[source]

Wrap API calls with role based access controls (RBAC).

This handles both the protection of the API parameters as well as any target entities for single-entity API calls.

More complex API calls (for example that deal with several different entities) should pass in a callback function, that will be subsequently called to check protection for these multiple entities. This callback function should gather the appropriate entities needed and then call check_protection() in the V3Controller class.

keystone.common.controller.protected_wrapper(self, f, check_function, request, filter_attr, *args, **kwargs)[source]
keystone.common.controller.v2_auth_deprecated(f)[source]
keystone.common.controller.v2_deprecated(f)[source]
keystone.common.controller.v2_ec2_deprecated(f)[source]

keystone.common.dependency module

This module provides support for dependency injection.

Providers are registered via the @provider() decorator, and dependencies on them are registered with @requires(). Providers are available to their consumers via an attribute. See the documentation for the individual functions for more detail.

See also:

exception keystone.common.dependency.UnresolvableDependencyException(name, targets)[source]

Bases: exceptions.Exception

Raised when a required dependency is not resolvable.

See resolve_future_dependencies() for more details.

keystone.common.dependency.get_provider(name, optional=<object object>)[source]
keystone.common.dependency.provider(name)[source]

A class decorator used to register providers.

When @provider() is used to decorate a class, members of that class will register themselves as providers for the named dependency. As an example, In the code fragment:

@dependency.provider('foo_api')
class Foo:
    def __init__(self):
        ...

    ...

foo = Foo()

The object foo will be registered as a provider for foo_api. No more than one such instance should be created; additional instances will replace the previous ones, possibly resulting in different instances being used by different consumers.

keystone.common.dependency.requires(*dependencies)[source]

A class decorator used to inject providers into consumers.

The required providers will be made available to instances of the decorated class via an attribute with the same name as the provider. For example, in the code fragment:

@dependency.requires('foo_api', 'bar_api')
class FooBarClient:
    def __init__(self):
        ...

    ...

client = FooBarClient()

The object client will have attributes named foo_api and bar_api, which are instances of the named providers.

Objects must not rely on the existence of these attributes until after resolve_future_dependencies() has been called; they may not exist beforehand.

Dependencies registered via @required() must have providers; if not, an UnresolvableDependencyException will be raised when resolve_future_dependencies() is called.

keystone.common.dependency.reset()[source]

Reset the registry of providers.

This is useful for unit testing to ensure that tests don’t use providers from previous tests.

keystone.common.dependency.resolve_future_dependencies(__provider_name=None)[source]

Force injection of all dependencies.

Before this function is called, circular dependencies may not have been injected. This function should be called only once, after all global providers are registered. If an object needs to be created after this call, it must not have circular dependencies.

If any required dependencies are unresolvable, this function will raise an UnresolvableDependencyException.

Outside of this module, this function should be called with no arguments; the optional argument, __provider_name is used internally, and should be treated as an implementation detail.

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.extension module

keystone.common.extension.register_admin_extension(url_prefix, extension_data)[source]

Register extension with collection of admin extensions.

Extensions register the information here that will show up in the /extensions page as a way to indicate that the extension is active.

url_prefix: unique key for the extension that will appear in the
urls generated by the extension.
extension_data is a dictionary. The expected fields are:
‘name’: short, human readable name of the extension ‘namespace’: xml namespace ‘alias’: identifier for the extension ‘updated’: date the extension was last updated ‘description’: text description of the extension ‘links’: hyperlinks to documents describing the extension
keystone.common.extension.register_public_extension(url_prefix, extension_data)[source]

Same as register_admin_extension but for public extensions.

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.Parameters[source]

Bases: object

Relationships for Common parameters.

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'
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'
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'
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.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_password_compat(password)[source]
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.policy module

keystone.common.policy.enforce(credentials, action, target, do_raise=True)[source]

Verify that the action is valid on the target in this context.

Parameters:
  • credentials – user credentials
  • action – string representing the action to be checked, which should be colon separated for clarity.
  • target – dictionary representing the object of the action for object creation this should be a dictionary representing the location of the object e.g. {‘project_id’: object.project_id}
Raises:

keystone.exception.Forbidden – If verification fails.

Actions should be colon separated for clarity. For example:

  • identity:list_users
keystone.common.policy.get_enforcer()[source]
keystone.common.policy.init()[source]
keystone.common.policy.register_rules(enforcer)[source]
keystone.common.policy.reset()[source]

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.request module

class keystone.common.request.Request(environ, charset=None, unicode_errors=None, decode_param_names=None, **kw)[source]

Bases: webob.request.Request

assert_authenticated()[source]

Ensure that the current request has been authenticated.

audit_initiator

A pyCADF initiator describing the current authenticated context.

auth_context
auth_type

Gets and sets the AUTH_TYPE key in the environment.

context

Gets and sets the keystone.oslo_request_context key in the environment.

context_dict
remote_domain

Gets and sets the REMOTE_DOMAIN key in the environment.

token_auth

Gets and sets the keystone.token_auth key in the environment.

keystone.common.resource_options module

Options specific to resources managed by Keystone (Domain, User, etc).

class keystone.common.resource_options.ResourceOption(option_id, option_name, validator=<function _validator>, json_schema_validation=None)[source]

Bases: object

json_schema
option_id
option_name
class keystone.common.resource_options.ResourceOptionRegistry(registry_name)[source]

Bases: object

get_option_by_id(opt_id)[source]
get_option_by_name(name)[source]
json_schema
option_ids
option_names
options
options_by_name
register_option(option)[source]
keystone.common.resource_options.boolean_validator(value)[source]
keystone.common.resource_options.ref_mapper_to_dict_options(ref)[source]

Convert the values in _resource_option_mapper to options dict.

NOTE: this is to be called from the relevant to_dict methods or
similar and must be called from within the active session context.
Parameters:ref – the DB model ref to extract options from
Returns:Dict of options as expected to be returned out of to_dict in the options key.
keystone.common.resource_options.resource_options_ref_to_mapper(ref, option_class)[source]

Convert the _resource_options property-dict to options attr map.

The model must have the resource option mapper located in the _resource_option_mapper attribute.

The model must have the resource option registry located in the resource_options_registry attribute.

The option dict with key(opt_id), value(opt_value) will be pulled from ref._resource_options.

NOTE: This function MUST be called within the active writer session
context!
Parameters:
  • ref – The DB model reference that is actually stored to the backend.
  • option_class – Class that is used to store the resource option in the DB.

keystone.common.router module

class keystone.common.router.Router(controller, collection_key, key, resource_descriptions=None, is_entity_implemented=True, method_template=None)[source]

Bases: keystone.common.wsgi.ComposableRouter

add_routes(mapper)[source]

keystone.common.tokenless_auth module

class keystone.common.tokenless_auth.TokenlessAuthHelper(*args, **kwargs)[source]

Bases: 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, encoding='utf-8', default=None)[source]

Bases: json.encoder.JSONEncoder

Help for JSON encoding dict-like objects.

default(obj)[source]
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.convert_ec2_to_v3_credential(ec2credential)[source]
keystone.common.utils.convert_v3_to_ec2_credential(credential)[source]
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_blob_from_credential(credential)[source]
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.make_dirs(path, mode=None, user=None, group=None, log=None)[source]

Assure directory exists, set ownership and permissions.

Assure the directory exists and optionally set its ownership and permissions.

Each of the mode, user and group are optional, if None then that aspect is not modified.

Owner and group may be specified either with a symbolic name or numeric id.

Parameters:
  • path (string) – Pathname of directory whose existence is assured.
  • mode (object) – ownership permissions flags (int) i.e. chmod, if None do not set.
  • user (object) – set user, name (string) or uid (integer), if None do not set.
  • group (object) – set group, name (string) or gid (integer) if None do not set.
  • log (logger) – logging.logger object, used to emit log messages, if None no logging is performed.
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.set_permissions(path, mode=None, user=None, group=None, log=None)[source]

Set the ownership and permissions on the pathname.

Each of the mode, user and group are optional, if None then that aspect is not modified.

Owner and group may be specified either with a symbolic name or numeric id.

Parameters:
  • path (string) – Pathname of directory whose existence is assured.
  • mode (object) – ownership permissions flags (int) i.e. chmod, if None do not set.
  • user (object) – set user, name (string) or uid (integer), if None do not set.
  • group (object) – set group, name (string) or gid (integer) if None do not set.
  • log (logger) – logging.logger object, used to emit log messages, if None no logging is performed.
keystone.common.utils.setup_remote_pydev_debug()[source]
keystone.common.utils.unixtime(dt_obj)[source]

Format datetime object as unix timestamp.

Parameters:dt_obj – datetime.datetime object
Returns:float

keystone.common.wsgi module

Utility methods for working with WSGI servers.

class keystone.common.wsgi.Application(*args, **kwargs)[source]

Bases: keystone.common.wsgi.BaseApplication

assert_admin(request)[source]

Ensure the user is an admin.

Raises:
classmethod base_url(context, endpoint_type)[source]
class keystone.common.wsgi.BaseApplication[source]

Bases: object

Base WSGI application wrapper. Subclasses need to implement __call__.

classmethod factory(global_config, **local_config)[source]

Used for paste app factories in paste.deploy config files.

Any local configuration (that is, values under the [app:APPNAME] section of the paste config) will be passed into the __init__ method as kwargs.

A hypothetical configuration would look like:

[app:wadl] latest_version = 1.3 paste.app_factory = keystone.fancy_api:Wadl.factory

which would result in a call to the Wadl class as

import keystone.fancy_api keystone.fancy_api.Wadl(latest_version=‘1.3’)

You could of course re-implement the factory method in subclasses, but using the kwarg passing it shouldn’t be necessary.

class keystone.common.wsgi.ComposableRouter(mapper=None)[source]

Bases: keystone.common.wsgi.Router

Router that supports use by ComposingRouter.

add_routes(mapper)[source]

Add routes to given mapper.

class keystone.common.wsgi.ComposingRouter(mapper=None, routers=None)[source]

Bases: keystone.common.wsgi.Router

class keystone.common.wsgi.Debug(application)[source]

Bases: keystone.common.wsgi.Middleware

Helper class for debugging a WSGI application.

Can be inserted into any WSGI application chain to get information about the request and response.

static print_generator(app_iter)[source]

Iterator that prints the contents of a wrapper string.

class keystone.common.wsgi.ExtensionRouter(application, mapper=None)[source]

Bases: keystone.common.wsgi.Router

A router that allows extensions to supplement or overwrite routes.

Expects to be subclassed.

add_routes(mapper)[source]
classmethod factory(global_config, **local_config)[source]

Used for paste app factories in paste.deploy config files.

Any local configuration (that is, values under the [filter:APPNAME] section of the paste config) will be passed into the __init__ method as kwargs.

A hypothetical configuration would look like:

[filter:analytics] redis_host = 127.0.0.1 paste.filter_factory = keystone.analytics:Analytics.factory

which would result in a call to the Analytics class as

import keystone.analytics keystone.analytics.Analytics(app, redis_host=‘127.0.0.1’)

You could of course re-implement the factory method in subclasses, but using the kwarg passing it shouldn’t be necessary.

class keystone.common.wsgi.Middleware(application)[source]

Bases: keystone.common.wsgi.Application

Base WSGI middleware.

These classes require an application to be initialized that will be called next. By default the middleware will simply call its wrapped app, or you can override __call__ to customize its behavior.

classmethod factory(global_config)[source]

Used for paste app factories in paste.deploy config files.

process_request(request)[source]

Called on each request.

If this returns None, the next application down the stack will be executed. If it returns a response then that response will be returned and execution will stop here.

process_response(request, response)[source]

Do whatever you’d like to the response, based on the request.

class keystone.common.wsgi.Router(mapper)[source]

Bases: object

WSGI middleware that maps incoming requests to WSGI apps.

class keystone.common.wsgi.RoutersBase[source]

Bases: object

Base class for Routers.

append_v3_routers(mapper, routers)[source]

Append v3 routers.

Subclasses should override this method to map its routes.

Use self._add_resource() to map routes for a resource.

class keystone.common.wsgi.V3ExtensionRouter(application, mapper=None)[source]

Bases: keystone.common.wsgi.ExtensionRouter, keystone.common.wsgi.RoutersBase

Base class for V3 extension router.

keystone.common.wsgi.best_match_language(req)[source]

Determine the best available locale.

This returns best available locale based on the Accept-Language HTTP header passed in the request.

keystone.common.wsgi.middleware_exceptions(method)[source]
keystone.common.wsgi.render_exception(error, context=None, request=None, user_locale=None)[source]

Form a WSGI response based on the current error.

keystone.common.wsgi.render_response(body=None, status=None, headers=None, method=None)[source]

Form a WSGI response.

keystone.common.wsgi.validate_token_bind(context, token_ref)[source]

Module contents

Creative Commons Attribution 3.0 License

Except where otherwise noted, this document is licensed under Creative Commons Attribution 3.0 License. See all OpenStack Legal Documents.