;ixydZ ddlmZn#e$r ddlmZYnwxYwddlZddlZddlZddlZddl Z ddl m Z ddl m Z ddl m Z ddl mZddlZ ddlmZn #e$rdZYnwxYwd Zd Zd e jiZed gZe ejed <dd ZdZdZdZddZddZGddej j!j"ej j!j#Z$Gddej j!j"ej j!j#Z%dS)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 crypt 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 )MappingN)_helpers)_service_account_info)crypt) exceptions)es256i RS256ES256c|i}||j}|ddid|vrPt2t|tjr|ddin|ddi|||d<t jtj| dt jtj| dg}d |}| |}| t j|d |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. NtypJWTalgr r kidutf-8.) key_idupdater isinstance ES256Signerrunpadded_urlsafe_b64encodejsondumpsencodejoinsignappend)signerpayloadheaderrsegments signing_input signatures CC:\PYTHON\MyICR_Workspace\venv\Lib\site-packages\google/auth/jwt.pyrrKs;~ ~ MM5%.!!! F  FE4E!F!F  MM5'* + + + + MM5'* + + + u  +DJv,>,>,E,Eg,N,NOO+DJw,?,?,F,Fw,O,OPPH IIh''M M**I OOH7 BBCCC 99X  ctj|} tj|dS#t $r/}t jd|}||d}~wwxYw)zDecodes a single JWT segment.rzCan't parse segment: {0}N) rpadded_urlsafe_b64decoderloadsdecode ValueErrorrMalformedErrorformat)encoded_section section_bytes caught_excnew_excs r$_decode_jwt_segmentr1vs5oFFM&z-..w77888 &&&+ & - -m < <  :% &s&= A6*A11A6cLtj|}|ddkr'tjd||d\}}}|dz|z}tj|}t|}t|}t|ts'tjd|t|ts'tjd|||||fS)awDecodes a token and does no verification. Args: token (Union[str, bytes]): The encoded JWT. Returns: Tuple[Mapping, Mapping, str, str]: header, payload, signed_section, and signature. Raises: google.auth.exceptions.MalformedError: if there are an incorrect amount of segments in the token or segments of the wrong type. rz&Wrong number of segments in token: {0}z+Header segment should be a JSON object: {0}z,Payload segment should be a JSON object: {0}) rto_bytescountrr+r,splitr'r1rr)tokenencoded_headerencoded_payloadr#signed_sectionr rs r$_unverified_decoder;s)  e $ $E {{4A' 4 ; ;E B B   27T1B1B.NOY#d*_s)//OFAq! Mr%ctjtj}dD]-}||vr'tjd|.|d}||z }||kr(tjd|||d}||z}||kr(tjd||dS)aVerifies the ``iat`` (Issued At) and ``exp`` (Expires) claims in a token payload. Args: payload (Mapping[str, str]): The JWT payload. clock_skew_in_seconds (int): The clock skew used for `iat` and `exp` validation. Raises: google.auth.exceptions.InvalidValue: if value validation failed. google.auth.exceptions.MalformedError: if schema validation failed. )iatexpz(Token does not contain required claim {}r@zQToken used too early, {} < {}. Check that your computer's clock is set correctly.rAzToken expired, {} < {}N)rdatetime_to_secsutcnowrr+r, InvalidValue)rclock_skew_in_secondsnowkeyr@earliestrAlatests r$_verify_iat_and_exprJs  #HO$5$5 6 6C g  +:AA#FF   %.C**H X~~% _ f fS      %.C( (F ||%&>&E&Efc&R&RSSS|r%Tcpt|\}}}}|s|S|d} |d} t| } nk#t$r^} | tvr(t jd| | t jd| | d} ~ wwxYwt|trL| r5| |vr't j d| || g} n| } n|} tj ||| | st j dt|||Y|d}t|tr|g}||vr(t jd |||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 signature. 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 or list): The audience claim, 'aud', that this JWT should contain. Or a list of audience claims. If None then the JWT's 'aud' parameter is not verified. clock_skew_in_seconds (int): The clock skew used for `iat` and `exp` validation. Returns: Mapping[str, str]: The deserialized JSON payload in the JWT. Raises: google.auth.exceptions.InvalidValue: if value validation failed. google.auth.exceptions.MalformedError: if schema validation failed. rrzGThe key algorithm {} requires the cryptography package to be installed.z"Unsupported signature algorithm {}Nz$Certificate for key id {} not found.z!Could not verify token signature.audz/Token has wrong audience {}, expected one of {})r;get_ALGORITHM_TO_VERIFIER_CLASSKeyError_CRYPTOGRAPHY_BASED_ALGORITHMSrrDr,rrr+valuesrverify_signaturerJstr)r7certsverifyaudiencerEr rr:r#key_algr verifier_clsexccerts_to_checkclaim_audiences r$r)r)s42DE1J1J.FG^Y jjG ZZ  F 3G<     4 4 4)Y``   )4;;GDD  %!!   ,U"" /:AA&II$Fm_NN#\\^^NN  ! ><  M'(KLLL!6777 U++ h $ $ " zH  ) ))AHH"H  Ns A B:AB55B:ceZdZdZdedffd ZedZedZedZ edZ ddZ e j ejjjd Zd Zd Ze j ejjjd Zee j ejjjd Zee j ejjjdZedZxZS) 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) Nctt|||_||_||_||_||_||_|i}||_ 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. quota_project_id (Optional[str]): The project ID used for quota and billing. N) superr]__init___signer_issuer_subject _audience_token_lifetime_quota_project_id_additional_claims) selfrissuersubjectrVadditional_claimstoken_lifetimequota_project_id __class__s r$r`zCredentials.__init__ssg0 k4  ))+++   !-!1  $ " "3r%c |d|d|d|d||fi|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: google.auth.exceptions.MalformedError: If the info is not in the expected format. rj client_emailri setdefaultclsrinfokwargss r$_from_signer_and_infoz!Credentials._from_signer_and_infoR )T.%9:::(D$8999s6$$V$$$r%c Ntj|dg}|j||fi|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: google.auth.exceptions.MalformedError: If the info is not in the expected format. rprequirer from_dictrwrtrurvrs r$from_service_account_infoz%Credentials.from_service_account_info9'0?OPPP(s(@@@@@r%c Ttj|dg\}}|j||fi|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. rprzr from_filenamerwrtfilenamervrurs r$from_service_account_filez%Credentials.from_service_account_fileF-: ~.   f)s(@@@@@r%c |d|j|d|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. rirjrVrr signer_emailr)rt credentialsrVrvs r$from_signing_credentialsz$Credentials.from_signing_credentialssV8 (K$<===)[%=>>>s;%CCCFCCCr%ctj|j}||pi||j||n|j||n|j||n|j||j S)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. NrirjrVrkrm) copydeepcopyrgrrnrarbrcrdrf)rhrirjrVrknew_additional_claimss r$ with_claimszCredentials.with_claimss&!% d.E F F$$%6%<"===~~ L#/66T\&2GG !)!5XX4>3!3    r%cj||j|j|j|j|j|S)Nr)rnrarbrcrdrgrhrms r$with_quota_projectzCredentials.with_quota_projects:~~ L<M^"5-    r%cXtj}tj|j}||z}|j|jtj|tj|d}|jr |j|d<| |j t|j |}||fS)zuMake a signed JWT. Returns: Tuple[bytes, datetime]: The encoded JWT and the expiration. seconds)isssubr@rArL) rrCdatetime timedeltarerbrcrBrdrrgrra)rhrFlifetimeexpiryrjwts r$ _make_jwtzCredentials._make_jwts o%d.BCCCx<=,S11,V44    > ,!^GENt.///T\7++F{r%cH|\|_|_dS)zVRefreshes the access token. Args: request (Any): Unused. N)rr7rrhrequests r$refreshzCredentials.refresh2s #'.."2"2 DKKKr%c6|j|SNrarrhmessages r$ sign_byteszCredentials.sign_bytes<|  )))r%c|jSrrbrhs r$rzCredentials.signer_email@ |r%c|jSrrars r$rzCredentials.signerErr%c|jS)z3 Additional claims the JWT object was created with.)rgrs r$rkzCredentials.additional_claimsJs &&r%)NNNN)__name__ __module__ __qualname____doc___DEFAULT_TOKEN_LIFETIME_SECSr` classmethodrwrrrrrcopy_docstringgoogleauthrCredentialsWithQuotaProjectrrrSigningrpropertyrrrk __classcell__rns@r$r]r]?s//n3#4#4#4#4#4#4J%%[%&AA[A"AA[A DD[D@KO    >XV[4PQQ  RQ 2333XV[4<==**>=*XV[4<==>=XXV[4<==>=X''X'''''r%r]ceZdZdZdeedffd ZedZedZ edZ edZ ddZ e jejjjd Zed Zd Zd Zd ZdZe jejjjdZee jejjjdZee jejjjdZxZS)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/ Nctt|||_||_||_||_||_|i}||_tj ||_ dS)a 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`. quota_project_id (Optional[str]): The project ID used for quota and billing. N)maxsize) r_rr`rarbrcrerfrg cachetoolsLRUCache_cache) rhrrirjrkrlmax_cache_sizermrns r$r`zOnDemandCredentials.__init__dst2 !4((11333   -!1  $ " "3 ).AAA r%c |d|d|d|d||fi|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: google.auth.exceptions.MalformedError: If the info is not in the expected format. rjrprirqrss r$rwz)OnDemandCredentials._from_signer_and_inforxr%c Ntj|dg}|j||fi|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: google.auth.exceptions.MalformedError: If the info is not in the expected format. rprzr|r~s r$rz-OnDemandCredentials.from_service_account_inforr%c Ttj|dg\}}|j||fi|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. rprzrrs r$rz-OnDemandCredentials.from_service_account_filerr%c |d|j|d|j||jfi|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. rirjr)rtrrvs r$rz,OnDemandCredentials.from_signing_credentialssQ0 (K$<===)[%=>>>s;%00000r%ctj|j}||pi||j||n|j||n|j||jj |j S)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. Nrirjrkrrm) rrrgrrnrarbrcrrrf)rhrirjrkrs r$rzOnDemandCredentials.with_claimss~!% d.E F F$$%6%<"===~~ L#/66T\&2GG 3;.!3    r%ct||j|j|j|j|jj|S)Nr)rnrarbrcrgrrrs r$rz&OnDemandCredentials.with_quota_projects?~~ L<M"5;.-    r%cdS)zChecks the validity of the credentials. These credentials are always valid because it generates tokens on demand. Trs r$validzOnDemandCredentials.valids tr%c8tj}tj|j}||z}|j|jtj|tj||d}||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)rrr@rArL) rrCrrrerbrcrBrrgrra)rhrVrFrrrrs r$_make_jwt_for_audiencez*OnDemandCredentials._make_jwt_for_audience so%d.BCCCx<=,S11,V44    t.///T\7++F{r%c|j|d\}}||tjkr$||\}}||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. NN)rrMrrCr)rhrVr7rs r$_get_jwt_for_audiencez)OnDemandCredentials._get_jwt_for_audience(s` ,?? v =FX_%6%666 77AAME6$)6MDK ! r%c*tjd)zRaises an exception, these credentials can not be directly refreshed. Args: request (Any): Unused. Raises: google.auth.RefreshError z2OnDemandCredentials can not be directly refreshed.)r RefreshErrorrs r$rzOnDemandCredentials.refresh=s% @   r%ctj|}tj|j|j|jddf}||}|||dS)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. )r7N) urllibparseurlsplit urlunsplitschemenetlocpathrapply)rhrmethodurlheaderspartsrVr7s r$before_requestz"OnDemandCredentials.before_requestMsu %%c**<** \5<R <  **844 7% (((((r%c6|j|Srrrs r$rzOnDemandCredentials.sign_bytesbrr%c|jSrrrs r$rz OnDemandCredentials.signer_emailfrr%c|jSrrrs r$rzOnDemandCredentials.signerkrr%)NNN)rrrrr_DEFAULT_MAX_CACHE_SIZEr`rrwrrrrrrrrrrrrrrrrrrrrrrrs@r$rrPs,3.$B$B$B$B$B$BL%%[%&AA[A"AA[A 11[16    6XV[4PQQ   RQ  X6*   )))*XV[4<==**>=*XV[4<==>=XXV[4<==>=Xr%rr)r)NTNr)&rcollections.abcr ImportError collectionsrrrrr google.authrrrrgoogle.auth.credentialsrgoogle.auth.cryptrrr RSAVerifierrN frozensetrP ES256Verifierrr1r;r>rJr)rrrrr]rrr%r$rsl8$'''''''$$$########$   ------""""""''''''' EEE $ '):;!*G9!5!5,1,? )((((V & & &&6&6&6R"(T(T(T(TVUUUUpN'N'N'N'N' K#V[%<%XN'N'N'b^^^^^ K#V[%<%X^^^^^s  AAA