Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/google/auth/credentials.py: 55%

Shortcuts on this page

r m x   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

141 statements  

1# Copyright 2016 Google LLC 

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 

19from enum import Enum 

20import os 

21 

22from google.auth import _helpers, environment_vars 

23from google.auth import exceptions 

24from google.auth import metrics 

25from google.auth._refresh_worker import RefreshThreadManager 

26 

27DEFAULT_UNIVERSE_DOMAIN = "googleapis.com" 

28 

29 

30class Credentials(metaclass=abc.ABCMeta): 

31 """Base class for all credentials. 

32 

33 All credentials have a :attr:`token` that is used for authentication and 

34 may also optionally set an :attr:`expiry` to indicate when the token will 

35 no longer be valid. 

36 

37 Most credentials will be :attr:`invalid` until :meth:`refresh` is called. 

38 Credentials can do this automatically before the first HTTP request in 

39 :meth:`before_request`. 

40 

41 Although the token and expiration will change as the credentials are 

42 :meth:`refreshed <refresh>` and used, credentials should be considered 

43 immutable. Various credentials will accept configuration such as private 

44 keys, scopes, and other options. These options are not changeable after 

45 construction. Some classes will provide mechanisms to copy the credentials 

46 with modifications such as :meth:`ScopedCredentials.with_scopes`. 

47 """ 

48 

49 def __init__(self): 

50 self.token = None 

51 """str: The bearer token that can be used in HTTP headers to make 

52 authenticated requests.""" 

53 self.expiry = None 

54 """Optional[datetime]: When the token expires and is no longer valid. 

55 If this is None, the token is assumed to never expire.""" 

56 self._quota_project_id = None 

57 """Optional[str]: Project to use for quota and billing purposes.""" 

58 self._trust_boundary = None 

59 """Optional[dict]: Cache of a trust boundary response which has a list 

60 of allowed regions and an encoded string representation of credentials 

61 trust boundary.""" 

62 self._universe_domain = DEFAULT_UNIVERSE_DOMAIN 

63 """Optional[str]: The universe domain value, default is googleapis.com 

64 """ 

65 

66 self._use_non_blocking_refresh = False 

67 self._refresh_worker = RefreshThreadManager() 

68 

69 @property 

70 def expired(self): 

71 """Checks if the credentials are expired. 

72 

73 Note that credentials can be invalid but not expired because 

74 Credentials with :attr:`expiry` set to None is considered to never 

75 expire. 

76 

77 .. deprecated:: v2.24.0 

78 Prefer checking :attr:`token_state` instead. 

79 """ 

80 if not self.expiry: 

81 return False 

82 # Remove some threshold from expiry to err on the side of reporting 

83 # expiration early so that we avoid the 401-refresh-retry loop. 

84 skewed_expiry = self.expiry - _helpers.REFRESH_THRESHOLD 

85 return _helpers.utcnow() >= skewed_expiry 

86 

87 @property 

88 def valid(self): 

89 """Checks the validity of the credentials. 

90 

91 This is True if the credentials have a :attr:`token` and the token 

92 is not :attr:`expired`. 

93 

94 .. deprecated:: v2.24.0 

95 Prefer checking :attr:`token_state` instead. 

96 """ 

97 return self.token is not None and not self.expired 

98 

99 @property 

100 def token_state(self): 

101 """ 

102 See `:obj:`TokenState` 

103 """ 

104 if self.token is None: 

105 return TokenState.INVALID 

106 

107 # Credentials that can't expire are always treated as fresh. 

108 if self.expiry is None: 

109 return TokenState.FRESH 

110 

111 expired = _helpers.utcnow() >= self.expiry 

112 if expired: 

113 return TokenState.INVALID 

114 

115 is_stale = _helpers.utcnow() >= (self.expiry - _helpers.REFRESH_THRESHOLD) 

116 if is_stale: 

117 return TokenState.STALE 

118 

119 return TokenState.FRESH 

120 

121 @property 

122 def quota_project_id(self): 

123 """Project to use for quota and billing purposes.""" 

124 return self._quota_project_id 

125 

126 @property 

127 def universe_domain(self): 

128 """The universe domain value.""" 

129 return self._universe_domain 

130 

131 @abc.abstractmethod 

132 def refresh(self, request): 

133 """Refreshes the access token. 

134 

135 Args: 

136 request (google.auth.transport.Request): The object used to make 

137 HTTP requests. 

138 

139 Raises: 

140 google.auth.exceptions.RefreshError: If the credentials could 

141 not be refreshed. 

142 """ 

