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