credentials.py 18 KB

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