blob: 8ff1f0251b167427063eff7a49ff7ca770bc7014 [file] [log] [blame]
Jon Wayne Parrott71ce2a02016-10-14 14:08:10 -07001# Copyright 2016 Google Inc.
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
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 """
44 def __init__(self):
45 self.token = None
46 """str: The bearer token that can be used in HTTP headers to make
47 authenticated requests."""
48 self.expiry = None
49 """Optional[datetime]: When the token expires and is no longer valid.
50 If this is None, the token is assumed to never expire."""
51
52 @property
53 def expired(self):
54 """Checks if the credentials are expired.
55
Craig Citro2f5cb2d2018-05-14 23:29:46 -070056 Note that credentials can be invalid but not expired because
57 Credentials with :attr:`expiry` set to None is considered to never
58 expire.
Jon Wayne Parrott71ce2a02016-10-14 14:08:10 -070059 """
Jon Wayne Parrott7af9f662017-05-08 09:40:56 -070060 if not self.expiry:
61 return False
62
63 # Remove 5 minutes from expiry to err on the side of reporting
64 # expiration early so that we avoid the 401-refresh-retry loop.
65 skewed_expiry = self.expiry - _helpers.CLOCK_SKEW
66 return _helpers.utcnow() >= skewed_expiry
Jon Wayne Parrott71ce2a02016-10-14 14:08:10 -070067
68 @property
69 def valid(self):
70 """Checks the validity of the credentials.
71
72 This is True if the credentials have a :attr:`token` and the token
73 is not :attr:`expired`.
74 """
75 return self.token is not None and not self.expired
76
77 @abc.abstractmethod
78 def refresh(self, request):
79 """Refreshes the access token.
80
81 Args:
82 request (google.auth.transport.Request): The object used to make
83 HTTP requests.
84
85 Raises:
86 google.auth.exceptions.RefreshError: If the credentials could
87 not be refreshed.
88 """
89 # pylint: disable=missing-raises-doc
90 # (pylint doesn't recognize that this is abstract)
91 raise NotImplementedError('Refresh must be implemented')
92
93 def apply(self, headers, token=None):
94 """Apply the token to the authentication header.
95
96 Args:
97 headers (Mapping): The HTTP request headers.
98 token (Optional[str]): If specified, overrides the current access
99 token.
100 """
101 headers['authorization'] = 'Bearer {}'.format(
102 _helpers.from_bytes(token or self.token))
103
104 def before_request(self, request, method, url, headers):
105 """Performs credential-specific before request logic.
106
107 Refreshes the credentials if necessary, then calls :meth:`apply` to
108 apply the token to the authentication header.
109
110 Args:
Jon Wayne Parrotta0425492016-10-17 10:48:35 -0700111 request (google.auth.transport.Request): The object used to make
Jon Wayne Parrott71ce2a02016-10-14 14:08:10 -0700112 HTTP requests.
Jon Wayne Parrotta2098192017-02-22 09:27:32 -0800113 method (str): The request's HTTP method or the RPC method being
114 invoked.
115 url (str): The request's URI or the RPC service's URI.
Jon Wayne Parrott71ce2a02016-10-14 14:08:10 -0700116 headers (Mapping): The request's headers.
117 """
118 # pylint: disable=unused-argument
119 # (Subclasses may use these arguments to ascertain information about
120 # the http request.)
121 if not self.valid:
122 self.refresh(request)
123 self.apply(headers)
124
125
Tres Seaverb096a3d2017-10-30 16:12:37 -0400126class AnonymousCredentials(Credentials):
127 """Credentials that do not provide any authentication information.
128
129 These are useful in the case of services that support anonymous access or
130 local service emulators that do not use credentials.
131 """
132
133 @property
134 def expired(self):
135 """Returns `False`, anonymous credentials never expire."""
136 return False
137
138 @property
139 def valid(self):
140 """Returns `True`, anonymous credentials are always valid."""
141 return True
142
143 def refresh(self, request):
144 """Raises :class:`ValueError``, anonymous credentials cannot be
145 refreshed."""
146 raise ValueError("Anonymous credentials cannot be refreshed.")
147
148 def apply(self, headers, token=None):
149 """Anonymous credentials do nothing to the request.
150
151 The optional ``token`` argument is not supported.
152
153 Raises:
154 ValueError: If a token was specified.
155 """
156 if token is not None:
157 raise ValueError("Anonymous credentials don't support tokens.")
158
159 def before_request(self, request, method, url, headers):
160 """Anonymous credentials do nothing to the request."""
161
162
Jon Wayne Parrott71ce2a02016-10-14 14:08:10 -0700163@six.add_metaclass(abc.ABCMeta)
Jon Wayne Parrott4460a962017-09-12 10:01:23 -0700164class ReadOnlyScoped(object):
Tres Seaver42468322017-09-11 15:36:53 -0400165 """Interface for credentials whose scopes can be queried.
Jon Wayne Parrott71ce2a02016-10-14 14:08:10 -0700166
167 OAuth 2.0-based credentials allow limiting access using scopes as described
168 in `RFC6749 Section 3.3`_.
169 If a credential class implements this interface then the credentials either
170 use scopes in their implementation.
171
172 Some credentials require scopes in order to obtain a token. You can check
173 if scoping is necessary with :attr:`requires_scopes`::
174
175 if credentials.requires_scopes:
176 # Scoping is required.
Ondrej Medekf682cb22017-11-27 18:33:46 +0100177 credentials = credentials.with_scopes(scopes=['one', 'two'])
Jon Wayne Parrott71ce2a02016-10-14 14:08:10 -0700178
179 Credentials that require scopes must either be constructed with scopes::
180
181 credentials = SomeScopedCredentials(scopes=['one', 'two'])
182
183 Or must copy an existing instance using :meth:`with_scopes`::
184
185 scoped_credentials = credentials.with_scopes(scopes=['one', 'two'])
186
187 Some credentials have scopes but do not allow or require scopes to be set,
188 these credentials can be used as-is.
189
190 .. _RFC6749 Section 3.3: https://tools.ietf.org/html/rfc6749#section-3.3
191 """
192 def __init__(self):
Jon Wayne Parrott4460a962017-09-12 10:01:23 -0700193 super(ReadOnlyScoped, self).__init__()
Jon Wayne Parrott71ce2a02016-10-14 14:08:10 -0700194 self._scopes = None
195
196 @property
197 def scopes(self):
198 """Sequence[str]: the credentials' current set of scopes."""
199 return self._scopes
200
201 @abc.abstractproperty
202 def requires_scopes(self):
203 """True if these credentials require scopes to obtain an access token.
204 """
205 return False
206
Tres Seaver42468322017-09-11 15:36:53 -0400207 def has_scopes(self, scopes):
208 """Checks if the credentials have the given scopes.
209
210 .. warning: This method is not guaranteed to be accurate if the
211 credentials are :attr:`~Credentials.invalid`.
212
Danny Hermes369e2a72017-12-13 12:08:15 -0800213 Args:
214 scopes (Sequence[str]): The list of scopes to check.
215
Tres Seaver42468322017-09-11 15:36:53 -0400216 Returns:
217 bool: True if the credentials have the given scopes.
218 """
219 return set(scopes).issubset(set(self._scopes or []))
220
221
Jon Wayne Parrott4460a962017-09-12 10:01:23 -0700222class Scoped(ReadOnlyScoped):
Tres Seaver42468322017-09-11 15:36:53 -0400223 """Interface for credentials whose scopes can be replaced while copying.
224
225 OAuth 2.0-based credentials allow limiting access using scopes as described
226 in `RFC6749 Section 3.3`_.
227 If a credential class implements this interface then the credentials either
228 use scopes in their implementation.
229
230 Some credentials require scopes in order to obtain a token. You can check
231 if scoping is necessary with :attr:`requires_scopes`::
232
233 if credentials.requires_scopes:
234 # Scoping is required.
235 credentials = credentials.create_scoped(['one', 'two'])
236
237 Credentials that require scopes must either be constructed with scopes::
238
239 credentials = SomeScopedCredentials(scopes=['one', 'two'])
240
241 Or must copy an existing instance using :meth:`with_scopes`::
242
243 scoped_credentials = credentials.with_scopes(scopes=['one', 'two'])
244
245 Some credentials have scopes but do not allow or require scopes to be set,
246 these credentials can be used as-is.
247
248 .. _RFC6749 Section 3.3: https://tools.ietf.org/html/rfc6749#section-3.3
249 """
Jon Wayne Parrott71ce2a02016-10-14 14:08:10 -0700250 @abc.abstractmethod
251 def with_scopes(self, scopes):
252 """Create a copy of these credentials with the specified scopes.
253
254 Args:
Danny Hermes369e2a72017-12-13 12:08:15 -0800255 scopes (Sequence[str]): The list of scopes to attach to the
256 current credentials.
Jon Wayne Parrott71ce2a02016-10-14 14:08:10 -0700257
258 Raises:
259 NotImplementedError: If the credentials' scopes can not be changed.
260 This can be avoided by checking :attr:`requires_scopes` before
261 calling this method.
262 """
263 raise NotImplementedError('This class does not require scoping.')
264
Jon Wayne Parrott71ce2a02016-10-14 14:08:10 -0700265
Jon Wayne Parrottf89a3cf2016-10-31 10:52:57 -0700266def with_scopes_if_required(credentials, scopes):
267 """Creates a copy of the credentials with scopes if scoping is required.
268
269 This helper function is useful when you do not know (or care to know) the
270 specific type of credentials you are using (such as when you use
271 :func:`google.auth.default`). This function will call
272 :meth:`Scoped.with_scopes` if the credentials are scoped credentials and if
273 the credentials require scoping. Otherwise, it will return the credentials
274 as-is.
275
276 Args:
Jon Wayne Parrottbdbf2b12016-11-10 15:00:29 -0800277 credentials (google.auth.credentials.Credentials): The credentials to
Jon Wayne Parrott8c3a10b2016-11-10 12:42:50 -0800278 scope if necessary.
Jon Wayne Parrottf89a3cf2016-10-31 10:52:57 -0700279 scopes (Sequence[str]): The list of scopes to use.
280
281 Returns:
Jon Wayne Parrottbdbf2b12016-11-10 15:00:29 -0800282 google.auth.credentials.Credentials: Either a new set of scoped
Jon Wayne Parrott8c3a10b2016-11-10 12:42:50 -0800283 credentials, or the passed in credentials instance if no scoping
284 was required.
Jon Wayne Parrottf89a3cf2016-10-31 10:52:57 -0700285 """
286 if isinstance(credentials, Scoped) and credentials.requires_scopes:
287 return credentials.with_scopes(scopes)
288 else:
289 return credentials
290
291
Jon Wayne Parrott71ce2a02016-10-14 14:08:10 -0700292@six.add_metaclass(abc.ABCMeta)
293class Signing(object):
294 """Interface for credentials that can cryptographically sign messages."""
295
296 @abc.abstractmethod
297 def sign_bytes(self, message):
298 """Signs the given message.
299
300 Args:
301 message (bytes): The message to sign.
302
303 Returns:
304 bytes: The message's cryptographic signature.
305 """
306 # pylint: disable=missing-raises-doc,redundant-returns-doc
307 # (pylint doesn't recognize that this is abstract)
308 raise NotImplementedError('Sign bytes must be implemented.')
Jon Wayne Parrott4c883f02016-12-02 14:26:33 -0800309
310 @abc.abstractproperty
311 def signer_email(self):
312 """Optional[str]: An email address that identifies the signer."""
313 # pylint: disable=missing-raises-doc
314 # (pylint doesn't recognize that this is abstract)
315 raise NotImplementedError('Signer email must be implemented.')
Jon Wayne Parrottd7221672017-02-16 09:05:11 -0800316
317 @abc.abstractproperty
318 def signer(self):
319 """google.auth.crypt.Signer: The signer used to sign bytes."""
320 # pylint: disable=missing-raises-doc
321 # (pylint doesn't recognize that this is abstract)
322 raise NotImplementedError('Signer must be implemented.')