OpenStack Identity (Keystone) Client
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

base.py 10KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  1. # Licensed under the Apache License, Version 2.0 (the "License"); you may
  2. # not use this file except in compliance with the License. You may obtain
  3. # a copy of the License at
  4. #
  5. # http://www.apache.org/licenses/LICENSE-2.0
  6. #
  7. # Unless required by applicable law or agreed to in writing, software
  8. # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  9. # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  10. # License for the specific language governing permissions and limitations
  11. # under the License.
  12. import abc
  13. import logging
  14. from oslo_config import cfg
  15. from oslo_serialization import jsonutils
  16. import six
  17. from keystoneclient import access
  18. from keystoneclient.auth.identity import base
  19. from keystoneclient import exceptions
  20. from keystoneclient.i18n import _
  21. _logger = logging.getLogger(__name__)
  22. __all__ = ('Auth', 'AuthMethod', 'AuthConstructor', 'BaseAuth')
  23. @six.add_metaclass(abc.ABCMeta)
  24. class BaseAuth(base.BaseIdentityPlugin):
  25. """Identity V3 Authentication Plugin.
  26. :param string auth_url: Identity service endpoint for authentication.
  27. :param List auth_methods: A collection of methods to authenticate with.
  28. :param string trust_id: Trust ID for trust scoping.
  29. :param string domain_id: Domain ID for domain scoping.
  30. :param string domain_name: Domain name for domain scoping.
  31. :param string project_id: Project ID for project scoping.
  32. :param string project_name: Project name for project scoping.
  33. :param string project_domain_id: Project's domain ID for project.
  34. :param string project_domain_name: Project's domain name for project.
  35. :param bool reauthenticate: Allow fetching a new token if the current one
  36. is going to expire. (optional) default True
  37. :param bool include_catalog: Include the service catalog in the returned
  38. token. (optional) default True.
  39. """
  40. def __init__(self, auth_url,
  41. trust_id=None,
  42. domain_id=None,
  43. domain_name=None,
  44. project_id=None,
  45. project_name=None,
  46. project_domain_id=None,
  47. project_domain_name=None,
  48. reauthenticate=True,
  49. include_catalog=True):
  50. super(BaseAuth, self).__init__(auth_url=auth_url,
  51. reauthenticate=reauthenticate)
  52. self._trust_id = trust_id
  53. self.domain_id = domain_id
  54. self.domain_name = domain_name
  55. self.project_id = project_id
  56. self.project_name = project_name
  57. self.project_domain_id = project_domain_id
  58. self.project_domain_name = project_domain_name
  59. self.include_catalog = include_catalog
  60. @property
  61. def trust_id(self):
  62. # Override to remove deprecation.
  63. return self._trust_id
  64. @trust_id.setter
  65. def trust_id(self, value):
  66. # Override to remove deprecation.
  67. self._trust_id = value
  68. @property
  69. def token_url(self):
  70. """The full URL where we will send authentication data."""
  71. return '%s/auth/tokens' % self.auth_url.rstrip('/')
  72. @abc.abstractmethod
  73. def get_auth_ref(self, session, **kwargs):
  74. return None # pragma: no cover
  75. @classmethod
  76. def get_options(cls):
  77. options = super(BaseAuth, cls).get_options()
  78. options.extend([
  79. cfg.StrOpt('domain-id', help='Domain ID to scope to'),
  80. cfg.StrOpt('domain-name', help='Domain name to scope to'),
  81. cfg.StrOpt('project-id', help='Project ID to scope to'),
  82. cfg.StrOpt('project-name', help='Project name to scope to'),
  83. cfg.StrOpt('project-domain-id',
  84. help='Domain ID containing project'),
  85. cfg.StrOpt('project-domain-name',
  86. help='Domain name containing project'),
  87. cfg.StrOpt('trust-id', help='Trust ID'),
  88. ])
  89. return options
  90. class Auth(BaseAuth):
  91. """Identity V3 Authentication Plugin.
  92. :param string auth_url: Identity service endpoint for authentication.
  93. :param List auth_methods: A collection of methods to authenticate with.
  94. :param string trust_id: Trust ID for trust scoping.
  95. :param string domain_id: Domain ID for domain scoping.
  96. :param string domain_name: Domain name for domain scoping.
  97. :param string project_id: Project ID for project scoping.
  98. :param string project_name: Project name for project scoping.
  99. :param string project_domain_id: Project's domain ID for project.
  100. :param string project_domain_name: Project's domain name for project.
  101. :param bool reauthenticate: Allow fetching a new token if the current one
  102. is going to expire. (optional) default True
  103. :param bool include_catalog: Include the service catalog in the returned
  104. token. (optional) default True.
  105. :param bool unscoped: Force the return of an unscoped token. This will make
  106. the keystone server return an unscoped token even if
  107. a default_project_id is set for this user.
  108. """
  109. def __init__(self, auth_url, auth_methods, **kwargs):
  110. self.unscoped = kwargs.pop('unscoped', False)
  111. super(Auth, self).__init__(auth_url=auth_url, **kwargs)
  112. self.auth_methods = auth_methods
  113. def get_auth_ref(self, session, **kwargs):
  114. headers = {'Accept': 'application/json'}
  115. body = {'auth': {'identity': {}}}
  116. ident = body['auth']['identity']
  117. rkwargs = {}
  118. for method in self.auth_methods:
  119. name, auth_data = method.get_auth_data(session,
  120. self,
  121. headers,
  122. request_kwargs=rkwargs)
  123. ident.setdefault('methods', []).append(name)
  124. ident[name] = auth_data
  125. if not ident:
  126. raise exceptions.AuthorizationFailure(
  127. _('Authentication method required (e.g. password)'))
  128. mutual_exclusion = [bool(self.domain_id or self.domain_name),
  129. bool(self.project_id or self.project_name),
  130. bool(self.trust_id),
  131. bool(self.unscoped)]
  132. if sum(mutual_exclusion) > 1:
  133. raise exceptions.AuthorizationFailure(
  134. _('Authentication cannot be scoped to multiple targets. Pick '
  135. 'one of: project, domain, trust or unscoped'))
  136. if self.domain_id:
  137. body['auth']['scope'] = {'domain': {'id': self.domain_id}}
  138. elif self.domain_name:
  139. body['auth']['scope'] = {'domain': {'name': self.domain_name}}
  140. elif self.project_id:
  141. body['auth']['scope'] = {'project': {'id': self.project_id}}
  142. elif self.project_name:
  143. scope = body['auth']['scope'] = {'project': {}}
  144. scope['project']['name'] = self.project_name
  145. if self.project_domain_id:
  146. scope['project']['domain'] = {'id': self.project_domain_id}
  147. elif self.project_domain_name:
  148. scope['project']['domain'] = {'name': self.project_domain_name}
  149. elif self.trust_id:
  150. body['auth']['scope'] = {'OS-TRUST:trust': {'id': self.trust_id}}
  151. elif self.unscoped:
  152. body['auth']['scope'] = {'unscoped': {}}
  153. # NOTE(jamielennox): we add nocatalog here rather than in token_url
  154. # directly as some federation plugins require the base token_url
  155. token_url = self.token_url
  156. if not self.include_catalog:
  157. token_url += '?nocatalog'
  158. _logger.debug('Making authentication request to %s', token_url)
  159. resp = session.post(token_url, json=body, headers=headers,
  160. authenticated=False, log=False, **rkwargs)
  161. try:
  162. _logger.debug(jsonutils.dumps(resp.json()))
  163. resp_data = resp.json()['token']
  164. except (KeyError, ValueError):
  165. raise exceptions.InvalidResponse(response=resp)
  166. return access.AccessInfoV3(resp.headers['X-Subject-Token'],
  167. **resp_data)
  168. @six.add_metaclass(abc.ABCMeta)
  169. class AuthMethod(object):
  170. """One part of a V3 Authentication strategy.
  171. V3 Tokens allow multiple methods to be presented when authentication
  172. against the server. Each one of these methods is implemented by an
  173. AuthMethod.
  174. Note: When implementing an AuthMethod use the method_parameters
  175. and do not use positional arguments. Otherwise they can't be picked up by
  176. the factory method and don't work as well with AuthConstructors.
  177. """
  178. _method_parameters = []
  179. def __init__(self, **kwargs):
  180. for param in self._method_parameters:
  181. setattr(self, param, kwargs.pop(param, None))
  182. if kwargs:
  183. msg = _("Unexpected Attributes: %s") % ", ".join(kwargs)
  184. raise AttributeError(msg)
  185. @classmethod
  186. def _extract_kwargs(cls, kwargs):
  187. """Remove parameters related to this method from other kwargs."""
  188. return dict([(p, kwargs.pop(p, None))
  189. for p in cls._method_parameters])
  190. @abc.abstractmethod
  191. def get_auth_data(self, session, auth, headers, **kwargs):
  192. """Return the authentication section of an auth plugin.
  193. :param session: The communication session.
  194. :type session: keystoneclient.session.Session
  195. :param base.Auth auth: The auth plugin calling the method.
  196. :param dict headers: The headers that will be sent with the auth
  197. request if a plugin needs to add to them.
  198. :return: The identifier of this plugin and a dict of authentication
  199. data for the auth type.
  200. :rtype: tuple(string, dict)
  201. """
  202. pass # pragma: no cover
  203. @six.add_metaclass(abc.ABCMeta)
  204. class AuthConstructor(Auth):
  205. """Abstract base class for creating an Auth Plugin.
  206. The Auth Plugin created contains only one authentication method. This
  207. is generally the required usage.
  208. An AuthConstructor creates an AuthMethod based on the method's
  209. arguments and the auth_method_class defined by the plugin. It then
  210. creates the auth plugin with only that authentication method.
  211. """
  212. _auth_method_class = None
  213. def __init__(self, auth_url, *args, **kwargs):
  214. method_kwargs = self._auth_method_class._extract_kwargs(kwargs)
  215. method = self._auth_method_class(*args, **method_kwargs)
  216. super(AuthConstructor, self).__init__(auth_url, [method], **kwargs)