blob: 5ea36a0bae9c5258cdfc0b3643054689b46a7f63 [file] [log] [blame]
C.J. Collier37141e42020-02-13 13:49:49 -08001# Copyright 2016 Google LLC
Jon Wayne Parrott71ce2a02016-10-14 14:08:10 -07002#
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
19
20import six
21
22from google.auth import _helpers
23
24
25@six.add_metaclass(abc.ABCMeta)
26class Credentials(object):
27 """Base class for all credentials.
28
29 All credentials have a :attr:`token` that is used for authentication and
30 may also optionally set an :attr:`expiry` to indicate when the token will
31 no longer be valid.
32
33 Most credentials will be :attr:`invalid` until :meth:`refresh` is called.
34 Credentials can do this automatically before the first HTTP request in
35 :meth:`before_request`.
36
37 Although the token and expiration will change as the credentials are
38 :meth:`refreshed <refresh>` and used, credentials should be considered
39 immutable. Various credentials will accept configuration such as private
40 keys, scopes, and other options. These options are not changeable after
41 construction. Some classes will provide mechanisms to copy the credentials
42 with modifications such as :meth:`ScopedCredentials.with_scopes`.
43 """
Bu Sun Kim9eec0912019-10-21 17:04:21 -070044
Jon Wayne Parrott71ce2a02016-10-14 14:08:10 -070045 def __init__(self):
46 self.token = None
47 """str: The bearer token that can be used in HTTP headers to make
48 authenticated requests."""
49 self.expiry = None
50 """Optional[datetime]: When the token expires and is no longer valid.
51 If this is None, the token is assumed to never expire."""
Bu Sun Kim3dda7b22020-07-09 10:39:39 -070052 self._quota_project_id = None
53 """Optional[str]: Project to use for quota and billing purposes."""
Jon Wayne Parrott71ce2a02016-10-14 14:08:10 -070054
55 @property
56 def expired(self):
57 """Checks if the credentials are expired.
58
Craig Citro2f5cb2d2018-05-14 23:29:46 -070059 Note that credentials can be invalid but not expired because
60 Credentials with :attr:`expiry` set to None is considered to never
61 expire.
Jon Wayne Parrott71ce2a02016-10-14 14:08:10 -070062 """
Jon Wayne Parrott7af9f662017-05-08 09:40:56 -070063 if not self.expiry:
64 return False
65
66 # Remove 5 minutes 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.CLOCK_SKEW
69 return _helpers.utcnow() >= skewed_expiry
Jon Wayne Parrott71ce2a02016-10-14 14:08:10 -070070
71 @property
72 def valid(self):
73 """Checks the validity of the credentials.
74
75 This is True if the credentials have a :attr:`token` and the token
76 is not :attr:`expired`.
77 """
78 return self.token is not None and not self.expired
79
Bu Sun Kim3dda7b22020-07-09 10:39:39 -070080 @property
81 def quota_project_id(self):
82 """Project to use for quota and billing purposes."""
83 return self._quota_project_id
84
Jon Wayne Parrott71ce2a02016-10-14 14:08:10 -070085 @abc.abstractmethod
86 def refresh(self, request):
87 """Refreshes the access token.
88
89 Args:
90 request (google.auth.transport.Request): The object used to make
91 HTTP requests.
92
93 Raises:
94 google.auth.exceptions.RefreshError: If the credentials could
95 not be refreshed.
96 """
97 # pylint: disable=missing-raises-doc
98 # (pylint doesn't recognize that this is abstract)
Bu Sun Kim9eec0912019-10-21 17:04:21 -070099 raise NotImplementedError("Refresh must be implemented")
Jon Wayne Parrott71ce2a02016-10-14 14:08:10 -0700100
101 def apply(self, headers, token=None):
102 """Apply the token to the authentication header.
103
104 Args:
105 headers (Mapping): The HTTP request headers.
106 token (Optional[str]): If specified, overrides the current access
107 token.
108 """
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700109 headers["authorization"] = "Bearer {}".format(
110 _helpers.from_bytes(token or self.token)
111 )
Bu Sun Kim3dda7b22020-07-09 10:39:39 -0700112 if self.quota_project_id:
113 headers["x-goog-user-project"] = self.quota_project_id
Jon Wayne Parrott71ce2a02016-10-14 14:08:10 -0700114
115 def before_request(self, request, method, url, headers):
116 """Performs credential-specific before request logic.
117
118 Refreshes the credentials if necessary, then calls :meth:`apply` to
119 apply the token to the authentication header.
120
121 Args:
Jon Wayne Parrotta0425492016-10-17 10:48:35 -0700122 request (google.auth.transport.Request): The object used to make
Jon Wayne Parrott71ce2a02016-10-14 14:08:10 -0700123 HTTP requests.
Jon Wayne Parrotta2098192017-02-22 09:27:32 -0800124 method (str): The request's HTTP method or the RPC method being
125 invoked.
126 url (str): The request's URI or the RPC service's URI.
Jon Wayne Parrott71ce2a02016-10-14 14:08:10 -0700127 headers (Mapping): The request's headers.
128 """
129 # pylint: disable=unused-argument
130 # (Subclasses may use these arguments to ascertain information about
131 # the http request.)
132 if not self.valid:
133 self.refresh(request)
134 self.apply(headers)
135
Bu Sun Kim41599ae2020-09-02 12:55:42 -0600136
137class CredentialsWithQuotaProject(Credentials):
138 """Abstract base for credentials supporting ``with_quota_project`` factory"""
139
Bu Sun Kim3dda7b22020-07-09 10:39:39 -0700140 def with_quota_project(self, quota_project_id):
141 """Returns a copy of these credentials with a modified quota project
142
143 Args:
144 quota_project_id (str): The project to use for quota and
145 billing purposes
146
147 Returns:
148 google.oauth2.credentials.Credentials: A new credentials instance.
149 """
Bu Sun Kim41599ae2020-09-02 12:55:42 -0600150 raise NotImplementedError("This credential does not support quota project.")
Bu Sun Kim3dda7b22020-07-09 10:39:39 -0700151
Jon Wayne Parrott71ce2a02016-10-14 14:08:10 -0700152
Tres Seaverb096a3d2017-10-30 16:12:37 -0400153class AnonymousCredentials(Credentials):
154 """Credentials that do not provide any authentication information.
155
156 These are useful in the case of services that support anonymous access or
157 local service emulators that do not use credentials.
158 """
159
160 @property
161 def expired(self):
162 """Returns `False`, anonymous credentials never expire."""
163 return False
164
165 @property
166 def valid(self):
167 """Returns `True`, anonymous credentials are always valid."""
168 return True
169
170 def refresh(self, request):
171 """Raises :class:`ValueError``, anonymous credentials cannot be
172 refreshed."""
173 raise ValueError("Anonymous credentials cannot be refreshed.")
174
175 def apply(self, headers, token=None):
176 """Anonymous credentials do nothing to the request.
177
178 The optional ``token`` argument is not supported.
179
180 Raises:
181 ValueError: If a token was specified.
182 """
183 if token is not None:
184 raise ValueError("Anonymous credentials don't support tokens.")
185
186 def before_request(self, request, method, url, headers):
187 """Anonymous credentials do nothing to the request."""
188
189
Jon Wayne Parrott71ce2a02016-10-14 14:08:10 -0700190@six.add_metaclass(abc.ABCMeta)
Jon Wayne Parrott4460a962017-09-12 10:01:23 -0700191class ReadOnlyScoped(object):
Tres Seaver42468322017-09-11 15:36:53 -0400192 """Interface for credentials whose scopes can be queried.
Jon Wayne Parrott71ce2a02016-10-14 14:08:10 -0700193
194 OAuth 2.0-based credentials allow limiting access using scopes as described
195 in `RFC6749 Section 3.3`_.
196 If a credential class implements this interface then the credentials either
197 use scopes in their implementation.
198
199 Some credentials require scopes in order to obtain a token. You can check
200 if scoping is necessary with :attr:`requires_scopes`::
201
202 if credentials.requires_scopes:
203 # Scoping is required.
Ondrej Medekf682cb22017-11-27 18:33:46 +0100204 credentials = credentials.with_scopes(scopes=['one', 'two'])
Jon Wayne Parrott71ce2a02016-10-14 14:08:10 -0700205
206 Credentials that require scopes must either be constructed with scopes::
207
208 credentials = SomeScopedCredentials(scopes=['one', 'two'])
209
210 Or must copy an existing instance using :meth:`with_scopes`::
211
212 scoped_credentials = credentials.with_scopes(scopes=['one', 'two'])
213
214 Some credentials have scopes but do not allow or require scopes to be set,
215 these credentials can be used as-is.
216
217 .. _RFC6749 Section 3.3: https://tools.ietf.org/html/rfc6749#section-3.3
218 """
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700219
Jon Wayne Parrott71ce2a02016-10-14 14:08:10 -0700220 def __init__(self):
Jon Wayne Parrott4460a962017-09-12 10:01:23 -0700221 super(ReadOnlyScoped, self).__init__()
Jon Wayne Parrott71ce2a02016-10-14 14:08:10 -0700222 self._scopes = None
223
224 @property
225 def scopes(self):
226 """Sequence[str]: the credentials' current set of scopes."""
227 return self._scopes
228
229 @abc.abstractproperty
230 def requires_scopes(self):
231 """True if these credentials require scopes to obtain an access token.
232 """
233 return False
234
Tres Seaver42468322017-09-11 15:36:53 -0400235 def has_scopes(self, scopes):
236 """Checks if the credentials have the given scopes.
237
238 .. warning: This method is not guaranteed to be accurate if the
239 credentials are :attr:`~Credentials.invalid`.
240
Danny Hermes369e2a72017-12-13 12:08:15 -0800241 Args:
242 scopes (Sequence[str]): The list of scopes to check.
243
Tres Seaver42468322017-09-11 15:36:53 -0400244 Returns:
245 bool: True if the credentials have the given scopes.
246 """
247 return set(scopes).issubset(set(self._scopes or []))
248
249
Jon Wayne Parrott4460a962017-09-12 10:01:23 -0700250class Scoped(ReadOnlyScoped):
Tres Seaver42468322017-09-11 15:36:53 -0400251 """Interface for credentials whose scopes can be replaced while copying.
252
253 OAuth 2.0-based credentials allow limiting access using scopes as described
254 in `RFC6749 Section 3.3`_.
255 If a credential class implements this interface then the credentials either
256 use scopes in their implementation.
257
258 Some credentials require scopes in order to obtain a token. You can check
259 if scoping is necessary with :attr:`requires_scopes`::
260
261 if credentials.requires_scopes:
262 # Scoping is required.
263 credentials = credentials.create_scoped(['one', 'two'])
264
265 Credentials that require scopes must either be constructed with scopes::
266
267 credentials = SomeScopedCredentials(scopes=['one', 'two'])
268
269 Or must copy an existing instance using :meth:`with_scopes`::
270
271 scoped_credentials = credentials.with_scopes(scopes=['one', 'two'])
272
273 Some credentials have scopes but do not allow or require scopes to be set,
274 these credentials can be used as-is.
275
276 .. _RFC6749 Section 3.3: https://tools.ietf.org/html/rfc6749#section-3.3
277 """
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700278
Jon Wayne Parrott71ce2a02016-10-14 14:08:10 -0700279 @abc.abstractmethod
280 def with_scopes(self, scopes):
281 """Create a copy of these credentials with the specified scopes.
282
283 Args:
Danny Hermes369e2a72017-12-13 12:08:15 -0800284 scopes (Sequence[str]): The list of scopes to attach to the
285 current credentials.
Jon Wayne Parrott71ce2a02016-10-14 14:08:10 -0700286
287 Raises:
288 NotImplementedError: If the credentials' scopes can not be changed.
289 This can be avoided by checking :attr:`requires_scopes` before
290 calling this method.
291 """
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700292 raise NotImplementedError("This class does not require scoping.")
Jon Wayne Parrott71ce2a02016-10-14 14:08:10 -0700293
Jon Wayne Parrott71ce2a02016-10-14 14:08:10 -0700294
Jon Wayne Parrottf89a3cf2016-10-31 10:52:57 -0700295def with_scopes_if_required(credentials, scopes):
296 """Creates a copy of the credentials with scopes if scoping is required.
297
298 This helper function is useful when you do not know (or care to know) the
299 specific type of credentials you are using (such as when you use
300 :func:`google.auth.default`). This function will call
301 :meth:`Scoped.with_scopes` if the credentials are scoped credentials and if
302 the credentials require scoping. Otherwise, it will return the credentials
303 as-is.
304
305 Args:
Jon Wayne Parrottbdbf2b12016-11-10 15:00:29 -0800306 credentials (google.auth.credentials.Credentials): The credentials to
Jon Wayne Parrott8c3a10b2016-11-10 12:42:50 -0800307 scope if necessary.
Jon Wayne Parrottf89a3cf2016-10-31 10:52:57 -0700308 scopes (Sequence[str]): The list of scopes to use.
309
310 Returns:
Jon Wayne Parrottbdbf2b12016-11-10 15:00:29 -0800311 google.auth.credentials.Credentials: Either a new set of scoped
Jon Wayne Parrott8c3a10b2016-11-10 12:42:50 -0800312 credentials, or the passed in credentials instance if no scoping
313 was required.
Jon Wayne Parrottf89a3cf2016-10-31 10:52:57 -0700314 """
315 if isinstance(credentials, Scoped) and credentials.requires_scopes:
316 return credentials.with_scopes(scopes)
317 else:
318 return credentials
319
320
Jon Wayne Parrott71ce2a02016-10-14 14:08:10 -0700321@six.add_metaclass(abc.ABCMeta)
322class Signing(object):
323 """Interface for credentials that can cryptographically sign messages."""
324
325 @abc.abstractmethod
326 def sign_bytes(self, message):
327 """Signs the given message.
328
329 Args:
330 message (bytes): The message to sign.
331
332 Returns:
333 bytes: The message's cryptographic signature.
334 """
335 # pylint: disable=missing-raises-doc,redundant-returns-doc
336 # (pylint doesn't recognize that this is abstract)
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700337 raise NotImplementedError("Sign bytes must be implemented.")
Jon Wayne Parrott4c883f02016-12-02 14:26:33 -0800338
339 @abc.abstractproperty
340 def signer_email(self):
341 """Optional[str]: An email address that identifies the signer."""
342 # pylint: disable=missing-raises-doc
343 # (pylint doesn't recognize that this is abstract)
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700344 raise NotImplementedError("Signer email must be implemented.")
Jon Wayne Parrottd7221672017-02-16 09:05:11 -0800345
346 @abc.abstractproperty
347 def signer(self):
348 """google.auth.crypt.Signer: The signer used to sign bytes."""
349 # pylint: disable=missing-raises-doc
350 # (pylint doesn't recognize that this is abstract)
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700351 raise NotImplementedError("Signer must be implemented.")