credentials.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  1. # Copyright 2016 Google LLC
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. """Interfaces for credentials."""
  15. import abc
  16. import os
  17. import six
  18. from google.auth import _helpers, environment_vars
  19. @six.add_metaclass(abc.ABCMeta)
  20. class Credentials(object):
  21. """Base class for all credentials.
  22. All credentials have a :attr:`token` that is used for authentication and
  23. may also optionally set an :attr:`expiry` to indicate when the token will
  24. no longer be valid.
  25. Most credentials will be :attr:`invalid` until :meth:`refresh` is called.
  26. Credentials can do this automatically before the first HTTP request in
  27. :meth:`before_request`.
  28. Although the token and expiration will change as the credentials are
  29. :meth:`refreshed <refresh>` and used, credentials should be considered
  30. immutable. Various credentials will accept configuration such as private
  31. keys, scopes, and other options. These options are not changeable after
  32. construction. Some classes will provide mechanisms to copy the credentials
  33. with modifications such as :meth:`ScopedCredentials.with_scopes`.
  34. """
  35. def __init__(self):
  36. self.token = None
  37. """str: The bearer token that can be used in HTTP headers to make
  38. authenticated requests."""
  39. self.expiry = None
  40. """Optional[datetime]: When the token expires and is no longer valid.
  41. If this is None, the token is assumed to never expire."""
  42. self._quota_project_id = None
  43. """Optional[str]: Project to use for quota and billing purposes."""
  44. @property
  45. def expired(self):
  46. """Checks if the credentials are expired.
  47. Note that credentials can be invalid but not expired because
  48. Credentials with :attr:`expiry` set to None is considered to never
  49. expire.
  50. """
  51. if not self.expiry:
  52. return False
  53. # Remove some threshold from expiry to err on the side of reporting
  54. # expiration early so that we avoid the 401-refresh-retry loop.
  55. skewed_expiry = self.expiry - _helpers.REFRESH_THRESHOLD
  56. return _helpers.utcnow() >= skewed_expiry
  57. @property
  58. def valid(self):
  59. """Checks the validity of the credentials.
  60. This is True if the credentials have a :attr:`token` and the token
  61. is not :attr:`expired`.
  62. """
  63. return self.token is not None and not self.expired
  64. @property
  65. def quota_project_id(self):
  66. """Project to use for quota and billing purposes."""
  67. return self._quota_project_id
  68. @abc.abstractmethod
  69. def refresh(self, request):
  70. """Refreshes the access token.
  71. Args:
  72. request (google.auth.transport.Request): The object used to make
  73. HTTP requests.
  74. Raises:
  75. google.auth.exceptions.RefreshError: If the credentials could
  76. not be refreshed.
  77. """
  78. # pylint: disable=missing-raises-doc
  79. # (pylint doesn't recognize that this is abstract)
  80. raise NotImplementedError("Refresh must be implemented")
  81. def apply(self, headers, token=None):
  82. """Apply the token to the authentication header.
  83. Args:
  84. headers (Mapping): The HTTP request headers.
  85. token (Optional[str]): If specified, overrides the current access
  86. token.
  87. """
  88. headers["authorization"] = "Bearer {}".format(
  89. _helpers.from_bytes(token or self.token)
  90. )
  91. if self.quota_project_id:
  92. headers["x-goog-user-project"] = self.quota_project_id
  93. def before_request(self, request, method, url, headers):
  94. """Performs credential-specific before request logic.
  95. Refreshes the credentials if necessary, then calls :meth:`apply` to
  96. apply the token to the authentication header.
  97. Args:
  98. request (google.auth.transport.Request): The object used to make
  99. HTTP requests.
  100. method (str): The request's HTTP method or the RPC method being
  101. invoked.
  102. url (str): The request's URI or the RPC service's URI.
  103. headers (Mapping): The request's headers.
  104. """
  105. # pylint: disable=unused-argument
  106. # (Subclasses may use these arguments to ascertain information about
  107. # the http request.)
  108. if not self.valid:
  109. self.refresh(request)
  110. self.apply(headers)
  111. class CredentialsWithQuotaProject(Credentials):
  112. """Abstract base for credentials supporting ``with_quota_project`` factory"""
  113. def with_quota_project(self, quota_project_id):
  114. """Returns a copy of these credentials with a modified quota project.
  115. Args:
  116. quota_project_id (str): The project to use for quota and
  117. billing purposes
  118. Returns:
  119. google.oauth2.credentials.Credentials: A new credentials instance.
  120. """
  121. raise NotImplementedError("This credential does not support quota project.")
  122. def with_quota_project_from_environment(self):
  123. quota_from_env = os.environ.get(environment_vars.GOOGLE_CLOUD_QUOTA_PROJECT)
  124. if quota_from_env:
  125. return self.with_quota_project(quota_from_env)
  126. return self
  127. class CredentialsWithTokenUri(Credentials):
  128. """Abstract base for credentials supporting ``with_token_uri`` factory"""
  129. def with_token_uri(self, token_uri):
  130. """Returns a copy of these credentials with a modified token uri.
  131. Args:
  132. token_uri (str): The uri to use for fetching/exchanging tokens
  133. Returns:
  134. google.oauth2.credentials.Credentials: A new credentials instance.
  135. """
  136. raise NotImplementedError("This credential does not use token uri.")
  137. class AnonymousCredentials(Credentials):
  138. """Credentials that do not provide any authentication information.
  139. These are useful in the case of services that support anonymous access or
  140. local service emulators that do not use credentials.
  141. """
  142. @property
  143. def expired(self):
  144. """Returns `False`, anonymous credentials never expire."""
  145. return False
  146. @property
  147. def valid(self):
  148. """Returns `True`, anonymous credentials are always valid."""
  149. return True
  150. def refresh(self, request):
  151. """Raises :class:`ValueError``, anonymous credentials cannot be
  152. refreshed."""
  153. raise ValueError("Anonymous credentials cannot be refreshed.")
  154. def apply(self, headers, token=None):
  155. """Anonymous credentials do nothing to the request.
  156. The optional ``token`` argument is not supported.
  157. Raises:
  158. ValueError: If a token was specified.
  159. """
  160. if token is not None:
  161. raise ValueError("Anonymous credentials don't support tokens.")
  162. def before_request(self, request, method, url, headers):
  163. """Anonymous credentials do nothing to the request."""
  164. @six.add_metaclass(abc.ABCMeta)
  165. class ReadOnlyScoped(object):
  166. """Interface for credentials whose scopes can be queried.
  167. OAuth 2.0-based credentials allow limiting access using scopes as described
  168. in `RFC6749 Section 3.3`_.
  169. If a credential class implements this interface then the credentials either
  170. use scopes in their implementation.
  171. Some credentials require scopes in order to obtain a token. You can check
  172. if scoping is necessary with :attr:`requires_scopes`::
  173. if credentials.requires_scopes:
  174. # Scoping is required.
  175. credentials = credentials.with_scopes(scopes=['one', 'two'])
  176. Credentials that require scopes must either be constructed with scopes::
  177. credentials = SomeScopedCredentials(scopes=['one', 'two'])
  178. Or must copy an existing instance using :meth:`with_scopes`::
  179. scoped_credentials = credentials.with_scopes(scopes=['one', 'two'])
  180. Some credentials have scopes but do not allow or require scopes to be set,
  181. these credentials can be used as-is.
  182. .. _RFC6749 Section 3.3: https://tools.ietf.org/html/rfc6749#section-3.3
  183. """
  184. def __init__(self):
  185. super(ReadOnlyScoped, self).__init__()
  186. self._scopes = None
  187. self._default_scopes = None
  188. @property
  189. def scopes(self):
  190. """Sequence[str]: the credentials' current set of scopes."""
  191. return self._scopes
  192. @property
  193. def default_scopes(self):
  194. """Sequence[str]: the credentials' current set of default scopes."""
  195. return self._default_scopes
  196. @abc.abstractproperty
  197. def requires_scopes(self):
  198. """True if these credentials require scopes to obtain an access token.
  199. """
  200. return False
  201. def has_scopes(self, scopes):
  202. """Checks if the credentials have the given scopes.
  203. .. warning: This method is not guaranteed to be accurate if the
  204. credentials are :attr:`~Credentials.invalid`.
  205. Args:
  206. scopes (Sequence[str]): The list of scopes to check.
  207. Returns:
  208. bool: True if the credentials have the given scopes.
  209. """
  210. credential_scopes = (
  211. self._scopes if self._scopes is not None else self._default_scopes
  212. )
  213. return set(scopes).issubset(set(credential_scopes or []))
  214. class Scoped(ReadOnlyScoped):
  215. """Interface for credentials whose scopes can be replaced while copying.
  216. OAuth 2.0-based credentials allow limiting access using scopes as described
  217. in `RFC6749 Section 3.3`_.
  218. If a credential class implements this interface then the credentials either
  219. use scopes in their implementation.
  220. Some credentials require scopes in order to obtain a token. You can check
  221. if scoping is necessary with :attr:`requires_scopes`::
  222. if credentials.requires_scopes:
  223. # Scoping is required.
  224. credentials = credentials.create_scoped(['one', 'two'])
  225. Credentials that require scopes must either be constructed with scopes::
  226. credentials = SomeScopedCredentials(scopes=['one', 'two'])
  227. Or must copy an existing instance using :meth:`with_scopes`::
  228. scoped_credentials = credentials.with_scopes(scopes=['one', 'two'])
  229. Some credentials have scopes but do not allow or require scopes to be set,
  230. these credentials can be used as-is.
  231. .. _RFC6749 Section 3.3: https://tools.ietf.org/html/rfc6749#section-3.3
  232. """
  233. @abc.abstractmethod
  234. def with_scopes(self, scopes, default_scopes=None):
  235. """Create a copy of these credentials with the specified scopes.
  236. Args:
  237. scopes (Sequence[str]): The list of scopes to attach to the
  238. current credentials.
  239. Raises:
  240. NotImplementedError: If the credentials' scopes can not be changed.
  241. This can be avoided by checking :attr:`requires_scopes` before
  242. calling this method.
  243. """
  244. raise NotImplementedError("This class does not require scoping.")
  245. def with_scopes_if_required(credentials, scopes, default_scopes=None):
  246. """Creates a copy of the credentials with scopes if scoping is required.
  247. This helper function is useful when you do not know (or care to know) the
  248. specific type of credentials you are using (such as when you use
  249. :func:`google.auth.default`). This function will call
  250. :meth:`Scoped.with_scopes` if the credentials are scoped credentials and if
  251. the credentials require scoping. Otherwise, it will return the credentials
  252. as-is.
  253. Args:
  254. credentials (google.auth.credentials.Credentials): The credentials to
  255. scope if necessary.
  256. scopes (Sequence[str]): The list of scopes to use.
  257. default_scopes (Sequence[str]): Default scopes passed by a
  258. Google client library. Use 'scopes' for user-defined scopes.
  259. Returns:
  260. google.auth.credentials.Credentials: Either a new set of scoped
  261. credentials, or the passed in credentials instance if no scoping
  262. was required.
  263. """
  264. if isinstance(credentials, Scoped) and credentials.requires_scopes:
  265. return credentials.with_scopes(scopes, default_scopes=default_scopes)
  266. else:
  267. return credentials
  268. @six.add_metaclass(abc.ABCMeta)
  269. class Signing(object):
  270. """Interface for credentials that can cryptographically sign messages."""
  271. @abc.abstractmethod
  272. def sign_bytes(self, message):
  273. """Signs the given message.
  274. Args:
  275. message (bytes): The message to sign.
  276. Returns:
  277. bytes: The message's cryptographic signature.
  278. """
  279. # pylint: disable=missing-raises-doc,redundant-returns-doc
  280. # (pylint doesn't recognize that this is abstract)
  281. raise NotImplementedError("Sign bytes must be implemented.")
  282. @abc.abstractproperty
  283. def signer_email(self):
  284. """Optional[str]: An email address that identifies the signer."""
  285. # pylint: disable=missing-raises-doc
  286. # (pylint doesn't recognize that this is abstract)
  287. raise NotImplementedError("Signer email must be implemented.")
  288. @abc.abstractproperty
  289. def signer(self):
  290. """google.auth.crypt.Signer: The signer used to sign bytes."""
  291. # pylint: disable=missing-raises-doc
  292. # (pylint doesn't recognize that this is abstract)
  293. raise NotImplementedError("Signer must be implemented.")