blob: 3f389b1713ffe903d43abac52cbda4ce17cbc89b [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 Kim3dda7b22020-07-09 10:39:39 -0700136 def with_quota_project(self, quota_project_id):
137 """Returns a copy of these credentials with a modified quota project
138
139 Args:
140 quota_project_id (str): The project to use for quota and
141 billing purposes
142
143 Returns:
144 google.oauth2.credentials.Credentials: A new credentials instance.
145 """
146 raise NotImplementedError("This class does not support quota project.")
147
Jon Wayne Parrott71ce2a02016-10-14 14:08:10 -0700148
Tres Seaverb096a3d2017-10-30 16:12:37 -0400149class AnonymousCredentials(Credentials):
150 """Credentials that do not provide any authentication information.
151
152 These are useful in the case of services that support anonymous access or
153 local service emulators that do not use credentials.
154 """
155
156 @property
157 def expired(self):
158 """Returns `False`, anonymous credentials never expire."""
159 return False
160
161 @property
162 def valid(self):
163 """Returns `True`, anonymous credentials are always valid."""
164 return True
165
166 def refresh(self, request):
167 """Raises :class:`ValueError``, anonymous credentials cannot be
168 refreshed."""
169 raise ValueError("Anonymous credentials cannot be refreshed.")
170
171 def apply(self, headers, token=None):
172 """Anonymous credentials do nothing to the request.
173
174 The optional ``token`` argument is not supported.
175
176 Raises:
177 ValueError: If a token was specified.
178 """
179 if token is not None:
180 raise ValueError("Anonymous credentials don't support tokens.")
181
182 def before_request(self, request, method, url, headers):
183 """Anonymous credentials do nothing to the request."""
184
Bu Sun Kim3dda7b22020-07-09 10:39:39 -0700185 def with_quota_project(self, quota_project_id):
186 raise ValueError("Anonymous credentials don't support quota project.")
187
Tres Seaverb096a3d2017-10-30 16:12:37 -0400188
Jon Wayne Parrott71ce2a02016-10-14 14:08:10 -0700189@six.add_metaclass(abc.ABCMeta)
Jon Wayne Parrott4460a962017-09-12 10:01:23 -0700190class ReadOnlyScoped(object):
Tres Seaver42468322017-09-11 15:36:53 -0400191 """Interface for credentials whose scopes can be queried.
Jon Wayne Parrott71ce2a02016-10-14 14:08:10 -0700192
193 OAuth 2.0-based credentials allow limiting access using scopes as described
194 in `RFC6749 Section 3.3`_.
195 If a credential class implements this interface then the credentials either
196 use scopes in their implementation.
197
198 Some credentials require scopes in order to obtain a token. You can check
199 if scoping is necessary with :attr:`requires_scopes`::
200
201 if credentials.requires_scopes:
202 # Scoping is required.
Ondrej Medekf682cb22017-11-27 18:33:46 +0100203 credentials = credentials.with_scopes(scopes=['one', 'two'])
Jon Wayne Parrott71ce2a02016-10-14 14:08:10 -0700204
205 Credentials that require scopes must either be constructed with scopes::
206
207 credentials = SomeScopedCredentials(scopes=['one', 'two'])
208
209 Or must copy an existing instance using :meth:`with_scopes`::
210
211 scoped_credentials = credentials.with_scopes(scopes=['one', 'two'])
212
213 Some credentials have scopes but do not allow or require scopes to be set,
214 these credentials can be used as-is.
215
216 .. _RFC6749 Section 3.3: https://tools.ietf.org/html/rfc6749#section-3.3
217 """
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700218
Jon Wayne Parrott71ce2a02016-10-14 14:08:10 -0700219 def __init__(self):
Jon Wayne Parrott4460a962017-09-12 10:01:23 -0700220 super(ReadOnlyScoped, self).__init__()
Jon Wayne Parrott71ce2a02016-10-14 14:08:10 -0700221 self._scopes = None
222
223 @property
224 def scopes(self):
225 """Sequence[str]: the credentials' current set of scopes."""
226 return self._scopes
227
228 @abc.abstractproperty
229 def requires_scopes(self):
230 """True if these credentials require scopes to obtain an access token.
231 """
232 return False
233
Tres Seaver42468322017-09-11 15:36:53 -0400234 def has_scopes(self, scopes):
235 """Checks if the credentials have the given scopes.
236
237 .. warning: This method is not guaranteed to be accurate if the
238 credentials are :attr:`~Credentials.invalid`.
239
Danny Hermes369e2a72017-12-13 12:08:15 -0800240 Args:
241 scopes (Sequence[str]): The list of scopes to check.
242
Tres Seaver42468322017-09-11 15:36:53 -0400243 Returns:
244 bool: True if the credentials have the given scopes.
245 """
246 return set(scopes).issubset(set(self._scopes or []))
247
248
Jon Wayne Parrott4460a962017-09-12 10:01:23 -0700249class Scoped(ReadOnlyScoped):
Tres Seaver42468322017-09-11 15:36:53 -0400250 """Interface for credentials whose scopes can be replaced while copying.
251
252 OAuth 2.0-based credentials allow limiting access using scopes as described
253 in `RFC6749 Section 3.3`_.
254 If a credential class implements this interface then the credentials either
255 use scopes in their implementation.
256
257 Some credentials require scopes in order to obtain a token. You can check
258 if scoping is necessary with :attr:`requires_scopes`::
259
260 if credentials.requires_scopes:
261 # Scoping is required.
262 credentials = credentials.create_scoped(['one', 'two'])
263
264 Credentials that require scopes must either be constructed with scopes::
265
266 credentials = SomeScopedCredentials(scopes=['one', 'two'])
267
268 Or must copy an existing instance using :meth:`with_scopes`::
269
270 scoped_credentials = credentials.with_scopes(scopes=['one', 'two'])
271
272 Some credentials have scopes but do not allow or require scopes to be set,
273 these credentials can be used as-is.
274
275 .. _RFC6749 Section 3.3: https://tools.ietf.org/html/rfc6749#section-3.3
276 """
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700277
Jon Wayne Parrott71ce2a02016-10-14 14:08:10 -0700278 @abc.abstractmethod
279 def with_scopes(self, scopes):
280 """Create a copy of these credentials with the specified scopes.
281
282 Args:
Danny Hermes369e2a72017-12-13 12:08:15 -0800283 scopes (Sequence[str]): The list of scopes to attach to the
284 current credentials.
Jon Wayne Parrott71ce2a02016-10-14 14:08:10 -0700285
286 Raises:
287 NotImplementedError: If the credentials' scopes can not be changed.
288 This can be avoided by checking :attr:`requires_scopes` before
289 calling this method.
290 """
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700291 raise NotImplementedError("This class does not require scoping.")
Jon Wayne Parrott71ce2a02016-10-14 14:08:10 -0700292
Jon Wayne Parrott71ce2a02016-10-14 14:08:10 -0700293
Jon Wayne Parrottf89a3cf2016-10-31 10:52:57 -0700294def with_scopes_if_required(credentials, scopes):
295 """Creates a copy of the credentials with scopes if scoping is required.
296
297 This helper function is useful when you do not know (or care to know) the
298 specific type of credentials you are using (such as when you use
299 :func:`google.auth.default`). This function will call
300 :meth:`Scoped.with_scopes` if the credentials are scoped credentials and if
301 the credentials require scoping. Otherwise, it will return the credentials
302 as-is.
303
304 Args:
Jon Wayne Parrottbdbf2b12016-11-10 15:00:29 -0800305 credentials (google.auth.credentials.Credentials): The credentials to
Jon Wayne Parrott8c3a10b2016-11-10 12:42:50 -0800306 scope if necessary.
Jon Wayne Parrottf89a3cf2016-10-31 10:52:57 -0700307 scopes (Sequence[str]): The list of scopes to use.
308
309 Returns:
Jon Wayne Parrottbdbf2b12016-11-10 15:00:29 -0800310 google.auth.credentials.Credentials: Either a new set of scoped
Jon Wayne Parrott8c3a10b2016-11-10 12:42:50 -0800311 credentials, or the passed in credentials instance if no scoping
312 was required.
Jon Wayne Parrottf89a3cf2016-10-31 10:52:57 -0700313 """
314 if isinstance(credentials, Scoped) and credentials.requires_scopes:
315 return credentials.with_scopes(scopes)
316 else:
317 return credentials
318
319
Jon Wayne Parrott71ce2a02016-10-14 14:08:10 -0700320@six.add_metaclass(abc.ABCMeta)
321class Signing(object):
322 """Interface for credentials that can cryptographically sign messages."""
323
324 @abc.abstractmethod
325 def sign_bytes(self, message):
326 """Signs the given message.
327
328 Args:
329 message (bytes): The message to sign.
330
331 Returns:
332 bytes: The message's cryptographic signature.
333 """
334 # pylint: disable=missing-raises-doc,redundant-returns-doc
335 # (pylint doesn't recognize that this is abstract)
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700336 raise NotImplementedError("Sign bytes must be implemented.")
Jon Wayne Parrott4c883f02016-12-02 14:26:33 -0800337
338 @abc.abstractproperty
339 def signer_email(self):
340 """Optional[str]: An email address that identifies the signer."""
341 # pylint: disable=missing-raises-doc
342 # (pylint doesn't recognize that this is abstract)
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700343 raise NotImplementedError("Signer email must be implemented.")
Jon Wayne Parrottd7221672017-02-16 09:05:11 -0800344
345 @abc.abstractproperty
346 def signer(self):
347 """google.auth.crypt.Signer: The signer used to sign bytes."""
348 # pylint: disable=missing-raises-doc
349 # (pylint doesn't recognize that this is abstract)
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700350 raise NotImplementedError("Signer must be implemented.")