credentials.py 18 KB

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