143 # pylint: disable=missing-raises-doc 

144 # (pylint doesn't recognize that this is abstract) 

145 raise NotImplementedError("Refresh must be implemented") 

146 

147 def _metric_header_for_usage(self): 

148 """The x-goog-api-client header for token usage metric. 

149 

150 This header will be added to the API service requests in before_request 

151 method. For example, "cred-type/sa-jwt" means service account self 

152 signed jwt access token is used in the API service request 

153 authorization header. Children credentials classes need to override 

154 this method to provide the header value, if the token usage metric is 

155 needed. 

156 

157 Returns: 

158 str: The x-goog-api-client header value. 

159 """ 

160 return None 

161 

162 def apply(self, headers, token=None): 

163 """Apply the token to the authentication header. 

164 

165 Args: 

166 headers (Mapping): The HTTP request headers. 

167 token (Optional[str]): If specified, overrides the current access 

168 token. 

169 """ 

170 headers["authorization"] = "Bearer {}".format( 

171 _helpers.from_bytes(token or self.token) 

172 ) 

173 """Trust boundary value will be a cached value from global lookup. 

174 

175 The response of trust boundary will be a list of regions and a hex 

176 encoded representation. 

177 

178 An example of global lookup response: 

179 { 

180 "locations": [ 

181 "us-central1", "us-east1", "europe-west1", "asia-east1" 

182 ] 

183 "encoded_locations": "0xA30" 

184 } 

185 """ 

186 if self._trust_boundary is not None: 

187 headers["x-allowed-locations"] = self._trust_boundary["encoded_locations"] 

188 if self.quota_project_id: 

189 headers["x-goog-user-project"] = self.quota_project_id 

190 

191 def _blocking_refresh(self, request): 

192 if not self.valid: 

193 self.refresh(request) 

194 

195 def _non_blocking_refresh(self, request): 

196 use_blocking_refresh_fallback = False 

197 

198 if self.token_state == TokenState.STALE: 

199 use_blocking_refresh_fallback = not self._refresh_worker.start_refresh( 

200 self, request 

201 ) 

202 

203 if self.token_state == TokenState.INVALID or use_blocking_refresh_fallback: 

204 self.refresh(request) 

205 # If the blocking refresh succeeds then we can clear the error info 

206 # on the background refresh worker, and perform refreshes in a 

207 # background thread. 

208 self._refresh_worker.clear_error() 

209 

210 def before_request(self, request, method, url, headers): 

211 """Performs credential-specific before request logic. 

212 

213 Refreshes the credentials if necessary, then calls :meth:`apply` to 

214 apply the token to the authentication header. 

215 

216 Args: 

217 request (google.auth.transport.Request): The object used to make 

218 HTTP requests. 

219 method (str): The request's HTTP method or the RPC method being 

220 invoked. 

221 url (str): The request's URI or the RPC service's URI. 

222 headers (Mapping): The request's headers. 

223 """ 

224 # pylint: disable=unused-argument 

225 # (Subclasses may use these arguments to ascertain information about 

226 # the http request.) 

227 if self._use_non_blocking_refresh: 

228 self._non_blocking_refresh(request) 

229 else: 

230 self._blocking_refresh(request) 

231 

232 metrics.add_metric_header(headers, self._metric_header_for_usage()) 

233 self.apply(headers) 

234 

235 def with_non_blocking_refresh(self): 

236 self._use_non_blocking_refresh = True 

237 

238 

239class CredentialsWithQuotaProject(Credentials): 

240 """Abstract base for credentials supporting ``with_quota_project`` factory""" 

241 

242 def with_quota_project(self, quota_project_id): 

243 """Returns a copy of these credentials with a modified quota project. 

244 

245 Args: 

246 quota_project_id (str): The project to use for quota and 

247 billing purposes 

248 

249 Returns: 

250 google.auth.credentials.Credentials: A new credentials instance. 

251 """ 

252 raise NotImplementedError("This credential does not support quota project.") 

253 

254 def with_quota_project_from_environment(self): 

255 quota_from_env = os.environ.get(environment_vars.GOOGLE_CLOUD_QUOTA_PROJECT) 

256 if quota_from_env: 

257 return self.with_quota_project(quota_from_env) 

258 return self 

259 

260 

261class CredentialsWithTokenUri(Credentials): 

262 """Abstract base for credentials supporting ``with_token_uri`` factory""" 

263 

264 def with_token_uri(self, token_uri): 

