keystone.common package¶
Subpackages¶
- keystone.common.cache package
- keystone.common.environment package
- keystone.common.kvs package
- keystone.common.ldap package
- keystone.common.sql package
- Subpackages
- keystone.common.sql.migrate_repo package
- Subpackages
- keystone.common.sql.migrate_repo.versions package
- Submodules
- keystone.common.sql.migrate_repo.versions.067_kilo module
- keystone.common.sql.migrate_repo.versions.068_placeholder module
- keystone.common.sql.migrate_repo.versions.069_placeholder module
- keystone.common.sql.migrate_repo.versions.070_placeholder module
- keystone.common.sql.migrate_repo.versions.071_placeholder module
- keystone.common.sql.migrate_repo.versions.072_placeholder module
- keystone.common.sql.migrate_repo.versions.073_insert_assignment_inherited_pk module
- keystone.common.sql.migrate_repo.versions.074_add_is_domain_project module
- keystone.common.sql.migrate_repo.versions.075_confirm_config_registration module
- keystone.common.sql.migrate_repo.versions.076_placeholder module
- keystone.common.sql.migrate_repo.versions.077_placeholder module
- keystone.common.sql.migrate_repo.versions.078_placeholder module
- keystone.common.sql.migrate_repo.versions.079_placeholder module
- keystone.common.sql.migrate_repo.versions.080_placeholder module
- keystone.common.sql.migrate_repo.versions.081_add_endpoint_policy_table module
- keystone.common.sql.migrate_repo.versions.082_add_federation_tables module
- keystone.common.sql.migrate_repo.versions.083_add_oauth1_tables module
- keystone.common.sql.migrate_repo.versions.084_add_revoke_tables module
- keystone.common.sql.migrate_repo.versions.085_add_endpoint_filtering_table module
- keystone.common.sql.migrate_repo.versions.086_add_duplicate_constraint_trusts module
- keystone.common.sql.migrate_repo.versions.087_implied_roles module
- keystone.common.sql.migrate_repo.versions.088_domain_specific_roles module
- keystone.common.sql.migrate_repo.versions.089_add_root_of_all_domains module
- keystone.common.sql.migrate_repo.versions.090_add_local_user_and_password_tables module
- keystone.common.sql.migrate_repo.versions.091_migrate_data_to_local_user_and_password_tables module
- keystone.common.sql.migrate_repo.versions.092_make_implied_roles_fks_cascaded module
- keystone.common.sql.migrate_repo.versions.093_migrate_domains_to_projects module
- keystone.common.sql.migrate_repo.versions.094_add_federated_user_table module
- keystone.common.sql.migrate_repo.versions.095_add_integer_pkey_to_revocation_event_table module
- keystone.common.sql.migrate_repo.versions.096_drop_role_name_constraint module
- keystone.common.sql.migrate_repo.versions.097_drop_user_name_domainid_constraint module
- Module contents
- keystone.common.sql.migrate_repo.versions package
- Submodules
- keystone.common.sql.migrate_repo.manage module
- Module contents
- Subpackages
- keystone.common.sql.migrate_repo package
- Submodules
- keystone.common.sql.core module
- keystone.common.sql.migration_helpers module
- Module contents
- Subpackages
- keystone.common.validation package
Submodules¶
keystone.common.authorization module¶
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 requestuser_id
: user ID of the principaluser_domain_id
(optional): Domain ID of the principal if the principalhas a domain.
project_id
(optional): project ID of the scoped project if auth isproject-scoped
project_domain_id
(optional): Domain ID of the scoped project if auth isproject-scoped.
domain_id
(optional): domain ID of the scoped domain if auth isdomain-scoped
domain_name
(optional): domain name of the scoped domain if auth isdomain-scoped
is_delegated_auth
: True if this is delegated (via trust or oauth)trust_id
: Trust ID if trust-scoped, or Nonetrustor_id
: Trustor ID if trust-scoped, or Nonetrustee_id
: Trustee ID if trust-scoped, or Noneconsumer_id
: OAuth consumer ID, or Noneaccess_token_id
: OAuth access token ID, or Noneroles
(optional): list of role names for the given scopegroup_ids
(optional): list of group IDs for which the API user hasmembership if token was for a federated user
keystone.common.clean module¶
keystone.common.config module¶
-
keystone.common.config.
find_paste_config
()[source]¶ Find Keystone’s paste.deploy configuration file.
Keystone’s paste.deploy configuration file is specified in the
[paste_deploy]
section of the main Keystone configuration file,keystone.conf
.For example:
[paste_deploy] config_file = keystone-paste.ini
Returns: The selected configuration filename Raises: exception.ConfigFileNotFound
-
keystone.common.config.
list_opts
()[source]¶ Return a list of oslo_config options available in Keystone.
The returned list includes all oslo_config options which are registered as the “FILE_OPTIONS” in keystone.common.config. This list will not include the options from the oslo-incubator library or any options registered dynamically at run time.
Each object in the list is a two element tuple. The first element of each tuple is the name of the group under which the list of options 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_config.opts’ entry point under the ‘keystone.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
-
keystone.common.config.
set_config_defaults
()[source]¶ Override all configuration default values for keystone.
-
keystone.common.config.
set_default_for_default_log_levels
()[source]¶ Set the default for the default_log_levels option for keystone.
Keystone uses some packages that other OpenStack services don’t use that do logging. This will set the default_log_levels default level for those packages.
This function needs to be called before CONF().
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_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]¶ Adds 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]¶ Adds 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
If ref is a list type, we will iterate through each element and do the conversion.
-
static
-
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
andmember_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
build_driver_hints
(context, supported_filters)[source]¶ Build list hints based on the context query string.
Parameters: - context – contains the query_string from which any list hints can be extracted
- supported_filters – list of filters supported, so ignore any keys in query_dict that are not in this list.
-
check_protection
(context, 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]¶ Filters a list of references by filter values.
-
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
-
get_member_from_driver
= None¶
-
classmethod
limit
(refs, hints)[source]¶ Limits 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
-
keystone.common.controller.
filterprotected
(*filters, **callback)[source]¶ Wraps 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]¶ Wraps 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.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.
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 forfoo_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 namedfoo_api
andbar_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, anUnresolvableDependencyException
will be raised whenresolve_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]¶ Forces 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 matchedvalue
: the value against which it is being matchedcomparator
: the operation, which can be one ofequals
,contains
,startswith
orendswith
case_sensitive
: whether any comparison should take account ofcase
type
: will always be ‘filter’
-
add_filter
(name, value, comparator='equals', case_sensitive=False)[source]¶ Adds a filter to the filters list, which is publicly accessible.
-
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.json_home module¶
-
class
keystone.common.json_home.
Parameters
[source]¶ Bases:
object
Relationships for Common parameters.
-
DOMAIN_ID
= 'http://docs.openstack.org/api/openstack-identity/3/param/domain_id'¶
-
ENDPOINT_ID
= 'http://docs.openstack.org/api/openstack-identity/3/param/endpoint_id'¶
-
GROUP_ID
= 'http://docs.openstack.org/api/openstack-identity/3/param/group_id'¶
-
POLICY_ID
= 'http://docs.openstack.org/api/openstack-identity/3/param/policy_id'¶
-
PROJECT_ID
= 'http://docs.openstack.org/api/openstack-identity/3/param/project_id'¶
-
REGION_ID
= 'http://docs.openstack.org/api/openstack-identity/3/param/region_id'¶
-
ROLE_ID
= 'http://docs.openstack.org/api/openstack-identity/3/param/role_id'¶
-
SERVICE_ID
= 'http://docs.openstack.org/api/openstack-identity/3/param/service_id'¶
-
USER_ID
= 'http://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'¶
-
-
keystone.common.json_home.
build_v3_extension_parameter_relation
(extension_name, extension_version, parameter_name)[source]¶
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.
create_legacy_driver
(driver_class)[source]¶ Helper function to deprecate the original driver classes.
The keystone.{subsystem}.Driver classes are deprecated in favor of the new versioned classes. This function creates a new class based on a versioned class and adds a deprecation message when it is used.
This will allow existing custom drivers to work when the Driver class is renamed to include a version.
Example usage:
Driver = create_legacy_driver(CatalogDriverV8)
-
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.models module¶
Base model for keystone internal services
Unless marked otherwise, all fields are strings.
-
class
keystone.common.models.
Domain
[source]¶ Bases:
keystone.common.models.Model
Domain object.
- Required keys:
- id name
Optional keys:
description enabled (bool, default True)-
optional_keys
= ('description', 'enabled')¶
-
required_keys
= ('id', 'name')¶
-
class
keystone.common.models.
Endpoint
[source]¶ Bases:
keystone.common.models.Model
Endpoint object
- Required keys:
- id region service_id
- Optional keys:
- internalurl publicurl adminurl
-
optional_keys
= ('internalurl', 'publicurl', 'adminurl')¶
-
required_keys
= ('id', 'region', 'service_id')¶
-
class
keystone.common.models.
Group
[source]¶ Bases:
keystone.common.models.Model
Group object.
- Required keys:
- id name domain_id
Optional keys:
description-
optional_keys
= ('description',)¶
-
required_keys
= ('id', 'name', 'domain_id')¶
-
class
keystone.common.models.
ImpliedRole
[source]¶ Bases:
keystone.common.models.Model
ImpliedRole object.
- Required keys:
- prior_role_id implied_role_id
-
optional_keys
= ()¶
-
required_keys
= ('prior_role_id', 'implied_role_id')¶
-
class
keystone.common.models.
Project
[source]¶ Bases:
keystone.common.models.Model
Project object.
- Required keys:
- id name domain_id
- Optional Keys:
- description enabled (bool, default True) is_domain (bool, default False)
-
optional_keys
= ('description', 'enabled', 'is_domain')¶
-
required_keys
= ('id', 'name', 'domain_id')¶
-
class
keystone.common.models.
Role
[source]¶ Bases:
keystone.common.models.Model
Role object.
- Required keys:
- id name
-
optional_keys
= ()¶
-
required_keys
= ('id', 'name')¶
-
class
keystone.common.models.
Service
[source]¶ Bases:
keystone.common.models.Model
Service object.
- Required keys:
- id type name
Optional keys:
-
optional_keys
= ()¶
-
required_keys
= ('id', 'type', 'name')¶
-
class
keystone.common.models.
Token
[source]¶ Bases:
keystone.common.models.Model
Token object.
- Required keys:
- id expires (datetime)
- Optional keys:
- user tenant metadata trust_id
-
optional_keys
= ('extra',)¶
-
required_keys
= ('id', 'expires')¶
-
class
keystone.common.models.
Trust
[source]¶ Bases:
keystone.common.models.Model
Trust object.
- Required keys:
- id trustor_user_id trustee_user_id project_id
-
optional_keys
= ('expires_at',)¶
-
required_keys
= ('id', 'trustor_user_id', 'trustee_user_id', 'project_id')¶
-
class
keystone.common.models.
User
[source]¶ Bases:
keystone.common.models.Model
User object.
- Required keys:
- id name domain_id
- Optional keys:
- password description email enabled (bool, default True) default_project_id
-
optional_keys
= ('password', 'description', 'email', 'enabled', 'default_project_id')¶
-
required_keys
= ('id', 'name', 'domain_id')¶
keystone.common.openssl module¶
-
class
keystone.common.openssl.
BaseCertificateConfigure
(conf_obj, server_conf_obj, keystone_user, keystone_group, rebuild, **kwargs)[source]¶ Bases:
object
Create a certificate signing environment.
This is based on a config section and reasonable OpenSSL defaults.
-
sslconfig
= '\n# OpenSSL configuration file.\n#\n\n# Establish working directory.\n\ndir = %(conf_dir)s\n\n[ ca ]\ndefault_ca = CA_default\n\n[ CA_default ]\nnew_certs_dir = $dir\nserial = $dir/serial\ndatabase = $dir/index.txt\ndefault_days = 365\ndefault_md = %(default_md)s\npreserve = no\nemail_in_dn = no\nnameopt = default_ca\ncertopt = default_ca\npolicy = policy_anything\nx509_extensions = usr_cert\nunique_subject = no\n\n[ policy_anything ]\ncountryName = optional\nstateOrProvinceName = optional\norganizationName = optional\norganizationalUnitName = optional\ncommonName = supplied\nemailAddress = optional\n\n[ req ]\ndefault_bits = 2048 # Size of keys\ndefault_keyfile = key.pem # name of generated keys\nstring_mask = utf8only # permitted characters\ndistinguished_name = req_distinguished_name\nreq_extensions = v3_req\nx509_extensions = v3_ca\n\n[ req_distinguished_name ]\ncountryName = Country Name (2 letter code)\ncountryName_min = 2\ncountryName_max = 2\nstateOrProvinceName = State or Province Name (full name)\nlocalityName = Locality Name (city, district)\n0.organizationName = Organization Name (company)\norganizationalUnitName = Organizational Unit Name (department, division)\ncommonName = Common Name (hostname, IP, or your name)\ncommonName_max = 64\nemailAddress = Email Address\nemailAddress_max = 64\n\n[ v3_ca ]\nbasicConstraints = CA:TRUE\nsubjectKeyIdentifier = hash\nauthorityKeyIdentifier = keyid:always,issuer\n\n[ v3_req ]\nbasicConstraints = CA:FALSE\nkeyUsage = nonRepudiation, digitalSignature, keyEncipherment\n\n[ usr_cert ]\nbasicConstraints = CA:FALSE\nsubjectKeyIdentifier = hash\nauthorityKeyIdentifier = keyid:always\n'¶
-
-
class
keystone.common.openssl.
ConfigurePKI
(keystone_user, keystone_group, rebuild=False)[source]¶ Bases:
keystone.common.openssl.BaseCertificateConfigure
Generate files for PKI signing using OpenSSL.
Signed tokens require a private key and signing certificate which itself must be signed by a CA. This class generates them with workable defaults if each of the files are not present
-
class
keystone.common.openssl.
ConfigureSSL
(keystone_user, keystone_group, rebuild=False)[source]¶ Bases:
keystone.common.openssl.BaseCertificateConfigure
Generate files for HTTPS using OpenSSL.
Creates a public/private key and certificates. If a CA is not given one will be generated using provided arguments.
keystone.common.router module¶
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
-
keystone.common.utils module¶
-
class
keystone.common.utils.
PKIEncoder
(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:
keystone.common.utils.SmarterEncoder
Special encoder to make token JSON a bit shorter.
-
item_separator
= ','¶
-
key_separator
= ':'¶
-
-
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.
-
keystone.common.utils.
attr_as_boolean
(val_attr)[source]¶ Returns 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_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.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.
get_token_ref
(context)[source]¶ Retrieves 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.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_user_password
(user)[source]¶ Hash a user dict’s password without modifying the passed-in dict.
-
keystone.common.utils.
is_not_url_safe
(name)[source]¶ Check if a string contains any url reserved characters.
-
keystone.common.utils.
list_url_unsafe_chars
(name)[source]¶ Return a list of the reserved characters.
-
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.
read_cached_file
(filename, cache_info, reload_func=None)[source]¶ Read from a file if it has been modified.
Parameters: - cache_info – dictionary to hold opaque cache.
- reload_func – optional function to be called with data when file is reloaded due to a modification.
Returns: data from file.
-
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.wsgi module¶
Utility methods for working with WSGI servers.
-
class
keystone.common.wsgi.
Application
(*args, **kwargs)[source]¶ Bases:
keystone.common.wsgi.BaseApplication
-
assert_admin
(context)[source]¶ Ensure the user is an admin.
Raises: - keystone.exception.Unauthorized – if a token could not be found/authorized, a user is invalid, or a tenant is invalid/not scoped.
- keystone.exception.Forbidden – if the user is not an admin and does not have the admin role
-
-
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.factorywhich 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.
-
classmethod
-
class
keystone.common.wsgi.
ComposableRouter
(mapper=None)[source]¶ Bases:
keystone.common.wsgi.Router
Router that supports use by ComposingRouter.
-
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.
-
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.
-
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.factorywhich 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.
-
classmethod
-
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.
-
classmethod
-
class
keystone.common.wsgi.
Router
(mapper)[source]¶ Bases:
object
WSGI middleware that maps incoming requests to WSGI apps.
-
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]¶ Determines the best available locale.
This returns best available locale based on the Accept-Language HTTP header passed in the request.
-
keystone.common.wsgi.
render_exception
(error, context=None, request=None, user_locale=None)[source]¶ Forms a WSGI response based on the current error.