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