blob: 892f3a88a4966f112534d7b680dfd01a3b31ce65 [file] [log] [blame]
C.J. Collier37141e42020-02-13 13:49:49 -08001# Copyright 2016 Google LLC
Jon Wayne Parrott5824ad82016-10-06 09:27:44 -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"""JSON Web Tokens
16
17Provides support for creating (encoding) and verifying (decoding) JWTs,
18especially JWTs generated and consumed by Google infrastructure.
19
20See `rfc7519`_ for more details on JWTs.
21
Jon Wayne Parrott7eeab7d2016-10-12 15:02:37 -070022To encode a JWT use :func:`encode`::
Jon Wayne Parrott5824ad82016-10-06 09:27:44 -070023
Marco Rougeth7e1270b2018-02-28 20:13:56 -030024 from google.auth import crypt
Jon Wayne Parrott5824ad82016-10-06 09:27:44 -070025 from google.auth import jwt
26
27 signer = crypt.Signer(private_key)
28 payload = {'some': 'payload'}
29 encoded = jwt.encode(signer, payload)
30
Jon Wayne Parrott7eeab7d2016-10-12 15:02:37 -070031To decode a JWT and verify claims use :func:`decode`::
Jon Wayne Parrott5824ad82016-10-06 09:27:44 -070032
33 claims = jwt.decode(encoded, certs=public_certs)
34
35You can also skip verification::
36
37 claims = jwt.decode(encoded, verify=False)
38
39.. _rfc7519: https://tools.ietf.org/html/rfc7519
40
41"""
42
Jay Leec5a33952020-01-17 11:18:47 -080043try:
44 from collections.abc import Mapping
Bu Sun Kim0ca0ee52020-01-18 00:38:49 -080045# Python 2.7 compatibility
46except ImportError: # pragma: NO COVER
Jay Leec5a33952020-01-17 11:18:47 -080047 from collections import Mapping
Jon Wayne Parrott75c78b22017-03-23 13:14:53 -070048import copy
Jon Wayne Parrottabcd3ed2016-10-17 11:23:47 -070049import datetime
Jon Wayne Parrott5824ad82016-10-06 09:27:44 -070050import json
51
Jon Wayne Parrottcfbfd252017-03-28 13:03:11 -070052import cachetools
Danny Hermes895e3692017-11-09 11:35:57 -080053import six
Jon Wayne Parrottcfbfd252017-03-28 13:03:11 -070054from six.moves import urllib
55
Jon Wayne Parrott54a85172016-10-17 11:27:37 -070056from google.auth import _helpers
Jon Wayne Parrott807032c2016-10-18 09:38:26 -070057from google.auth import _service_account_info
Jon Wayne Parrott5824ad82016-10-06 09:27:44 -070058from google.auth import crypt
Jon Wayne Parrottcfbfd252017-03-28 13:03:11 -070059from google.auth import exceptions
Jon Wayne Parrottb8f48d02017-02-24 09:03:24 -080060import google.auth.credentials
Jon Wayne Parrott5824ad82016-10-06 09:27:44 -070061
Thea Flowerse290a3d2020-04-01 10:11:42 -070062try:
63 from google.auth.crypt import es256
64except ImportError: # pragma: NO COVER
65 es256 = None
66
Jon Wayne Parrotte60c1242017-03-23 16:00:24 -070067_DEFAULT_TOKEN_LIFETIME_SECS = 3600 # 1 hour in seconds
Jon Wayne Parrottcfbfd252017-03-28 13:03:11 -070068_DEFAULT_MAX_CACHE_SIZE = 10
Thea Flowerse290a3d2020-04-01 10:11:42 -070069_ALGORITHM_TO_VERIFIER_CLASS = {"RS256": crypt.RSAVerifier}
arithmetic1728866d9262020-05-05 12:53:37 -070070_CRYPTOGRAPHY_BASED_ALGORITHMS = frozenset(["ES256"])
Thea Flowerse290a3d2020-04-01 10:11:42 -070071
72if es256 is not None: # pragma: NO COVER
73 _ALGORITHM_TO_VERIFIER_CLASS["ES256"] = es256.ES256Verifier
Jon Wayne Parrott5824ad82016-10-06 09:27:44 -070074
75
76def encode(signer, payload, header=None, key_id=None):
77 """Make a signed JWT.
78
79 Args:
80 signer (google.auth.crypt.Signer): The signer used to sign the JWT.
Jon Wayne Parrott7eeab7d2016-10-12 15:02:37 -070081 payload (Mapping[str, str]): The JWT payload.
82 header (Mapping[str, str]): Additional JWT header payload.
Jon Wayne Parrott5824ad82016-10-06 09:27:44 -070083 key_id (str): The key id to add to the JWT header. If the
84 signer has a key id it will be used as the default. If this is
85 specified it will override the signer's key id.
86
87 Returns:
88 bytes: The encoded JWT.
89 """
90 if header is None:
91 header = {}
92
93 if key_id is None:
94 key_id = signer.key_id
95
Thea Flowerse290a3d2020-04-01 10:11:42 -070096 header.update({"typ": "JWT"})
97
arithmetic17280a837062021-04-08 10:58:38 -070098 if "alg" not in header:
99 if es256 is not None and isinstance(signer, es256.ES256Signer):
100 header.update({"alg": "ES256"})
101 else:
102 header.update({"alg": "RS256"})
Jon Wayne Parrott5824ad82016-10-06 09:27:44 -0700103
104 if key_id is not None:
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700105 header["kid"] = key_id
Jon Wayne Parrott5824ad82016-10-06 09:27:44 -0700106
107 segments = [
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700108 _helpers.unpadded_urlsafe_b64encode(json.dumps(header).encode("utf-8")),
109 _helpers.unpadded_urlsafe_b64encode(json.dumps(payload).encode("utf-8")),
Jon Wayne Parrott5824ad82016-10-06 09:27:44 -0700110 ]
111
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700112 signing_input = b".".join(segments)
Jon Wayne Parrott5824ad82016-10-06 09:27:44 -0700113 signature = signer.sign(signing_input)
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700114 segments.append(_helpers.unpadded_urlsafe_b64encode(signature))
Jon Wayne Parrott5824ad82016-10-06 09:27:44 -0700115
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700116 return b".".join(segments)
Jon Wayne Parrott5824ad82016-10-06 09:27:44 -0700117
118
119def _decode_jwt_segment(encoded_section):
120 """Decodes a single JWT segment."""
Jon Wayne Parrott97eb8702016-11-17 09:43:16 -0800121 section_bytes = _helpers.padded_urlsafe_b64decode(encoded_section)
Jon Wayne Parrott5824ad82016-10-06 09:27:44 -0700122 try:
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700123 return json.loads(section_bytes.decode("utf-8"))
Danny Hermes895e3692017-11-09 11:35:57 -0800124 except ValueError as caught_exc:
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700125 new_exc = ValueError("Can't parse segment: {0}".format(section_bytes))
Danny Hermes895e3692017-11-09 11:35:57 -0800126 six.raise_from(new_exc, caught_exc)
Jon Wayne Parrott5824ad82016-10-06 09:27:44 -0700127
128
129def _unverified_decode(token):
130 """Decodes a token and does no verification.
131
132 Args:
133 token (Union[str, bytes]): The encoded JWT.
134
135 Returns:
Danny Hermes48c85f72016-11-08 09:30:44 -0800136 Tuple[str, str, str, str]: header, payload, signed_section, and
Jon Wayne Parrott5824ad82016-10-06 09:27:44 -0700137 signature.
138
139 Raises:
140 ValueError: if there are an incorrect amount of segments in the token.
141 """
142 token = _helpers.to_bytes(token)
143
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700144 if token.count(b".") != 2:
145 raise ValueError("Wrong number of segments in token: {0}".format(token))
Jon Wayne Parrott5824ad82016-10-06 09:27:44 -0700146
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700147 encoded_header, encoded_payload, signature = token.split(b".")
148 signed_section = encoded_header + b"." + encoded_payload
Jon Wayne Parrott97eb8702016-11-17 09:43:16 -0800149 signature = _helpers.padded_urlsafe_b64decode(signature)
Jon Wayne Parrott5824ad82016-10-06 09:27:44 -0700150
151 # Parse segments
152 header = _decode_jwt_segment(encoded_header)
153 payload = _decode_jwt_segment(encoded_payload)
154
155 return header, payload, signed_section, signature
156
157
158def decode_header(token):
159 """Return the decoded header of a token.
160
161 No verification is done. This is useful to extract the key id from
162 the header in order to acquire the appropriate certificate to verify
163 the token.
164
165 Args:
166 token (Union[str, bytes]): the encoded JWT.
167
168 Returns:
169 Mapping: The decoded JWT header.
170 """
171 header, _, _, _ = _unverified_decode(token)
172 return header
173
174
175def _verify_iat_and_exp(payload):
Jon Wayne Parrott7eeab7d2016-10-12 15:02:37 -0700176 """Verifies the ``iat`` (Issued At) and ``exp`` (Expires) claims in a token
Jon Wayne Parrott5824ad82016-10-06 09:27:44 -0700177 payload.
178
179 Args:
Jon Wayne Parrott7eeab7d2016-10-12 15:02:37 -0700180 payload (Mapping[str, str]): The JWT payload.
Jon Wayne Parrott5824ad82016-10-06 09:27:44 -0700181
182 Raises:
183 ValueError: if any checks failed.
184 """
185 now = _helpers.datetime_to_secs(_helpers.utcnow())
186
Jon Wayne Parrotte60c1242017-03-23 16:00:24 -0700187 # Make sure the iat and exp claims are present.
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700188 for key in ("iat", "exp"):
Jon Wayne Parrott5824ad82016-10-06 09:27:44 -0700189 if key not in payload:
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700190 raise ValueError("Token does not contain required claim {}".format(key))
Jon Wayne Parrott5824ad82016-10-06 09:27:44 -0700191
Jon Wayne Parrotte60c1242017-03-23 16:00:24 -0700192 # Make sure the token wasn't issued in the future.
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700193 iat = payload["iat"]
Jon Wayne Parrotte60c1242017-03-23 16:00:24 -0700194 # Err on the side of accepting a token that is slightly early to account
195 # for clock skew.
196 earliest = iat - _helpers.CLOCK_SKEW_SECS
Jon Wayne Parrott5824ad82016-10-06 09:27:44 -0700197 if now < earliest:
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700198 raise ValueError("Token used too early, {} < {}".format(now, iat))
Jon Wayne Parrott5824ad82016-10-06 09:27:44 -0700199
Jon Wayne Parrotte60c1242017-03-23 16:00:24 -0700200 # Make sure the token wasn't issued in the past.
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700201 exp = payload["exp"]
Jon Wayne Parrotte60c1242017-03-23 16:00:24 -0700202 # Err on the side of accepting a token that is slightly out of date
203 # to account for clow skew.
204 latest = exp + _helpers.CLOCK_SKEW_SECS
Jon Wayne Parrott5824ad82016-10-06 09:27:44 -0700205 if latest < now:
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700206 raise ValueError("Token expired, {} < {}".format(latest, now))
Jon Wayne Parrott5824ad82016-10-06 09:27:44 -0700207
208
209def decode(token, certs=None, verify=True, audience=None):
210 """Decode and verify a JWT.
211
212 Args:
Jon Wayne Parrott7eeab7d2016-10-12 15:02:37 -0700213 token (str): The encoded JWT.
214 certs (Union[str, bytes, Mapping[str, Union[str, bytes]]]): The
Tianzi Cai2c6ad782019-03-29 13:49:06 -0700215 certificate used to validate the JWT signature. If bytes or string,
Jon Wayne Parrott7eeab7d2016-10-12 15:02:37 -0700216 it must the the public key certificate in PEM format. If a mapping,
217 it must be a mapping of key IDs to public key certificates in PEM
218 format. The mapping must contain the same key ID that's specified
219 in the token's header.
Jon Wayne Parrott5824ad82016-10-06 09:27:44 -0700220 verify (bool): Whether to perform signature and claim validation.
221 Verification is done by default.
Jonathan Beaulieu56c39462021-04-15 04:28:04 -0400222 audience (str or list): The audience claim, 'aud', that this JWT should
223 contain. Or a list of audience claims. If None then the JWT's 'aud'
224 parameter is not verified.
Jon Wayne Parrott5824ad82016-10-06 09:27:44 -0700225
226 Returns:
Jon Wayne Parrott7eeab7d2016-10-12 15:02:37 -0700227 Mapping[str, str]: The deserialized JSON payload in the JWT.
Jon Wayne Parrott5824ad82016-10-06 09:27:44 -0700228
229 Raises:
230 ValueError: if any verification checks failed.
231 """
232 header, payload, signed_section, signature = _unverified_decode(token)
233
234 if not verify:
235 return payload
236
Thea Flowerse290a3d2020-04-01 10:11:42 -0700237 # Pluck the key id and algorithm from the header and make sure we have
238 # a verifier that can support it.
239 key_alg = header.get("alg")
240 key_id = header.get("kid")
241
242 try:
243 verifier_cls = _ALGORITHM_TO_VERIFIER_CLASS[key_alg]
244 except KeyError as exc:
245 if key_alg in _CRYPTOGRAPHY_BASED_ALGORITHMS:
246 six.raise_from(
247 ValueError(
248 "The key algorithm {} requires the cryptography package "
249 "to be installed.".format(key_alg)
250 ),
251 exc,
252 )
253 else:
254 six.raise_from(
255 ValueError("Unsupported signature algorithm {}".format(key_alg)), exc
256 )
257
Jon Wayne Parrott5824ad82016-10-06 09:27:44 -0700258 # If certs is specified as a dictionary of key IDs to certificates, then
259 # use the certificate identified by the key ID in the token header.
Jay Leec5a33952020-01-17 11:18:47 -0800260 if isinstance(certs, Mapping):
Jon Wayne Parrott5824ad82016-10-06 09:27:44 -0700261 if key_id:
262 if key_id not in certs:
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700263 raise ValueError("Certificate for key id {} not found.".format(key_id))
Jon Wayne Parrott5824ad82016-10-06 09:27:44 -0700264 certs_to_check = [certs[key_id]]
265 # If there's no key id in the header, check against all of the certs.
266 else:
267 certs_to_check = certs.values()
268 else:
269 certs_to_check = certs
270
271 # Verify that the signature matches the message.
Thea Flowerse290a3d2020-04-01 10:11:42 -0700272 if not crypt.verify_signature(
273 signed_section, signature, certs_to_check, verifier_cls
274 ):
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700275 raise ValueError("Could not verify token signature.")
Jon Wayne Parrott5824ad82016-10-06 09:27:44 -0700276
277 # Verify the issued at and created times in the payload.
278 _verify_iat_and_exp(payload)
279
280 # Check audience.
281 if audience is not None:
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700282 claim_audience = payload.get("aud")
Jonathan Beaulieu56c39462021-04-15 04:28:04 -0400283 if isinstance(audience, str):
284 audience = [audience]
285 if claim_audience not in audience:
Jon Wayne Parrott5824ad82016-10-06 09:27:44 -0700286 raise ValueError(
Jonathan Beaulieu56c39462021-04-15 04:28:04 -0400287 "Token has wrong audience {}, expected one of {}".format(
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700288 claim_audience, audience
289 )
290 )
Jon Wayne Parrott5824ad82016-10-06 09:27:44 -0700291
292 return payload
Jon Wayne Parrottabcd3ed2016-10-17 11:23:47 -0700293
294
Bu Sun Kim41599ae2020-09-02 12:55:42 -0600295class Credentials(
296 google.auth.credentials.Signing, google.auth.credentials.CredentialsWithQuotaProject
297):
Jon Wayne Parrottabcd3ed2016-10-17 11:23:47 -0700298 """Credentials that use a JWT as the bearer token.
299
300 These credentials require an "audience" claim. This claim identifies the
Jon Wayne Parrottab086892017-02-23 09:20:14 -0800301 intended recipient of the bearer token.
Jon Wayne Parrottabcd3ed2016-10-17 11:23:47 -0700302
303 The constructor arguments determine the claims for the JWT that is
304 sent with requests. Usually, you'll construct these credentials with
305 one of the helper constructors as shown in the next section.
306
307 To create JWT credentials using a Google service account private key
308 JSON file::
309
Jon Wayne Parrottb8f48d02017-02-24 09:03:24 -0800310 audience = 'https://pubsub.googleapis.com/google.pubsub.v1.Publisher'
Jon Wayne Parrottabcd3ed2016-10-17 11:23:47 -0700311 credentials = jwt.Credentials.from_service_account_file(
Jon Wayne Parrottab086892017-02-23 09:20:14 -0800312 'service-account.json',
Jon Wayne Parrottb8f48d02017-02-24 09:03:24 -0800313 audience=audience)
Jon Wayne Parrottabcd3ed2016-10-17 11:23:47 -0700314
315 If you already have the service account file loaded and parsed::
316
317 service_account_info = json.load(open('service_account.json'))
318 credentials = jwt.Credentials.from_service_account_info(
Jon Wayne Parrottab086892017-02-23 09:20:14 -0800319 service_account_info,
Jon Wayne Parrottb8f48d02017-02-24 09:03:24 -0800320 audience=audience)
Jon Wayne Parrottabcd3ed2016-10-17 11:23:47 -0700321
322 Both helper methods pass on arguments to the constructor, so you can
323 specify the JWT claims::
324
325 credentials = jwt.Credentials.from_service_account_file(
326 'service-account.json',
Jon Wayne Parrottb8f48d02017-02-24 09:03:24 -0800327 audience=audience,
Jon Wayne Parrottabcd3ed2016-10-17 11:23:47 -0700328 additional_claims={'meta': 'data'})
329
330 You can also construct the credentials directly if you have a
331 :class:`~google.auth.crypt.Signer` instance::
332
333 credentials = jwt.Credentials(
Jon Wayne Parrottab086892017-02-23 09:20:14 -0800334 signer,
335 issuer='your-issuer',
336 subject='your-subject',
Jon Wayne Parrottb8f48d02017-02-24 09:03:24 -0800337 audience=audience)
Jon Wayne Parrottabcd3ed2016-10-17 11:23:47 -0700338
339 The claims are considered immutable. If you want to modify the claims,
340 you can easily create another instance using :meth:`with_claims`::
341
Jon Wayne Parrottb8f48d02017-02-24 09:03:24 -0800342 new_audience = (
343 'https://pubsub.googleapis.com/google.pubsub.v1.Subscriber')
344 new_credentials = credentials.with_claims(audience=new_audience)
Jon Wayne Parrottabcd3ed2016-10-17 11:23:47 -0700345 """
346
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700347 def __init__(
348 self,
349 signer,
350 issuer,
351 subject,
352 audience,
353 additional_claims=None,
354 token_lifetime=_DEFAULT_TOKEN_LIFETIME_SECS,
Bu Sun Kim3dda7b22020-07-09 10:39:39 -0700355 quota_project_id=None,
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700356 ):
Jon Wayne Parrottabcd3ed2016-10-17 11:23:47 -0700357 """
358 Args:
359 signer (google.auth.crypt.Signer): The signer used to sign JWTs.
360 issuer (str): The `iss` claim.
361 subject (str): The `sub` claim.
362 audience (str): the `aud` claim. The intended audience for the
Jon Wayne Parrottab086892017-02-23 09:20:14 -0800363 credentials.
Jon Wayne Parrottabcd3ed2016-10-17 11:23:47 -0700364 additional_claims (Mapping[str, str]): Any additional claims for
365 the JWT payload.
366 token_lifetime (int): The amount of time in seconds for
367 which the token is valid. Defaults to 1 hour.
Bu Sun Kim3dda7b22020-07-09 10:39:39 -0700368 quota_project_id (Optional[str]): The project ID used for quota
369 and billing.
Jon Wayne Parrottabcd3ed2016-10-17 11:23:47 -0700370 """
371 super(Credentials, self).__init__()
372 self._signer = signer
373 self._issuer = issuer
374 self._subject = subject
375 self._audience = audience
Jon Wayne Parrottabcd3ed2016-10-17 11:23:47 -0700376 self._token_lifetime = token_lifetime
Bu Sun Kim3dda7b22020-07-09 10:39:39 -0700377 self._quota_project_id = quota_project_id
Jon Wayne Parrottabcd3ed2016-10-17 11:23:47 -0700378
Jon Wayne Parrottcfbfd252017-03-28 13:03:11 -0700379 if additional_claims is None:
380 additional_claims = {}
381
382 self._additional_claims = additional_claims
Danny Hermes93d1aa42016-10-17 13:15:07 -0700383
Jon Wayne Parrottabcd3ed2016-10-17 11:23:47 -0700384 @classmethod
Jon Wayne Parrott807032c2016-10-18 09:38:26 -0700385 def _from_signer_and_info(cls, signer, info, **kwargs):
386 """Creates a Credentials instance from a signer and service account
387 info.
388
389 Args:
390 signer (google.auth.crypt.Signer): The signer used to sign JWTs.
391 info (Mapping[str, str]): The service account info.
392 kwargs: Additional arguments to pass to the constructor.
393
394 Returns:
395 google.auth.jwt.Credentials: The constructed credentials.
396
397 Raises:
398 ValueError: If the info is not in the expected format.
399 """
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700400 kwargs.setdefault("subject", info["client_email"])
401 kwargs.setdefault("issuer", info["client_email"])
Jon Wayne Parrottab086892017-02-23 09:20:14 -0800402 return cls(signer, **kwargs)
Jon Wayne Parrott807032c2016-10-18 09:38:26 -0700403
404 @classmethod
Jon Wayne Parrottabcd3ed2016-10-17 11:23:47 -0700405 def from_service_account_info(cls, info, **kwargs):
Jon Wayne Parrottcfbfd252017-03-28 13:03:11 -0700406 """Creates an Credentials instance from a dictionary.
Jon Wayne Parrottabcd3ed2016-10-17 11:23:47 -0700407
408 Args:
409 info (Mapping[str, str]): The service account info in Google
410 format.
411 kwargs: Additional arguments to pass to the constructor.
412
413 Returns:
414 google.auth.jwt.Credentials: The constructed credentials.
415
416 Raises:
417 ValueError: If the info is not in the expected format.
418 """
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700419 signer = _service_account_info.from_dict(info, require=["client_email"])
Jon Wayne Parrott807032c2016-10-18 09:38:26 -0700420 return cls._from_signer_and_info(signer, info, **kwargs)
Jon Wayne Parrottabcd3ed2016-10-17 11:23:47 -0700421
422 @classmethod
423 def from_service_account_file(cls, filename, **kwargs):
Jon Wayne Parrott807032c2016-10-18 09:38:26 -0700424 """Creates a Credentials instance from a service account .json file
425 in Google format.
Jon Wayne Parrottabcd3ed2016-10-17 11:23:47 -0700426
427 Args:
Jon Wayne Parrott807032c2016-10-18 09:38:26 -0700428 filename (str): The path to the service account .json file.
Jon Wayne Parrottabcd3ed2016-10-17 11:23:47 -0700429 kwargs: Additional arguments to pass to the constructor.
430
431 Returns:
432 google.auth.jwt.Credentials: The constructed credentials.
433 """
Jon Wayne Parrott807032c2016-10-18 09:38:26 -0700434 info, signer = _service_account_info.from_filename(
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700435 filename, require=["client_email"]
436 )
Jon Wayne Parrott807032c2016-10-18 09:38:26 -0700437 return cls._from_signer_and_info(signer, info, **kwargs)
Jon Wayne Parrottabcd3ed2016-10-17 11:23:47 -0700438
Jon Wayne Parrottb8f48d02017-02-24 09:03:24 -0800439 @classmethod
440 def from_signing_credentials(cls, credentials, audience, **kwargs):
441 """Creates a new :class:`google.auth.jwt.Credentials` instance from an
442 existing :class:`google.auth.credentials.Signing` instance.
443
444 The new instance will use the same signer as the existing instance and
445 will use the existing instance's signer email as the issuer and
446 subject by default.
447
448 Example::
449
450 svc_creds = service_account.Credentials.from_service_account_file(
451 'service_account.json')
452 audience = (
453 'https://pubsub.googleapis.com/google.pubsub.v1.Publisher')
454 jwt_creds = jwt.Credentials.from_signing_credentials(
455 svc_creds, audience=audience)
456
457 Args:
458 credentials (google.auth.credentials.Signing): The credentials to
459 use to construct the new credentials.
460 audience (str): the `aud` claim. The intended audience for the
461 credentials.
462 kwargs: Additional arguments to pass to the constructor.
463
464 Returns:
465 google.auth.jwt.Credentials: A new Credentials instance.
466 """
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700467 kwargs.setdefault("issuer", credentials.signer_email)
468 kwargs.setdefault("subject", credentials.signer_email)
469 return cls(credentials.signer, audience=audience, **kwargs)
Jon Wayne Parrottb8f48d02017-02-24 09:03:24 -0800470
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700471 def with_claims(
472 self, issuer=None, subject=None, audience=None, additional_claims=None
473 ):
Jon Wayne Parrottabcd3ed2016-10-17 11:23:47 -0700474 """Returns a copy of these credentials with modified claims.
475
476 Args:
477 issuer (str): The `iss` claim. If unspecified the current issuer
478 claim will be used.
479 subject (str): The `sub` claim. If unspecified the current subject
480 claim will be used.
Jon Wayne Parrottab086892017-02-23 09:20:14 -0800481 audience (str): the `aud` claim. If unspecified the current
482 audience claim will be used.
Jon Wayne Parrottabcd3ed2016-10-17 11:23:47 -0700483 additional_claims (Mapping[str, str]): Any additional claims for
484 the JWT payload. This will be merged with the current
485 additional claims.
486
487 Returns:
488 google.auth.jwt.Credentials: A new credentials instance.
489 """
Jon Wayne Parrott75c78b22017-03-23 13:14:53 -0700490 new_additional_claims = copy.deepcopy(self._additional_claims)
491 new_additional_claims.update(additional_claims or {})
492
Christophe Tatonb649b432018-02-08 14:12:23 -0800493 return self.__class__(
Jon Wayne Parrottabcd3ed2016-10-17 11:23:47 -0700494 self._signer,
495 issuer=issuer if issuer is not None else self._issuer,
496 subject=subject if subject is not None else self._subject,
497 audience=audience if audience is not None else self._audience,
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700498 additional_claims=new_additional_claims,
Bu Sun Kim3dda7b22020-07-09 10:39:39 -0700499 quota_project_id=self._quota_project_id,
500 )
501
Bu Sun Kim41599ae2020-09-02 12:55:42 -0600502 @_helpers.copy_docstring(google.auth.credentials.CredentialsWithQuotaProject)
Bu Sun Kim3dda7b22020-07-09 10:39:39 -0700503 def with_quota_project(self, quota_project_id):
504 return self.__class__(
505 self._signer,
506 issuer=self._issuer,
507 subject=self._subject,
508 audience=self._audience,
509 additional_claims=self._additional_claims,
510 quota_project_id=quota_project_id,
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700511 )
Jon Wayne Parrottabcd3ed2016-10-17 11:23:47 -0700512
Jon Wayne Parrottab086892017-02-23 09:20:14 -0800513 def _make_jwt(self):
Jon Wayne Parrottabcd3ed2016-10-17 11:23:47 -0700514 """Make a signed JWT.
515
Jon Wayne Parrottabcd3ed2016-10-17 11:23:47 -0700516 Returns:
Danny Hermes48c85f72016-11-08 09:30:44 -0800517 Tuple[bytes, datetime]: The encoded JWT and the expiration.
Jon Wayne Parrottabcd3ed2016-10-17 11:23:47 -0700518 """
519 now = _helpers.utcnow()
520 lifetime = datetime.timedelta(seconds=self._token_lifetime)
521 expiry = now + lifetime
522
523 payload = {
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700524 "iss": self._issuer,
525 "sub": self._subject,
526 "iat": _helpers.datetime_to_secs(now),
527 "exp": _helpers.datetime_to_secs(expiry),
528 "aud": self._audience,
Jon Wayne Parrottabcd3ed2016-10-17 11:23:47 -0700529 }
530
531 payload.update(self._additional_claims)
532
533 jwt = encode(self._signer, payload)
534
535 return jwt, expiry
536
Jon Wayne Parrottabcd3ed2016-10-17 11:23:47 -0700537 def refresh(self, request):
538 """Refreshes the access token.
539
540 Args:
541 request (Any): Unused.
542 """
543 # pylint: disable=unused-argument
544 # (pylint doesn't correctly recognize overridden methods.)
545 self.token, self.expiry = self._make_jwt()
546
Jon Wayne Parrottb8f48d02017-02-24 09:03:24 -0800547 @_helpers.copy_docstring(google.auth.credentials.Signing)
Jon Wayne Parrottabcd3ed2016-10-17 11:23:47 -0700548 def sign_bytes(self, message):
Jon Wayne Parrottabcd3ed2016-10-17 11:23:47 -0700549 return self._signer.sign(message)
550
Jon Wayne Parrott4c883f02016-12-02 14:26:33 -0800551 @property
Jon Wayne Parrottb8f48d02017-02-24 09:03:24 -0800552 @_helpers.copy_docstring(google.auth.credentials.Signing)
Jon Wayne Parrott4c883f02016-12-02 14:26:33 -0800553 def signer_email(self):
554 return self._issuer
555
Jon Wayne Parrottd7221672017-02-16 09:05:11 -0800556 @property
Jon Wayne Parrottb8f48d02017-02-24 09:03:24 -0800557 @_helpers.copy_docstring(google.auth.credentials.Signing)
Jon Wayne Parrottd7221672017-02-16 09:05:11 -0800558 def signer(self):
559 return self._signer
Jon Wayne Parrottcfbfd252017-03-28 13:03:11 -0700560
561
562class OnDemandCredentials(
Bu Sun Kim41599ae2020-09-02 12:55:42 -0600563 google.auth.credentials.Signing, google.auth.credentials.CredentialsWithQuotaProject
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700564):
Jon Wayne Parrottcfbfd252017-03-28 13:03:11 -0700565 """On-demand JWT credentials.
566
567 Like :class:`Credentials`, this class uses a JWT as the bearer token for
568 authentication. However, this class does not require the audience at
569 construction time. Instead, it will generate a new token on-demand for
570 each request using the request URI as the audience. It caches tokens
571 so that multiple requests to the same URI do not incur the overhead
572 of generating a new token every time.
573
574 This behavior is especially useful for `gRPC`_ clients. A gRPC service may
575 have multiple audience and gRPC clients may not know all of the audiences
576 required for accessing a particular service. With these credentials,
577 no knowledge of the audiences is required ahead of time.
578
579 .. _grpc: http://www.grpc.io/
580 """
581
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700582 def __init__(
583 self,
584 signer,
585 issuer,
586 subject,
587 additional_claims=None,
588 token_lifetime=_DEFAULT_TOKEN_LIFETIME_SECS,
589 max_cache_size=_DEFAULT_MAX_CACHE_SIZE,
Bu Sun Kim3dda7b22020-07-09 10:39:39 -0700590 quota_project_id=None,
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700591 ):
Jon Wayne Parrottcfbfd252017-03-28 13:03:11 -0700592 """
593 Args:
594 signer (google.auth.crypt.Signer): The signer used to sign JWTs.
595 issuer (str): The `iss` claim.
596 subject (str): The `sub` claim.
597 additional_claims (Mapping[str, str]): Any additional claims for
598 the JWT payload.
599 token_lifetime (int): The amount of time in seconds for
600 which the token is valid. Defaults to 1 hour.
601 max_cache_size (int): The maximum number of JWT tokens to keep in
602 cache. Tokens are cached using :class:`cachetools.LRUCache`.
Bu Sun Kim3dda7b22020-07-09 10:39:39 -0700603 quota_project_id (Optional[str]): The project ID used for quota
604 and billing.
605
Jon Wayne Parrottcfbfd252017-03-28 13:03:11 -0700606 """
607 super(OnDemandCredentials, self).__init__()
608 self._signer = signer
609 self._issuer = issuer
610 self._subject = subject
611 self._token_lifetime = token_lifetime
Bu Sun Kim3dda7b22020-07-09 10:39:39 -0700612 self._quota_project_id = quota_project_id
Jon Wayne Parrottcfbfd252017-03-28 13:03:11 -0700613
614 if additional_claims is None:
615 additional_claims = {}
616
617 self._additional_claims = additional_claims
618 self._cache = cachetools.LRUCache(maxsize=max_cache_size)
619
620 @classmethod
621 def _from_signer_and_info(cls, signer, info, **kwargs):
622 """Creates an OnDemandCredentials instance from a signer and service
623 account info.
624
625 Args:
626 signer (google.auth.crypt.Signer): The signer used to sign JWTs.
627 info (Mapping[str, str]): The service account info.
628 kwargs: Additional arguments to pass to the constructor.
629
630 Returns:
631 google.auth.jwt.OnDemandCredentials: The constructed credentials.
632
633 Raises:
634 ValueError: If the info is not in the expected format.
635 """
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700636 kwargs.setdefault("subject", info["client_email"])
637 kwargs.setdefault("issuer", info["client_email"])
Jon Wayne Parrottcfbfd252017-03-28 13:03:11 -0700638 return cls(signer, **kwargs)
639
640 @classmethod
641 def from_service_account_info(cls, info, **kwargs):
642 """Creates an OnDemandCredentials instance from a dictionary.
643
644 Args:
645 info (Mapping[str, str]): The service account info in Google
646 format.
647 kwargs: Additional arguments to pass to the constructor.
648
649 Returns:
650 google.auth.jwt.OnDemandCredentials: The constructed credentials.
651
652 Raises:
653 ValueError: If the info is not in the expected format.
654 """
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700655 signer = _service_account_info.from_dict(info, require=["client_email"])
Jon Wayne Parrottcfbfd252017-03-28 13:03:11 -0700656 return cls._from_signer_and_info(signer, info, **kwargs)
657
658 @classmethod
659 def from_service_account_file(cls, filename, **kwargs):
660 """Creates an OnDemandCredentials instance from a service account .json
661 file in Google format.
662
663 Args:
664 filename (str): The path to the service account .json file.
665 kwargs: Additional arguments to pass to the constructor.
666
667 Returns:
668 google.auth.jwt.OnDemandCredentials: The constructed credentials.
669 """
670 info, signer = _service_account_info.from_filename(
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700671 filename, require=["client_email"]
672 )
Jon Wayne Parrottcfbfd252017-03-28 13:03:11 -0700673 return cls._from_signer_and_info(signer, info, **kwargs)
674
675 @classmethod
676 def from_signing_credentials(cls, credentials, **kwargs):
677 """Creates a new :class:`google.auth.jwt.OnDemandCredentials` instance
678 from an existing :class:`google.auth.credentials.Signing` instance.
679
680 The new instance will use the same signer as the existing instance and
681 will use the existing instance's signer email as the issuer and
682 subject by default.
683
684 Example::
685
686 svc_creds = service_account.Credentials.from_service_account_file(
687 'service_account.json')
688 jwt_creds = jwt.OnDemandCredentials.from_signing_credentials(
689 svc_creds)
690
691 Args:
692 credentials (google.auth.credentials.Signing): The credentials to
693 use to construct the new credentials.
694 kwargs: Additional arguments to pass to the constructor.
695
696 Returns:
697 google.auth.jwt.Credentials: A new Credentials instance.
698 """
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700699 kwargs.setdefault("issuer", credentials.signer_email)
700 kwargs.setdefault("subject", credentials.signer_email)
Jon Wayne Parrottcfbfd252017-03-28 13:03:11 -0700701 return cls(credentials.signer, **kwargs)
702
703 def with_claims(self, issuer=None, subject=None, additional_claims=None):
704 """Returns a copy of these credentials with modified claims.
705
706 Args:
707 issuer (str): The `iss` claim. If unspecified the current issuer
708 claim will be used.
709 subject (str): The `sub` claim. If unspecified the current subject
710 claim will be used.
711 additional_claims (Mapping[str, str]): Any additional claims for
712 the JWT payload. This will be merged with the current
713 additional claims.
714
715 Returns:
716 google.auth.jwt.OnDemandCredentials: A new credentials instance.
717 """
718 new_additional_claims = copy.deepcopy(self._additional_claims)
719 new_additional_claims.update(additional_claims or {})
720
Christophe Tatonb649b432018-02-08 14:12:23 -0800721 return self.__class__(
Jon Wayne Parrottcfbfd252017-03-28 13:03:11 -0700722 self._signer,
723 issuer=issuer if issuer is not None else self._issuer,
724 subject=subject if subject is not None else self._subject,
725 additional_claims=new_additional_claims,
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700726 max_cache_size=self._cache.maxsize,
Bu Sun Kim3dda7b22020-07-09 10:39:39 -0700727 quota_project_id=self._quota_project_id,
728 )
729
Bu Sun Kim41599ae2020-09-02 12:55:42 -0600730 @_helpers.copy_docstring(google.auth.credentials.CredentialsWithQuotaProject)
Bu Sun Kim3dda7b22020-07-09 10:39:39 -0700731 def with_quota_project(self, quota_project_id):
732
733 return self.__class__(
734 self._signer,
735 issuer=self._issuer,
736 subject=self._subject,
737 additional_claims=self._additional_claims,
738 max_cache_size=self._cache.maxsize,
739 quota_project_id=quota_project_id,
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700740 )
Jon Wayne Parrottcfbfd252017-03-28 13:03:11 -0700741
742 @property
743 def valid(self):
744 """Checks the validity of the credentials.
745
746 These credentials are always valid because it generates tokens on
747 demand.
748 """
749 return True
750
751 def _make_jwt_for_audience(self, audience):
752 """Make a new JWT for the given audience.
753
754 Args:
755 audience (str): The intended audience.
756
757 Returns:
758 Tuple[bytes, datetime]: The encoded JWT and the expiration.
759 """
760 now = _helpers.utcnow()
761 lifetime = datetime.timedelta(seconds=self._token_lifetime)
762 expiry = now + lifetime
763
764 payload = {
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700765 "iss": self._issuer,
766 "sub": self._subject,
767 "iat": _helpers.datetime_to_secs(now),
768 "exp": _helpers.datetime_to_secs(expiry),
769 "aud": audience,
Jon Wayne Parrottcfbfd252017-03-28 13:03:11 -0700770 }
771
772 payload.update(self._additional_claims)
773
774 jwt = encode(self._signer, payload)
775
776 return jwt, expiry
777
778 def _get_jwt_for_audience(self, audience):
779 """Get a JWT For a given audience.
780
781 If there is already an existing, non-expired token in the cache for
782 the audience, that token is used. Otherwise, a new token will be
783 created.
784
785 Args:
786 audience (str): The intended audience.
787
788 Returns:
789 bytes: The encoded JWT.
790 """
791 token, expiry = self._cache.get(audience, (None, None))
792
793 if token is None or expiry < _helpers.utcnow():
794 token, expiry = self._make_jwt_for_audience(audience)
795 self._cache[audience] = token, expiry
796
797 return token
798
799 def refresh(self, request):
800 """Raises an exception, these credentials can not be directly
801 refreshed.
802
803 Args:
804 request (Any): Unused.
805
806 Raises:
807 google.auth.RefreshError
808 """
809 # pylint: disable=unused-argument
810 # (pylint doesn't correctly recognize overridden methods.)
811 raise exceptions.RefreshError(
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700812 "OnDemandCredentials can not be directly refreshed."
813 )
Jon Wayne Parrottcfbfd252017-03-28 13:03:11 -0700814
815 def before_request(self, request, method, url, headers):
816 """Performs credential-specific before request logic.
817
818 Args:
819 request (Any): Unused. JWT credentials do not need to make an
820 HTTP request to refresh.
821 method (str): The request's HTTP method.
822 url (str): The request's URI. This is used as the audience claim
823 when generating the JWT.
824 headers (Mapping): The request's headers.
825 """
826 # pylint: disable=unused-argument
827 # (pylint doesn't correctly recognize overridden methods.)
828 parts = urllib.parse.urlsplit(url)
829 # Strip query string and fragment
830 audience = urllib.parse.urlunsplit(
Bu Sun Kim9eec0912019-10-21 17:04:21 -0700831 (parts.scheme, parts.netloc, parts.path, "", "")
832 )
Jon Wayne Parrottcfbfd252017-03-28 13:03:11 -0700833 token = self._get_jwt_for_audience(audience)
834 self.apply(headers, token=token)
835
836 @_helpers.copy_docstring(google.auth.credentials.Signing)
837 def sign_bytes(self, message):
838 return self._signer.sign(message)
839
840 @property
841 @_helpers.copy_docstring(google.auth.credentials.Signing)
842 def signer_email(self):
843 return self._issuer
844
845 @property
846 @_helpers.copy_docstring(google.auth.credentials.Signing)
847 def signer(self):
848 return self._signer