265 """Returns a copy of these credentials with a modified token uri. 

266 

267 Args: 

268 token_uri (str): The uri to use for fetching/exchanging tokens 

269 

270 Returns: 

271 google.auth.credentials.Credentials: A new credentials instance. 

272 """ 

273 raise NotImplementedError("This credential does not use token uri.") 

274 

275 

276class CredentialsWithUniverseDomain(Credentials): 

277 """Abstract base for credentials supporting ``with_universe_domain`` factory""" 

278 

279 def with_universe_domain(self, universe_domain): 

280 """Returns a copy of these credentials with a modified universe domain. 

281 

282 Args: 

283 universe_domain (str): The universe domain to use 

284 

285 Returns: 

286 google.auth.credentials.Credentials: A new credentials instance. 

287 """ 

288 raise NotImplementedError( 

289 "This credential does not support with_universe_domain." 

290 ) 

291 

292 

293class AnonymousCredentials(Credentials): 

294 """Credentials that do not provide any authentication information. 

295 

296 These are useful in the case of services that support anonymous access or 

297 local service emulators that do not use credentials. 

298 """ 

299 

300 @property 

301 def expired(self): 

302 """Returns `False`, anonymous credentials never expire.""" 

303 return False 

304 

305 @property 

306 def valid(self): 

307 """Returns `True`, anonymous credentials are always valid.""" 

308 return True 

309 

310 def refresh(self, request): 

311 """Raises :class:``InvalidOperation``, anonymous credentials cannot be 

312 refreshed.""" 

313 raise exceptions.InvalidOperation("Anonymous credentials cannot be refreshed.") 

314 

315 def apply(self, headers, token=None): 

316 """Anonymous credentials do nothing to the request. 

317 

318 The optional ``token`` argument is not supported. 

319 

320 Raises: 

321 google.auth.exceptions.InvalidValue: If a token was specified. 

322 """ 

323 if token is not None: 

324 raise exceptions.InvalidValue("Anonymous credentials don't support tokens.") 

325 

326 def before_request(self, request, method, url, headers): 

327 """Anonymous credentials do nothing to the request.""" 

328 

329 

330class ReadOnlyScoped(metaclass=abc.ABCMeta): 

331 """Interface for credentials whose scopes can be queried. 

332 

333 OAuth 2.0-based credentials allow limiting access using scopes as described 

334 in `RFC6749 Section 3.3`_. 

335 If a credential class implements this interface then the credentials either 

336 use scopes in their implementation. 

337 

338 Some credentials require scopes in order to obtain a token. You can check 

339 if scoping is necessary with :attr:`requires_scopes`:: 

340 

341 if credentials.requires_scopes: 

342 # Scoping is required. 

343 credentials = credentials.with_scopes(scopes=['one', 'two']) 

344 

345 Credentials that require scopes must either be constructed with scopes:: 

346 

347 credentials = SomeScopedCredentials(scopes=['one', 'two']) 

348 

349 Or must copy an existing instance using :meth:`with_scopes`:: 

350 

351 scoped_credentials = credentials.with_scopes(scopes=['one', 'two']) 

352 

353 Some credentials have scopes but do not allow or require scopes to be set, 

354 these credentials can be used as-is. 

355 

356 .. _RFC6749 Section 3.3: https://tools.ietf.org/html/rfc6749#section-3.3 

357 """ 

358 

359 def __init__(self): 

360 super(ReadOnlyScoped, self).__init__() 

361 self._scopes = None 

362 self._default_scopes = None 

363 

364 @property 

365 def scopes(self): 

366 """Sequence[str]: the credentials' current set of scopes.""" 

367 return self._scopes 

368 

369 @property 

370 def default_scopes(self): 

371 """Sequence[str]: the credentials' current set of default scopes.""" 

372 return self._default_scopes 

373 

374 @abc.abstractproperty 

375 def requires_scopes(self): 

376 """True if these credentials require scopes to obtain an access token. 

377 """ 

378 return False 

379 

380 def has_scopes(self, scopes): 

381 """Checks if the credentials have the given scopes. 

382 

383 .. warning: This method is not guaranteed to be accurate if the 

384 credentials are :attr:`~Credentials.invalid`. 

385 

386 Args: 

387 scopes (Sequence[str]): The list of scopes to check. 

388 

389 Returns: 

390 bool: True if the credentials have the given scopes. 

391 """ 

392 credential_scopes = ( 

393 self._scopes if self._scopes is not None else self._default_scopes 

394 ) 

395 return set(scopes).issubset(set(credential_scopes or [])) 

396 

397 

398class Scoped(ReadOnlyScoped): 

