3 L(Yh@sdZddlZddlZddlZddlZddlZddlZddlmZddl m Z ddl m Z ddl m Z ddl m Z ddlZdZd Zdd d Zd d ZddZddZddZdddZGdddejjjejjjZGdddejjjejjjZdS)aJSON Web Tokens Provides support for creating (encoding) and verifying (decoding) JWTs, especially JWTs generated and consumed by Google infrastructure. See `rfc7519`_ for more details on JWTs. To encode a JWT use :func:`encode`:: from google.auth import crypto from google.auth import jwt signer = crypt.Signer(private_key) payload = {'some': 'payload'} encoded = jwt.encode(signer, payload) To decode a JWT and verify claims use :func:`decode`:: claims = jwt.decode(encoded, certs=public_certs) You can also skip verification:: claims = jwt.decode(encoded, verify=False) .. _rfc7519: https://tools.ietf.org/html/rfc7519 N)urllib)_helpers)_service_account_info)crypt) exceptionsi cCs|dkr i}|dkr|j}|jddd|dk r:||d<tjtj|jdtjtj|jdg}dj|}|j|}|j tj|dj|S)aMake a signed JWT. Args: signer (google.auth.crypt.Signer): The signer used to sign the JWT. payload (Mapping[str, str]): The JWT payload. header (Mapping[str, str]): Additional JWT header payload. key_id (str): The key id to add to the JWT header. If the signer has a key id it will be used as the default. If this is specified it will override the signer's key id. Returns: bytes: The encoded JWT. NZJWTZRS256)typZalgkidzutf-8.) key_idupdatebase64urlsafe_b64encodejsondumpsencodejoinsignappend)signerpayloadheaderr segmentsZ signing_input signaturer>/private/tmp/pip-build-nl73fm5q/google-auth/google/auth/jwt.pyr>s  rc CsBtj|}ytj|jdStk r<tdj|YnXdS)zDecodes a single JWT segment.zutf-8zCan't parse segment: {0}N)rpadded_urlsafe_b64decoderloadsdecode ValueErrorformat)Zencoded_sectionZ section_bytesrrr_decode_jwt_segmentcs  r!cCshtj|}|jddkr&tdj||jd\}}}|d|}tj|}t|}t|}||||fS)a6Decodes a token and does no verification. Args: token (Union[str, bytes]): The encoded JWT. Returns: Tuple[str, str, str, str]: header, payload, signed_section, and signature. Raises: ValueError: if there are an incorrect amount of segments in the token. r z&Wrong number of segments in token: {0})rto_bytescountrr splitrr!)tokenZencoded_headerZencoded_payloadrsigned_sectionrrrrr_unverified_decodels    r(cCst|\}}}}|S)a@Return the decoded header of a token. No verification is done. This is useful to extract the key id from the header in order to acquire the appropriate certificate to verify the token. Args: token (Union[str, bytes]): the encoded JWT. Returns: Mapping: The decoded JWT header. )r()r&r_rrr decode_headers r*cCstjtj}x"dD]}||krtdj|qW|d}|tj}||kr\tdj|||d}|tj}||krtdj||dS)zVerifies the ``iat`` (Issued At) and ``exp`` (Expires) claims in a token payload. Args: payload (Mapping[str, str]): The JWT payload. Raises: ValueError: if any checks failed. iatexpz(Token does not contain required claim {}zToken used too early, {} < {}zToken expired, {} < {}N)r+r,)rdatetime_to_secsutcnowrr ZCLOCK_SKEW_SECS)rnowkeyr+Zearliestr,latestrrr_verify_iat_and_exps    r2Tc Cst|\}}}}|s|St|tjr^|jd}|rT||krHtdj|||g} qb|j} n|} tj ||| sxtdt ||dk r|jd} || krtdj| ||S)aDecode and verify a JWT. Args: token (str): The encoded JWT. certs (Union[str, bytes, Mapping[str, Union[str, bytes]]]): The certificate used to validate the JWT signatyre. If bytes or string, it must the the public key certificate in PEM format. If a mapping, it must be a mapping of key IDs to public key certificates in PEM format. The mapping must contain the same key ID that's specified in the token's header. verify (bool): Whether to perform signature and claim validation. Verification is done by default. audience (str): The audience claim, 'aud', that this JWT should contain. If None then the JWT's 'aud' parameter is not verified. Returns: Mapping[str, str]: The deserialized JSON payload in the JWT. Raises: ValueError: if any verification checks failed. r z$Certificate for key id {} not found.z!Could not verify token signature.Naudz(Token has wrong audience {}, expected {}) r( isinstance collectionsMappinggetrr valuesrZverify_signaturer2) r&certsverifyaudiencerrr'rr Zcerts_to_checkZclaim_audiencerrrrs,       rcseZdZdZdeffdd ZeddZeddZed d Z ed d Z dd dZ ddZ ddZ ejejjjddZeejejjjddZeejejjjddZZS) Credentialsa.Credentials that use a JWT as the bearer token. These credentials require an "audience" claim. This claim identifies the intended recipient of the bearer token. The constructor arguments determine the claims for the JWT that is sent with requests. Usually, you'll construct these credentials with one of the helper constructors as shown in the next section. To create JWT credentials using a Google service account private key JSON file:: audience = 'https://pubsub.googleapis.com/google.pubsub.v1.Publisher' credentials = jwt.Credentials.from_service_account_file( 'service-account.json', audience=audience) If you already have the service account file loaded and parsed:: service_account_info = json.load(open('service_account.json')) credentials = jwt.Credentials.from_service_account_info( service_account_info, audience=audience) Both helper methods pass on arguments to the constructor, so you can specify the JWT claims:: credentials = jwt.Credentials.from_service_account_file( 'service-account.json', audience=audience, additional_claims={'meta': 'data'}) You can also construct the credentials directly if you have a :class:`~google.auth.crypt.Signer` instance:: credentials = jwt.Credentials( signer, issuer='your-issuer', subject='your-subject', audience=audience) The claims are considered immutable. If you want to modify the claims, you can easily create another instance using :meth:`with_claims`:: new_audience = ( 'https://pubsub.googleapis.com/google.pubsub.v1.Subscriber') new_credentials = credentials.with_claims(audience=new_audience) NcsBtt|j||_||_||_||_||_|dkr8i}||_dS)a Args: signer (google.auth.crypt.Signer): The signer used to sign JWTs. issuer (str): The `iss` claim. subject (str): The `sub` claim. audience (str): the `aud` claim. The intended audience for the credentials. additional_claims (Mapping[str, str]): Any additional claims for the JWT payload. token_lifetime (int): The amount of time in seconds for which the token is valid. Defaults to 1 hour. N) superr<__init___signer_issuer_subject _audience_token_lifetime_additional_claims)selfrissuersubjectr;additional_claimstoken_lifetime) __class__rrr>-szCredentials.__init__cKs,|jd|d|jd|d||f|S)aCreates a Credentials instance from a signer and service account info. Args: signer (google.auth.crypt.Signer): The signer used to sign JWTs. info (Mapping[str, str]): The service account info. kwargs: Additional arguments to pass to the constructor. Returns: google.auth.jwt.Credentials: The constructed credentials. Raises: ValueError: If the info is not in the expected format. rG client_emailrF) setdefault)clsrinfokwargsrrr_from_signer_and_infoHsz!Credentials._from_signer_and_infocKs tj|dgd}|j||f|S)aCreates an Credentials instance from a dictionary. Args: info (Mapping[str, str]): The service account info in Google format. kwargs: Additional arguments to pass to the constructor. Returns: google.auth.jwt.Credentials: The constructed credentials. Raises: ValueError: If the info is not in the expected format. rK)require)r from_dictrP)rMrNrOrrrrfrom_service_account_info\s z%Credentials.from_service_account_infocKs$tj|dgd\}}|j||f|S)aWCreates a Credentials instance from a service account .json file in Google format. Args: filename (str): The path to the service account .json file. kwargs: Additional arguments to pass to the constructor. Returns: google.auth.jwt.Credentials: The constructed credentials. rK)rQ)r from_filenamerP)rMfilenamerOrNrrrrfrom_service_account_fileos z%Credentials.from_service_account_filecKs2|jd|j|jd|j||jfd|i|S)a;Creates a new :class:`google.auth.jwt.Credentials` instance from an existing :class:`google.auth.credentials.Signing` instance. The new instance will use the same signer as the existing instance and will use the existing instance's signer email as the issuer and subject by default. Example:: svc_creds = service_account.Credentials.from_service_account_file( 'service_account.json') audience = ( 'https://pubsub.googleapis.com/google.pubsub.v1.Publisher') jwt_creds = jwt.Credentials.from_signing_credentials( svc_creds, audience=audience) Args: credentials (google.auth.credentials.Signing): The credentials to use to construct the new credentials. audience (str): the `aud` claim. The intended audience for the credentials. kwargs: Additional arguments to pass to the constructor. Returns: google.auth.jwt.Credentials: A new Credentials instance. rFrGr;)rL signer_emailr)rM credentialsr;rOrrrfrom_signing_credentialss z$Credentials.from_signing_credentialscCsXtj|j}|j|pit|j|dk r,|n|j|dk r<|n|j|dk rL|n|j|dS)aReturns a copy of these credentials with modified claims. Args: issuer (str): The `iss` claim. If unspecified the current issuer claim will be used. subject (str): The `sub` claim. If unspecified the current subject claim will be used. audience (str): the `aud` claim. If unspecified the current audience claim will be used. additional_claims (Mapping[str, str]): Any additional claims for the JWT payload. This will be merged with the current additional claims. Returns: google.auth.jwt.Credentials: A new credentials instance. N)rFrGr;rH) copydeepcopyrDr r<r?r@rArB)rErFrGr;rHnew_additional_claimsrrr with_claimss zCredentials.with_claimscCs`tj}tj|jd}||}|j|jtj|tj||jd}|j |j t |j |}||fS)zuMake a signed JWT. Returns: Tuple[bytes, datetime]: The encoded JWT and the expiration. )seconds)isssubr+r,r3) rr.datetime timedeltarCr@rAr-rBr rDrr?)rEr/lifetimeexpiryrjwtrrr _make_jwts   zCredentials._make_jwtcCs|j\|_|_dS)zVRefreshes the access token. Args: request (Any): Unused. N)rfr&rd)rErequestrrrrefreshszCredentials.refreshcCs |jj|S)N)r?r)rEmessagerrr sign_bytesszCredentials.sign_bytescCs|jS)N)r@)rErrrrWszCredentials.signer_emailcCs|jS)N)r?)rErrrrszCredentials.signer)NNNN)__name__ __module__ __qualname____doc___DEFAULT_TOKEN_LIFETIME_SECSr> classmethodrPrSrVrYr]rfrhrcopy_docstringgoogleauthrXSigningrjpropertyrWr __classcell__rr)rJrr<s 1    #  r<cseZdZdZdeeffdd ZeddZeddZ ed d Z ed d Z dd dZ e ddZddZddZddZddZejejjjddZe ejejjjddZe ejejjjddZZS) OnDemandCredentialsaOn-demand JWT credentials. Like :class:`Credentials`, this class uses a JWT as the bearer token for authentication. However, this class does not require the audience at construction time. Instead, it will generate a new token on-demand for each request using the request URI as the audience. It caches tokens so that multiple requests to the same URI do not incur the overhead of generating a new token every time. This behavior is especially useful for `gRPC`_ clients. A gRPC service may have multiple audience and gRPC clients may not know all of the audiences required for accessing a particular service. With these credentials, no knowledge of the audiences is required ahead of time. .. _grpc: http://www.grpc.io/ NcsJtt|j||_||_||_||_|dkr2i}||_tj |d|_ dS)aF Args: signer (google.auth.crypt.Signer): The signer used to sign JWTs. issuer (str): The `iss` claim. subject (str): The `sub` claim. additional_claims (Mapping[str, str]): Any additional claims for the JWT payload. token_lifetime (int): The amount of time in seconds for which the token is valid. Defaults to 1 hour. max_cache_size (int): The maximum number of JWT tokens to keep in cache. Tokens are cached using :class:`cachetools.LRUCache`. N)maxsize) r=rwr>r?r@rArCrD cachetoolsZLRUCache_cache)rErrFrGrHrImax_cache_size)rJrrr>szOnDemandCredentials.__init__cKs,|jd|d|jd|d||f|S)aCreates an OnDemandCredentials instance from a signer and service account info. Args: signer (google.auth.crypt.Signer): The signer used to sign JWTs. info (Mapping[str, str]): The service account info. kwargs: Additional arguments to pass to the constructor. Returns: google.auth.jwt.OnDemandCredentials: The constructed credentials. Raises: ValueError: If the info is not in the expected format. rGrKrF)rL)rMrrNrOrrrrPsz)OnDemandCredentials._from_signer_and_infocKs tj|dgd}|j||f|S)aCreates an OnDemandCredentials instance from a dictionary. Args: info (Mapping[str, str]): The service account info in Google format. kwargs: Additional arguments to pass to the constructor. Returns: google.auth.jwt.OnDemandCredentials: The constructed credentials. Raises: ValueError: If the info is not in the expected format. rK)rQ)rrRrP)rMrNrOrrrrrS3s z-OnDemandCredentials.from_service_account_infocKs$tj|dgd\}}|j||f|S)ahCreates an OnDemandCredentials instance from a service account .json file in Google format. Args: filename (str): The path to the service account .json file. kwargs: Additional arguments to pass to the constructor. Returns: google.auth.jwt.OnDemandCredentials: The constructed credentials. rK)rQ)rrTrP)rMrUrOrNrrrrrVFs z-OnDemandCredentials.from_service_account_filecKs*|jd|j|jd|j||jf|S)akCreates a new :class:`google.auth.jwt.OnDemandCredentials` instance from an existing :class:`google.auth.credentials.Signing` instance. The new instance will use the same signer as the existing instance and will use the existing instance's signer email as the issuer and subject by default. Example:: svc_creds = service_account.Credentials.from_service_account_file( 'service_account.json') jwt_creds = jwt.OnDemandCredentials.from_signing_credentials( svc_creds) Args: credentials (google.auth.credentials.Signing): The credentials to use to construct the new credentials. kwargs: Additional arguments to pass to the constructor. Returns: google.auth.jwt.Credentials: A new Credentials instance. rFrG)rLrWr)rMrXrOrrrrYVsz,OnDemandCredentials.from_signing_credentialscCsNtj|j}|j|pit|j|dk r,|n|j|dk r<|n|j||jj dS)aJReturns a copy of these credentials with modified claims. Args: issuer (str): The `iss` claim. If unspecified the current issuer claim will be used. subject (str): The `sub` claim. If unspecified the current subject claim will be used. additional_claims (Mapping[str, str]): Any additional claims for the JWT payload. This will be merged with the current additional claims. Returns: google.auth.jwt.OnDemandCredentials: A new credentials instance. N)rFrGrHr{) rZr[rDr rwr?r@rArzrx)rErFrGrHr\rrrr]rs zOnDemandCredentials.with_claimscCsdS)zChecks the validity of the credentials. These credentials are always valid because it generates tokens on demand. Tr)rErrrvalidszOnDemandCredentials.validcCs^tj}tj|jd}||}|j|jtj|tj||d}|j|j t |j |}||fS)zMake a new JWT for the given audience. Args: audience (str): The intended audience. Returns: Tuple[bytes, datetime]: The encoded JWT and the expiration. )r^)r_r`r+r,r3) rr.rarbrCr@rAr-r rDrr?)rEr;r/rcrdrrerrr_make_jwt_for_audiences   z*OnDemandCredentials._make_jwt_for_audiencecCsF|jj|d\}}|dks&|tjkrB|j|\}}||f|j|<|S)aGGet a JWT For a given audience. If there is already an existing, non-expired token in the cache for the audience, that token is used. Otherwise, a new token will be created. Args: audience (str): The intended audience. Returns: bytes: The encoded JWT. N)NN)rzr7rr.r})rEr;r&rdrrr_get_jwt_for_audiences z)OnDemandCredentials._get_jwt_for_audiencecCstjddS)zRaises an exception, these credentials can not be directly refreshed. Args: request (Any): Unused. Raises: google.auth.RefreshError z2OnDemandCredentials can not be directly refreshed.N)rZ RefreshError)rErgrrrrhs zOnDemandCredentials.refreshcCsDtjj|}tjj|j|j|jddf}|j|}|j||ddS)aPerforms credential-specific before request logic. Args: request (Any): Unused. JWT credentials do not need to make an HTTP request to refresh. method (str): The request's HTTP method. url (str): The request's URI. This is used as the audience claim when generating the JWT. headers (Mapping): The request's headers. N)r&) rparseurlsplit urlunsplitschemenetlocpathr~apply)rErgmethodurlheaderspartsr;r&rrrbefore_requests  z"OnDemandCredentials.before_requestcCs |jj|S)N)r?r)rErirrrrjszOnDemandCredentials.sign_bytescCs|jS)N)r@)rErrrrWsz OnDemandCredentials.signer_emailcCs|jS)N)r?)rErrrrszOnDemandCredentials.signer)NNN)rkrlrmrnro_DEFAULT_MAX_CACHE_SIZEr>rprPrSrVrYr]rur|r}r~rhrrrqrrrsrXrtrjrWrrvrr)rJrrws&      rw)NN)NTN)rnr r5rZrarryZ six.movesrZ google.authrrrrZgoogle.auth.credentialsrrrorrr!r(r*r2rrsrXrtr<rwrrrr)s4      % # < u