blob: 3cc976b525dadf9badd470a0fbe4c2d127681a84 [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."""
52
53 @property
54 def expired(self):
55 """Checks if the credentials are expired.
56
Craig Citro2f5cb2d2018-05-14 23:29:46 -070057 Note that credentials can be invalid but not expired because
58 Credentials with :attr:`expiry` set to None is considered to never
59 expire.
Jon Wayne Parrott71ce2a02016-10-14 14:08:10 -070060 """
Jon Wayne Parrott7af9f662017-05-08 09:40:56 -070061 if not self.expiry:
62 return False
63
64 # Remove 5 minutes from expiry to err on the side of reporting
65 # expiration early so that we avoid the 401-refresh-retry loop.
66 skewed_expiry = self.expiry - _helpers.CLOCK_SKEW
67 return _helpers.utcnow() >= skewed_expiry
Jon Wayne Parrott71ce2a02016-10-14 14:08:10 -070068
69 @property
70 def valid(self):
71 """Checks the validity of the credentials.
72
73 This is True if the credentials have a :attr:`token` and the token
74 is not :attr:`expired`.
75 """
76 return self.token is not None and not self.expired
77
78 @abc.abstractmethod
79 def refresh(self, request):
80 """Refreshes the access token.
81
82 Args:
83 request (google.auth.transport.Request): The object used to make
84 HTTP requests.
85
86 Raises:
87 google.auth.exceptions.RefreshError: If the credentials could
88 not be refreshed.
89 """
90 # pylint: disable=missing-raises-doc
91 # (pylint doesn't recognize that this is abstract)
Bu Sun Kim9eec0912019-10-21 17:04:21 -070092 raise NotImplementedError("Refresh must be implemented")
Jon Wayne Parrott71ce2a02016-10-14 14:08:10 -070093
94 def apply(self, headers, token=None):
95 """Apply the token to the authentication header.
96
97 Args:
98 headers (Mapping): The HTTP request headers.
99 token (Optional[str]): If specified, overrides the current access
100 token.
101 """
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700102 headers["authorization"] = "Bearer {}".format(
103 _helpers.from_bytes(token or self.token)
104 )
Jon Wayne Parrott71ce2a02016-10-14 14:08:10 -0700105
106 def before_request(self, request, method, url, headers):
107 """Performs credential-specific before request logic.
108
109 Refreshes the credentials if necessary, then calls :meth:`apply` to
110 apply the token to the authentication header.
111
112 Args:
Jon Wayne Parrotta0425492016-10-17 10:48:35 -0700113 request (google.auth.transport.Request): The object used to make
Jon Wayne Parrott71ce2a02016-10-14 14:08:10 -0700114 HTTP requests.
Jon Wayne Parrotta2098192017-02-22 09:27:32 -0800115 method (str): The request's HTTP method or the RPC method being
116 invoked.
117 url (str): The request's URI or the RPC service's URI.
Jon Wayne Parrott71ce2a02016-10-14 14:08:10 -0700118 headers (Mapping): The request's headers.
119 """
120 # pylint: disable=unused-argument
121 # (Subclasses may use these arguments to ascertain information about
122 # the http request.)
123 if not self.valid:
124 self.refresh(request)
125 self.apply(headers)
126
127
Tres Seaverb096a3d2017-10-30 16:12:37 -0400128class AnonymousCredentials(Credentials):
129 """Credentials that do not provide any authentication information.
130
131 These are useful in the case of services that support anonymous access or
132 local service emulators that do not use credentials.
133 """
134
135 @property
136 def expired(self):
137 """Returns `False`, anonymous credentials never expire."""
138 return False
139
140 @property
141 def valid(self):
142 """Returns `True`, anonymous credentials are always valid."""
143 return True
144
145 def refresh(self, request):
146 """Raises :class:`ValueError``, anonymous credentials cannot be
147 refreshed."""
148 raise ValueError("Anonymous credentials cannot be refreshed.")
149
150 def apply(self, headers, token=None):
151 """Anonymous credentials do nothing to the request.
152
153 The optional ``token`` argument is not supported.
154
155 Raises:
156 ValueError: If a token was specified.
157 """
158 if token is not None:
159 raise ValueError("Anonymous credentials don't support tokens.")
160
161 def before_request(self, request, method, url, headers):
162 """Anonymous credentials do nothing to the request."""
163
164
Jon Wayne Parrott71ce2a02016-10-14 14:08:10 -0700165@six.add_metaclass(abc.ABCMeta)
Jon Wayne Parrott4460a962017-09-12 10:01:23 -0700166class ReadOnlyScoped(object):
Tres Seaver42468322017-09-11 15:36:53 -0400167 """Interface for credentials whose scopes can be queried.
Jon Wayne Parrott71ce2a02016-10-14 14:08:10 -0700168
169 OAuth 2.0-based credentials allow limiting access using scopes as described
170 in `RFC6749 Section 3.3`_.
171 If a credential class implements this interface then the credentials either
172 use scopes in their implementation.
173
174 Some credentials require scopes in order to obtain a token. You can check
175 if scoping is necessary with :attr:`requires_scopes`::
176
177 if credentials.requires_scopes:
178 # Scoping is required.
Ondrej Medekf682cb22017-11-27 18:33:46 +0100179 credentials = credentials.with_scopes(scopes=['one', 'two'])
Jon Wayne Parrott71ce2a02016-10-14 14:08:10 -0700180
181 Credentials that require scopes must either be constructed with scopes::
182
183 credentials = SomeScopedCredentials(scopes=['one', 'two'])
184
185 Or must copy an existing instance using :meth:`with_scopes`::
186
187 scoped_credentials = credentials.with_scopes(scopes=['one', 'two'])
188
189 Some credentials have scopes but do not allow or require scopes to be set,
190 these credentials can be used as-is.
191
192 .. _RFC6749 Section 3.3: https://tools.ietf.org/html/rfc6749#section-3.3
193 """
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700194
Jon Wayne Parrott71ce2a02016-10-14 14:08:10 -0700195 def __init__(self):
Jon Wayne Parrott4460a962017-09-12 10:01:23 -0700196 super(ReadOnlyScoped, self).__init__()
Jon Wayne Parrott71ce2a02016-10-14 14:08:10 -0700197 self._scopes = None
198
199 @property
200 def scopes(self):
201 """Sequence[str]: the credentials' current set of scopes."""
202 return self._scopes
203
204 @abc.abstractproperty
205 def requires_scopes(self):
206 """True if these credentials require scopes to obtain an access token.
207 """
208 return False
209
Tres Seaver42468322017-09-11 15:36:53 -0400210 def has_scopes(self, scopes):
211 """Checks if the credentials have the given scopes.
212
213 .. warning: This method is not guaranteed to be accurate if the
214 credentials are :attr:`~Credentials.invalid`.
215
Danny Hermes369e2a72017-12-13 12:08:15 -0800216 Args:
217 scopes (Sequence[str]): The list of scopes to check.
218
Tres Seaver42468322017-09-11 15:36:53 -0400219 Returns:
220 bool: True if the credentials have the given scopes.
221 """
222 return set(scopes).issubset(set(self._scopes or []))
223
224
Jon Wayne Parrott4460a962017-09-12 10:01:23 -0700225class Scoped(ReadOnlyScoped):
Tres Seaver42468322017-09-11 15:36:53 -0400226 """Interface for credentials whose scopes can be replaced while copying.
227
228 OAuth 2.0-based credentials allow limiting access using scopes as described
229 in `RFC6749 Section 3.3`_.
230 If a credential class implements this interface then the credentials either
231 use scopes in their implementation.
232
233 Some credentials require scopes in order to obtain a token. You can check
234 if scoping is necessary with :attr:`requires_scopes`::
235
236 if credentials.requires_scopes:
237 # Scoping is required.
238 credentials = credentials.create_scoped(['one', 'two'])
239
240 Credentials that require scopes must either be constructed with scopes::
241
242 credentials = SomeScopedCredentials(scopes=['one', 'two'])
243
244 Or must copy an existing instance using :meth:`with_scopes`::
245
246 scoped_credentials = credentials.with_scopes(scopes=['one', 'two'])
247
248 Some credentials have scopes but do not allow or require scopes to be set,
249 these credentials can be used as-is.
250
251 .. _RFC6749 Section 3.3: https://tools.ietf.org/html/rfc6749#section-3.3
252 """
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700253
Jon Wayne Parrott71ce2a02016-10-14 14:08:10 -0700254 @abc.abstractmethod
255 def with_scopes(self, scopes):
256 """Create a copy of these credentials with the specified scopes.
257
258 Args:
Danny Hermes369e2a72017-12-13 12:08:15 -0800259 scopes (Sequence[str]): The list of scopes to attach to the
260 current credentials.
Jon Wayne Parrott71ce2a02016-10-14 14:08:10 -0700261
262 Raises:
263 NotImplementedError: If the credentials' scopes can not be changed.
264 This can be avoided by checking :attr:`requires_scopes` before
265 calling this method.
266 """
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700267 raise NotImplementedError("This class does not require scoping.")
Jon Wayne Parrott71ce2a02016-10-14 14:08:10 -0700268
Jon Wayne Parrott71ce2a02016-10-14 14:08:10 -0700269
Jon Wayne Parrottf89a3cf2016-10-31 10:52:57 -0700270def with_scopes_if_required(credentials, scopes):
271 """Creates a copy of the credentials with scopes if scoping is required.
272
273 This helper function is useful when you do not know (or care to know) the
274 specific type of credentials you are using (such as when you use
275 :func:`google.auth.default`). This function will call
276 :meth:`Scoped.with_scopes` if the credentials are scoped credentials and if
277 the credentials require scoping. Otherwise, it will return the credentials
278 as-is.
279
280 Args:
Jon Wayne Parrottbdbf2b12016-11-10 15:00:29 -0800281 credentials (google.auth.credentials.Credentials): The credentials to
Jon Wayne Parrott8c3a10b2016-11-10 12:42:50 -0800282 scope if necessary.
Jon Wayne Parrottf89a3cf2016-10-31 10:52:57 -0700283 scopes (Sequence[str]): The list of scopes to use.
284
285 Returns:
Jon Wayne Parrottbdbf2b12016-11-10 15:00:29 -0800286 google.auth.credentials.Credentials: Either a new set of scoped
Jon Wayne Parrott8c3a10b2016-11-10 12:42:50 -0800287 credentials, or the passed in credentials instance if no scoping
288 was required.
Jon Wayne Parrottf89a3cf2016-10-31 10:52:57 -0700289 """
290 if isinstance(credentials, Scoped) and credentials.requires_scopes:
291 return credentials.with_scopes(scopes)
292 else:
293 return credentials
294
295
Jon Wayne Parrott71ce2a02016-10-14 14:08:10 -0700296@six.add_metaclass(abc.ABCMeta)
297class Signing(object):
298 """Interface for credentials that can cryptographically sign messages."""
299
300 @abc.abstractmethod
301 def sign_bytes(self, message):
302 """Signs the given message.
303
304 Args:
305 message (bytes): The message to sign.
306
307 Returns:
308 bytes: The message's cryptographic signature.
309 """
310 # pylint: disable=missing-raises-doc,redundant-returns-doc
311 # (pylint doesn't recognize that this is abstract)
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700312 raise NotImplementedError("Sign bytes must be implemented.")
Jon Wayne Parrott4c883f02016-12-02 14:26:33 -0800313
314 @abc.abstractproperty
315 def signer_email(self):
316 """Optional[str]: An email address that identifies the signer."""
317 # pylint: disable=missing-raises-doc
318 # (pylint doesn't recognize that this is abstract)
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700319 raise NotImplementedError("Signer email must be implemented.")
Jon Wayne Parrottd7221672017-02-16 09:05:11 -0800320
321 @abc.abstractproperty
322 def signer(self):
323 """google.auth.crypt.Signer: The signer used to sign bytes."""
324 # pylint: disable=missing-raises-doc
325 # (pylint doesn't recognize that this is abstract)
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700326 raise NotImplementedError("Signer must be implemented.")