399 """Interface for credentials whose scopes can be replaced while copying. 

400 

401 OAuth 2.0-based credentials allow limiting access using scopes as described 

402 in `RFC6749 Section 3.3`_. 

403 If a credential class implements this interface then the credentials either 

404 use scopes in their implementation. 

405 

406 Some credentials require scopes in order to obtain a token. You can check 

407 if scoping is necessary with :attr:`requires_scopes`:: 

408 

409 if credentials.requires_scopes: 

410 # Scoping is required. 

411 credentials = credentials.create_scoped(['one', 'two']) 

412 

413 Credentials that require scopes must either be constructed with scopes:: 

414 

415 credentials = SomeScopedCredentials(scopes=['one', 'two']) 

416 

417 Or must copy an existing instance using :meth:`with_scopes`:: 

418 

419 scoped_credentials = credentials.with_scopes(scopes=['one', 'two']) 

420 

421 Some credentials have scopes but do not allow or require scopes to be set, 

422 these credentials can be used as-is. 

423 

424 .. _RFC6749 Section 3.3: https://tools.ietf.org/html/rfc6749#section-3.3 

425 """ 

426 

427 @abc.abstractmethod 

428 def with_scopes(self, scopes, default_scopes=None): 

429 """Create a copy of these credentials with the specified scopes. 

430 

431 Args: 

432 scopes (Sequence[str]): The list of scopes to attach to the 

433 current credentials. 

434 

435 Raises: 

436 NotImplementedError: If the credentials' scopes can not be changed. 

437 This can be avoided by checking :attr:`requires_scopes` before 

438 calling this method. 

439 """ 

440 raise NotImplementedError("This class does not require scoping.") 

441 

442 

443def with_scopes_if_required(credentials, scopes, default_scopes=None): 

444 """Creates a copy of the credentials with scopes if scoping is required. 

445 

446 This helper function is useful when you do not know (or care to know) the 

447 specific type of credentials you are using (such as when you use 

448 :func:`google.auth.default`). This function will call 

449 :meth:`Scoped.with_scopes` if the credentials are scoped credentials and if 

450 the credentials require scoping. Otherwise, it will return the credentials 

451 as-is. 

452 

453 Args: 

454 credentials (google.auth.credentials.Credentials): The credentials to 

455 scope if necessary. 

456 scopes (Sequence[str]): The list of scopes to use. 

457 default_scopes (Sequence[str]): Default scopes passed by a 

458 Google client library. Use 'scopes' for user-defined scopes. 

459 

460 Returns: 

461 google.auth.credentials.Credentials: Either a new set of scoped 

462 credentials, or the passed in credentials instance if no scoping 

463 was required. 

464 """ 

465 if isinstance(credentials, Scoped) and credentials.requires_scopes: 

466 return credentials.with_scopes(scopes, default_scopes=default_scopes) 

467 else: 

468 return credentials 

469 

470 

471class Signing(metaclass=abc.ABCMeta): 

472 """Interface for credentials that can cryptographically sign messages.""" 

473 

474 @abc.abstractmethod 

475 def sign_bytes(self, message): 

476 """Signs the given message. 

477 

478 Args: 

479 message (bytes): The message to sign. 

480 

481 Returns: 

482 bytes: The message's cryptographic signature. 

483 """ 

484 # pylint: disable=missing-raises-doc,redundant-returns-doc 

485 # (pylint doesn't recognize that this is abstract) 

486 raise NotImplementedError("Sign bytes must be implemented.") 

487 

488 @abc.abstractproperty 

489 def signer_email(self): 

490 """Optional[str]: An email address that identifies the signer.""" 

491 # pylint: disable=missing-raises-doc 

492 # (pylint doesn't recognize that this is abstract) 

493 raise NotImplementedError("Signer email must be implemented.") 

494 

495 @abc.abstractproperty 

496 def signer(self): 

497 """google.auth.crypt.Signer: The signer used to sign bytes.""" 

498 # pylint: disable=missing-raises-doc 

499 # (pylint doesn't recognize that this is abstract) 

500 raise NotImplementedError("Signer must be implemented.") 

501 

502 

503class TokenState(Enum): 

504 """ 

505 Tracks the state of a token. 

506 FRESH: The token is valid. It is not expired or close to expired, or the token has no expiry. 

507 STALE: The token is close to expired, and should be refreshed. The token can be used normally. 

508 INVALID: The token is expired or invalid. The token cannot be used for a normal operation. 

509 """ 

510 

511 FRESH = 1 

512 STALE = 2 

513 INVALID = 3