C.J. Collier | 37141e4 | 2020-02-13 13:49:49 -0800 | [diff] [blame] | 1 | # Copyright 2016 Google LLC |
Jon Wayne Parrott | 71ce2a0 | 2016-10-14 14:08:10 -0700 | [diff] [blame] | 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 | |
| 18 | import abc |
| 19 | |
| 20 | import six |
| 21 | |
| 22 | from google.auth import _helpers |
| 23 | |
| 24 | |
| 25 | @six.add_metaclass(abc.ABCMeta) |
| 26 | class 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 Kim | 9eec091 | 2019-10-21 17:04:21 -0700 | [diff] [blame] | 44 | |
Jon Wayne Parrott | 71ce2a0 | 2016-10-14 14:08:10 -0700 | [diff] [blame] | 45 | 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 Kim | 3dda7b2 | 2020-07-09 10:39:39 -0700 | [diff] [blame] | 52 | self._quota_project_id = None |
| 53 | """Optional[str]: Project to use for quota and billing purposes.""" |
Jon Wayne Parrott | 71ce2a0 | 2016-10-14 14:08:10 -0700 | [diff] [blame] | 54 | |
| 55 | @property |
| 56 | def expired(self): |
| 57 | """Checks if the credentials are expired. |
| 58 | |
Craig Citro | 2f5cb2d | 2018-05-14 23:29:46 -0700 | [diff] [blame] | 59 | 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 Parrott | 71ce2a0 | 2016-10-14 14:08:10 -0700 | [diff] [blame] | 62 | """ |
Jon Wayne Parrott | 7af9f66 | 2017-05-08 09:40:56 -0700 | [diff] [blame] | 63 | 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 Parrott | 71ce2a0 | 2016-10-14 14:08:10 -0700 | [diff] [blame] | 70 | |
| 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 Kim | 3dda7b2 | 2020-07-09 10:39:39 -0700 | [diff] [blame] | 80 | @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 Parrott | 71ce2a0 | 2016-10-14 14:08:10 -0700 | [diff] [blame] | 85 | @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 Kim | 9eec091 | 2019-10-21 17:04:21 -0700 | [diff] [blame] | 99 | raise NotImplementedError("Refresh must be implemented") |
Jon Wayne Parrott | 71ce2a0 | 2016-10-14 14:08:10 -0700 | [diff] [blame] | 100 | |
| 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 Kim | 9eec091 | 2019-10-21 17:04:21 -0700 | [diff] [blame] | 109 | headers["authorization"] = "Bearer {}".format( |
| 110 | _helpers.from_bytes(token or self.token) |
| 111 | ) |
Bu Sun Kim | 3dda7b2 | 2020-07-09 10:39:39 -0700 | [diff] [blame] | 112 | if self.quota_project_id: |
| 113 | headers["x-goog-user-project"] = self.quota_project_id |
Jon Wayne Parrott | 71ce2a0 | 2016-10-14 14:08:10 -0700 | [diff] [blame] | 114 | |
| 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 Parrott | a042549 | 2016-10-17 10:48:35 -0700 | [diff] [blame] | 122 | request (google.auth.transport.Request): The object used to make |
Jon Wayne Parrott | 71ce2a0 | 2016-10-14 14:08:10 -0700 | [diff] [blame] | 123 | HTTP requests. |
Jon Wayne Parrott | a209819 | 2017-02-22 09:27:32 -0800 | [diff] [blame] | 124 | 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 Parrott | 71ce2a0 | 2016-10-14 14:08:10 -0700 | [diff] [blame] | 127 | 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 Kim | 41599ae | 2020-09-02 12:55:42 -0600 | [diff] [blame^] | 136 | |
| 137 | class CredentialsWithQuotaProject(Credentials): |
| 138 | """Abstract base for credentials supporting ``with_quota_project`` factory""" |
| 139 | |
Bu Sun Kim | 3dda7b2 | 2020-07-09 10:39:39 -0700 | [diff] [blame] | 140 | 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 Kim | 41599ae | 2020-09-02 12:55:42 -0600 | [diff] [blame^] | 150 | raise NotImplementedError("This credential does not support quota project.") |
Bu Sun Kim | 3dda7b2 | 2020-07-09 10:39:39 -0700 | [diff] [blame] | 151 | |
Jon Wayne Parrott | 71ce2a0 | 2016-10-14 14:08:10 -0700 | [diff] [blame] | 152 | |
Tres Seaver | b096a3d | 2017-10-30 16:12:37 -0400 | [diff] [blame] | 153 | class 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 Parrott | 71ce2a0 | 2016-10-14 14:08:10 -0700 | [diff] [blame] | 190 | @six.add_metaclass(abc.ABCMeta) |
Jon Wayne Parrott | 4460a96 | 2017-09-12 10:01:23 -0700 | [diff] [blame] | 191 | class ReadOnlyScoped(object): |
Tres Seaver | 4246832 | 2017-09-11 15:36:53 -0400 | [diff] [blame] | 192 | """Interface for credentials whose scopes can be queried. |
Jon Wayne Parrott | 71ce2a0 | 2016-10-14 14:08:10 -0700 | [diff] [blame] | 193 | |
| 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 Medek | f682cb2 | 2017-11-27 18:33:46 +0100 | [diff] [blame] | 204 | credentials = credentials.with_scopes(scopes=['one', 'two']) |
Jon Wayne Parrott | 71ce2a0 | 2016-10-14 14:08:10 -0700 | [diff] [blame] | 205 | |
| 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 Kim | 9eec091 | 2019-10-21 17:04:21 -0700 | [diff] [blame] | 219 | |
Jon Wayne Parrott | 71ce2a0 | 2016-10-14 14:08:10 -0700 | [diff] [blame] | 220 | def __init__(self): |
Jon Wayne Parrott | 4460a96 | 2017-09-12 10:01:23 -0700 | [diff] [blame] | 221 | super(ReadOnlyScoped, self).__init__() |
Jon Wayne Parrott | 71ce2a0 | 2016-10-14 14:08:10 -0700 | [diff] [blame] | 222 | 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 Seaver | 4246832 | 2017-09-11 15:36:53 -0400 | [diff] [blame] | 235 | 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 Hermes | 369e2a7 | 2017-12-13 12:08:15 -0800 | [diff] [blame] | 241 | Args: |
| 242 | scopes (Sequence[str]): The list of scopes to check. |
| 243 | |
Tres Seaver | 4246832 | 2017-09-11 15:36:53 -0400 | [diff] [blame] | 244 | 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 Parrott | 4460a96 | 2017-09-12 10:01:23 -0700 | [diff] [blame] | 250 | class Scoped(ReadOnlyScoped): |
Tres Seaver | 4246832 | 2017-09-11 15:36:53 -0400 | [diff] [blame] | 251 | """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 Kim | 9eec091 | 2019-10-21 17:04:21 -0700 | [diff] [blame] | 278 | |
Jon Wayne Parrott | 71ce2a0 | 2016-10-14 14:08:10 -0700 | [diff] [blame] | 279 | @abc.abstractmethod |
| 280 | def with_scopes(self, scopes): |
| 281 | """Create a copy of these credentials with the specified scopes. |
| 282 | |
| 283 | Args: |
Danny Hermes | 369e2a7 | 2017-12-13 12:08:15 -0800 | [diff] [blame] | 284 | scopes (Sequence[str]): The list of scopes to attach to the |
| 285 | current credentials. |
Jon Wayne Parrott | 71ce2a0 | 2016-10-14 14:08:10 -0700 | [diff] [blame] | 286 | |
| 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 Kim | 9eec091 | 2019-10-21 17:04:21 -0700 | [diff] [blame] | 292 | raise NotImplementedError("This class does not require scoping.") |
Jon Wayne Parrott | 71ce2a0 | 2016-10-14 14:08:10 -0700 | [diff] [blame] | 293 | |
Jon Wayne Parrott | 71ce2a0 | 2016-10-14 14:08:10 -0700 | [diff] [blame] | 294 | |
Jon Wayne Parrott | f89a3cf | 2016-10-31 10:52:57 -0700 | [diff] [blame] | 295 | def 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 Parrott | bdbf2b1 | 2016-11-10 15:00:29 -0800 | [diff] [blame] | 306 | credentials (google.auth.credentials.Credentials): The credentials to |
Jon Wayne Parrott | 8c3a10b | 2016-11-10 12:42:50 -0800 | [diff] [blame] | 307 | scope if necessary. |
Jon Wayne Parrott | f89a3cf | 2016-10-31 10:52:57 -0700 | [diff] [blame] | 308 | scopes (Sequence[str]): The list of scopes to use. |
| 309 | |
| 310 | Returns: |
Jon Wayne Parrott | bdbf2b1 | 2016-11-10 15:00:29 -0800 | [diff] [blame] | 311 | google.auth.credentials.Credentials: Either a new set of scoped |
Jon Wayne Parrott | 8c3a10b | 2016-11-10 12:42:50 -0800 | [diff] [blame] | 312 | credentials, or the passed in credentials instance if no scoping |
| 313 | was required. |
Jon Wayne Parrott | f89a3cf | 2016-10-31 10:52:57 -0700 | [diff] [blame] | 314 | """ |
| 315 | if isinstance(credentials, Scoped) and credentials.requires_scopes: |
| 316 | return credentials.with_scopes(scopes) |
| 317 | else: |
| 318 | return credentials |
| 319 | |
| 320 | |
Jon Wayne Parrott | 71ce2a0 | 2016-10-14 14:08:10 -0700 | [diff] [blame] | 321 | @six.add_metaclass(abc.ABCMeta) |
| 322 | class 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 Kim | 9eec091 | 2019-10-21 17:04:21 -0700 | [diff] [blame] | 337 | raise NotImplementedError("Sign bytes must be implemented.") |
Jon Wayne Parrott | 4c883f0 | 2016-12-02 14:26:33 -0800 | [diff] [blame] | 338 | |
| 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 Kim | 9eec091 | 2019-10-21 17:04:21 -0700 | [diff] [blame] | 344 | raise NotImplementedError("Signer email must be implemented.") |
Jon Wayne Parrott | d722167 | 2017-02-16 09:05:11 -0800 | [diff] [blame] | 345 | |
| 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 Kim | 9eec091 | 2019-10-21 17:04:21 -0700 | [diff] [blame] | 351 | raise NotImplementedError("Signer must be implemented.") |