credentials.py 13 KB

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