credentials.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522
  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. from enum import Enum
  17. import os
  18. from google.auth import _helpers, environment_vars
  19. from google.auth import exceptions
  20. from google.auth import metrics
  21. from google.auth._credentials_base import _BaseCredentials
  22. from google.auth._refresh_worker import RefreshThreadManager
  23. DEFAULT_UNIVERSE_DOMAIN = "googleapis.com"
  24. class Credentials(_BaseCredentials):
  25. """Base class for all credentials.
  26. All credentials have a :attr:`token` that is used for authentication and
  27. may also optionally set an :attr:`expiry` to indicate when the token will
  28. no longer be valid.
  29. Most credentials will be :attr:`invalid` until :meth:`refresh` is called.
  30. Credentials can do this automatically before the first HTTP request in
  31. :meth:`before_request`.
  32. Although the token and expiration will change as the credentials are
  33. :meth:`refreshed <refresh>` and used, credentials should be considered
  34. immutable. Various credentials will accept configuration such as private
  35. keys, scopes, and other options. These options are not changeable after
  36. construction. Some classes will provide mechanisms to copy the credentials
  37. with modifications such as :meth:`ScopedCredentials.with_scopes`.
  38. """
  39. def __init__(self):
  40. super(Credentials, self).__init__()
  41. self.expiry = None
  42. """Optional[datetime]: When the token expires and is no longer valid.
  43. If this is None, the token is assumed to never expire."""
  44. self._quota_project_id = None
  45. """Optional[str]: Project to use for quota and billing purposes."""
  46. self._trust_boundary = None
  47. """Optional[dict]: Cache of a trust boundary response which has a list
  48. of allowed regions and an encoded string representation of credentials
  49. trust boundary."""
  50. self._universe_domain = DEFAULT_UNIVERSE_DOMAIN
  51. """Optional[str]: The universe domain value, default is googleapis.com
  52. """
  53. self._use_non_blocking_refresh = False
  54. self._refresh_worker = RefreshThreadManager()
  55. @property
  56. def expired(self):
  57. """Checks if the credentials are expired.
  58. Note that credentials can be invalid but not expired because
  59. Credentials with :attr:`expiry` set to None is considered to never
  60. expire.
  61. .. deprecated:: v2.24.0
  62. Prefer checking :attr:`token_state` instead.
  63. """
  64. if not self.expiry:
  65. return False
  66. # Remove some threshold from expiry to err on the side of reporting
  67. # expiration early so that we avoid the 401-refresh-retry loop.
  68. skewed_expiry = self.expiry - _helpers.REFRESH_THRESHOLD
  69. return _helpers.utcnow() >= skewed_expiry
  70. @property
  71. def valid(self):
  72. """Checks the validity of the credentials.
  73. This is True if the credentials have a :attr:`token` and the token
  74. is not :attr:`expired`.
  75. .. deprecated:: v2.24.0
  76. Prefer checking :attr:`token_state` instead.
  77. """
  78. return self.token is not None and not self.expired
  79. @property
  80. def token_state(self):
  81. """
  82. See `:obj:`TokenState`
  83. """
  84. if self.token is None:
  85. return TokenState.INVALID
  86. # Credentials that can't expire are always treated as fresh.
  87. if self.expiry is None:
  88. return TokenState.FRESH
  89. expired = _helpers.utcnow() >= self.expiry
  90. if expired:
  91. return TokenState.INVALID
  92. is_stale = _helpers.utcnow() >= (self.expiry - _helpers.REFRESH_THRESHOLD)
  93. if is_stale:
  94. return TokenState.STALE
  95. return TokenState.FRESH
  96. @property
  97. def quota_project_id(self):
  98. """Project to use for quota and billing purposes."""
  99. return self._quota_project_id
  100. @property
  101. def universe_domain(self):
  102. """The universe domain value."""
  103. return self._universe_domain
  104. def get_cred_info(self):
  105. """The credential information JSON.
  106. The credential information will be added to auth related error messages
  107. by client library.
  108. Returns:
  109. Mapping[str, str]: The credential information JSON.
  110. """
  111. return None
  112. @abc.abstractmethod
  113. def refresh(self, request):
  114. """Refreshes the access token.
  115. Args:
  116. request (google.auth.transport.Request): The object used to make
  117. HTTP requests.
  118. Raises:
  119. google.auth.exceptions.RefreshError: If the credentials could
  120. not be refreshed.
  121. """
  122. # pylint: disable=missing-raises-doc
  123. # (pylint doesn't recognize that this is abstract)
  124. raise NotImplementedError("Refresh must be implemented")
  125. def _metric_header_for_usage(self):
  126. """The x-goog-api-client header for token usage metric.
  127. This header will be added to the API service requests in before_request
  128. method. For example, "cred-type/sa-jwt" means service account self
  129. signed jwt access token is used in the API service request
  130. authorization header. Children credentials classes need to override
  131. this method to provide the header value, if the token usage metric is
  132. needed.
  133. Returns:
  134. str: The x-goog-api-client header value.
  135. """
  136. return None
  137. def apply(self, headers, token=None):
  138. """Apply the token to the authentication header.
  139. Args:
  140. headers (Mapping): The HTTP request headers.
  141. token (Optional[str]): If specified, overrides the current access
  142. token.
  143. """
  144. self._apply(headers, token=token)
  145. """Trust boundary value will be a cached value from global lookup.
  146. The response of trust boundary will be a list of regions and a hex
  147. encoded representation.
  148. An example of global lookup response:
  149. {
  150. "locations": [
  151. "us-central1", "us-east1", "europe-west1", "asia-east1"
  152. ]
  153. "encoded_locations": "0xA30"
  154. }
  155. """
  156. if self._trust_boundary is not None:
  157. headers["x-allowed-locations"] = self._trust_boundary["encoded_locations"]
  158. if self.quota_project_id:
  159. headers["x-goog-user-project"] = self.quota_project_id
  160. def _blocking_refresh(self, request):
  161. if not self.valid:
  162. self.refresh(request)
  163. def _non_blocking_refresh(self, request):
  164. use_blocking_refresh_fallback = False
  165. if self.token_state == TokenState.STALE:
  166. use_blocking_refresh_fallback = not self._refresh_worker.start_refresh(
  167. self, request
  168. )
  169. if self.token_state == TokenState.INVALID or use_blocking_refresh_fallback:
  170. self.refresh(request)
  171. # If the blocking refresh succeeds then we can clear the error info
  172. # on the background refresh worker, and perform refreshes in a
  173. # background thread.
  174. self._refresh_worker.clear_error()
  175. def before_request(self, request, method, url, headers):
  176. """Performs credential-specific before request logic.
  177. Refreshes the credentials if necessary, then calls :meth:`apply` to
  178. apply the token to the authentication header.
  179. Args:
  180. request (google.auth.transport.Request): The object used to make
  181. HTTP requests.
  182. method (str): The request's HTTP method or the RPC method being
  183. invoked.
  184. url (str): The request's URI or the RPC service's URI.
  185. headers (Mapping): The request's headers.
  186. """
  187. # pylint: disable=unused-argument
  188. # (Subclasses may use these arguments to ascertain information about
  189. # the http request.)
  190. if self._use_non_blocking_refresh:
  191. self._non_blocking_refresh(request)
  192. else:
  193. self._blocking_refresh(request)
  194. metrics.add_metric_header(headers, self._metric_header_for_usage())
  195. self.apply(headers)
  196. def with_non_blocking_refresh(self):
  197. self._use_non_blocking_refresh = True
  198. class CredentialsWithQuotaProject(Credentials):
  199. """Abstract base for credentials supporting ``with_quota_project`` factory"""
  200. def with_quota_project(self, quota_project_id):
  201. """Returns a copy of these credentials with a modified quota project.
  202. Args:
  203. quota_project_id (str): The project to use for quota and
  204. billing purposes
  205. Returns:
  206. google.auth.credentials.Credentials: A new credentials instance.
  207. """
  208. raise NotImplementedError("This credential does not support quota project.")
  209. def with_quota_project_from_environment(self):
  210. quota_from_env = os.environ.get(environment_vars.GOOGLE_CLOUD_QUOTA_PROJECT)
  211. if quota_from_env:
  212. return self.with_quota_project(quota_from_env)
  213. return self
  214. class CredentialsWithTokenUri(Credentials):
  215. """Abstract base for credentials supporting ``with_token_uri`` factory"""
  216. def with_token_uri(self, token_uri):
  217. """Returns a copy of these credentials with a modified token uri.
  218. Args:
  219. token_uri (str): The uri to use for fetching/exchanging tokens
  220. Returns:
  221. google.auth.credentials.Credentials: A new credentials instance.
  222. """
  223. raise NotImplementedError("This credential does not use token uri.")
  224. class CredentialsWithUniverseDomain(Credentials):
  225. """Abstract base for credentials supporting ``with_universe_domain`` factory"""
  226. def with_universe_domain(self, universe_domain):
  227. """Returns a copy of these credentials with a modified universe domain.
  228. Args:
  229. universe_domain (str): The universe domain to use
  230. Returns:
  231. google.auth.credentials.Credentials: A new credentials instance.
  232. """
  233. raise NotImplementedError(
  234. "This credential does not support with_universe_domain."
  235. )
  236. class AnonymousCredentials(Credentials):
  237. """Credentials that do not provide any authentication information.
  238. These are useful in the case of services that support anonymous access or
  239. local service emulators that do not use credentials.
  240. """
  241. @property
  242. def expired(self):
  243. """Returns `False`, anonymous credentials never expire."""
  244. return False
  245. @property
  246. def valid(self):
  247. """Returns `True`, anonymous credentials are always valid."""
  248. return True
  249. def refresh(self, request):
  250. """Raises :class:``InvalidOperation``, anonymous credentials cannot be
  251. refreshed."""
  252. raise exceptions.InvalidOperation("Anonymous credentials cannot be refreshed.")
  253. def apply(self, headers, token=None):
  254. """Anonymous credentials do nothing to the request.
  255. The optional ``token`` argument is not supported.
  256. Raises:
  257. google.auth.exceptions.InvalidValue: If a token was specified.
  258. """
  259. if token is not None:
  260. raise exceptions.InvalidValue("Anonymous credentials don't support tokens.")
  261. def before_request(self, request, method, url, headers):
  262. """Anonymous credentials do nothing to the request."""
  263. class ReadOnlyScoped(metaclass=abc.ABCMeta):
  264. """Interface for credentials whose scopes can be queried.
  265. OAuth 2.0-based credentials allow limiting access using scopes as described
  266. in `RFC6749 Section 3.3`_.
  267. If a credential class implements this interface then the credentials either
  268. use scopes in their implementation.
  269. Some credentials require scopes in order to obtain a token. You can check
  270. if scoping is necessary with :attr:`requires_scopes`::
  271. if credentials.requires_scopes:
  272. # Scoping is required.
  273. credentials = credentials.with_scopes(scopes=['one', 'two'])
  274. Credentials that require scopes must either be constructed with scopes::
  275. credentials = SomeScopedCredentials(scopes=['one', 'two'])
  276. Or must copy an existing instance using :meth:`with_scopes`::
  277. scoped_credentials = credentials.with_scopes(scopes=['one', 'two'])
  278. Some credentials have scopes but do not allow or require scopes to be set,
  279. these credentials can be used as-is.
  280. .. _RFC6749 Section 3.3: https://tools.ietf.org/html/rfc6749#section-3.3
  281. """
  282. def __init__(self):
  283. super(ReadOnlyScoped, self).__init__()
  284. self._scopes = None
  285. self._default_scopes = None
  286. @property
  287. def scopes(self):
  288. """Sequence[str]: the credentials' current set of scopes."""
  289. return self._scopes
  290. @property
  291. def default_scopes(self):
  292. """Sequence[str]: the credentials' current set of default scopes."""
  293. return self._default_scopes
  294. @abc.abstractproperty
  295. def requires_scopes(self):
  296. """True if these credentials require scopes to obtain an access token.
  297. """
  298. return False
  299. def has_scopes(self, scopes):
  300. """Checks if the credentials have the given scopes.
  301. .. warning: This method is not guaranteed to be accurate if the
  302. credentials are :attr:`~Credentials.invalid`.
  303. Args:
  304. scopes (Sequence[str]): The list of scopes to check.
  305. Returns:
  306. bool: True if the credentials have the given scopes.
  307. """
  308. credential_scopes = (
  309. self._scopes if self._scopes is not None else self._default_scopes
  310. )
  311. return set(scopes).issubset(set(credential_scopes or []))
  312. class Scoped(ReadOnlyScoped):
  313. """Interface for credentials whose scopes can be replaced while copying.
  314. OAuth 2.0-based credentials allow limiting access using scopes as described
  315. in `RFC6749 Section 3.3`_.
  316. If a credential class implements this interface then the credentials either
  317. use scopes in their implementation.
  318. Some credentials require scopes in order to obtain a token. You can check
  319. if scoping is necessary with :attr:`requires_scopes`::
  320. if credentials.requires_scopes:
  321. # Scoping is required.
  322. credentials = credentials.create_scoped(['one', 'two'])
  323. Credentials that require scopes must either be constructed with scopes::
  324. credentials = SomeScopedCredentials(scopes=['one', 'two'])
  325. Or must copy an existing instance using :meth:`with_scopes`::
  326. scoped_credentials = credentials.with_scopes(scopes=['one', 'two'])
  327. Some credentials have scopes but do not allow or require scopes to be set,
  328. these credentials can be used as-is.
  329. .. _RFC6749 Section 3.3: https://tools.ietf.org/html/rfc6749#section-3.3
  330. """
  331. @abc.abstractmethod
  332. def with_scopes(self, scopes, default_scopes=None):
  333. """Create a copy of these credentials with the specified scopes.
  334. Args:
  335. scopes (Sequence[str]): The list of scopes to attach to the
  336. current credentials.
  337. Raises:
  338. NotImplementedError: If the credentials' scopes can not be changed.
  339. This can be avoided by checking :attr:`requires_scopes` before
  340. calling this method.
  341. """
  342. raise NotImplementedError("This class does not require scoping.")
  343. def with_scopes_if_required(credentials, scopes, default_scopes=None):
  344. """Creates a copy of the credentials with scopes if scoping is required.
  345. This helper function is useful when you do not know (or care to know) the
  346. specific type of credentials you are using (such as when you use
  347. :func:`google.auth.default`). This function will call
  348. :meth:`Scoped.with_scopes` if the credentials are scoped credentials and if
  349. the credentials require scoping. Otherwise, it will return the credentials
  350. as-is.
  351. Args:
  352. credentials (google.auth.credentials.Credentials): The credentials to
  353. scope if necessary.
  354. scopes (Sequence[str]): The list of scopes to use.
  355. default_scopes (Sequence[str]): Default scopes passed by a
  356. Google client library. Use 'scopes' for user-defined scopes.
  357. Returns:
  358. google.auth.credentials.Credentials: Either a new set of scoped
  359. credentials, or the passed in credentials instance if no scoping
  360. was required.
  361. """
  362. if isinstance(credentials, Scoped) and credentials.requires_scopes:
  363. return credentials.with_scopes(scopes, default_scopes=default_scopes)
  364. else:
  365. return credentials
  366. class Signing(metaclass=abc.ABCMeta):
  367. """Interface for credentials that can cryptographically sign messages."""
  368. @abc.abstractmethod
  369. def sign_bytes(self, message):
  370. """Signs the given message.
  371. Args:
  372. message (bytes): The message to sign.
  373. Returns:
  374. bytes: The message's cryptographic signature.
  375. """
  376. # pylint: disable=missing-raises-doc,redundant-returns-doc
  377. # (pylint doesn't recognize that this is abstract)
  378. raise NotImplementedError("Sign bytes must be implemented.")
  379. @abc.abstractproperty
  380. def signer_email(self):
  381. """Optional[str]: An email address that identifies the signer."""
  382. # pylint: disable=missing-raises-doc
  383. # (pylint doesn't recognize that this is abstract)
  384. raise NotImplementedError("Signer email must be implemented.")
  385. @abc.abstractproperty
  386. def signer(self):
  387. """google.auth.crypt.Signer: The signer used to sign bytes."""
  388. # pylint: disable=missing-raises-doc
  389. # (pylint doesn't recognize that this is abstract)
  390. raise NotImplementedError("Signer must be implemented.")
  391. class TokenState(Enum):
  392. """
  393. Tracks the state of a token.
  394. FRESH: The token is valid. It is not expired or close to expired, or the token has no expiry.
  395. STALE: The token is close to expired, and should be refreshed. The token can be used normally.
  396. INVALID: The token is expired or invalid. The token cannot be used for a normal operation.
  397. """
  398. FRESH = 1
  399. STALE = 2
  400. INVALID = 3