HEX
Server: LiteSpeed
System: Linux us-phx-web629.main-hosting.eu 5.14.0-503.23.2.el9_5.x86_64 #1 SMP PREEMPT_DYNAMIC Wed Feb 12 05:52:18 EST 2025 x86_64
User: u756937133 (756937133)
PHP: 8.2.27
Disabled: passthru,chgrp
Upload Files
File: //opt/gsutil/third_party/apitools/apitools/base/py/__pycache__/credentials_lib.cpython-39.pyc
a

�z�g�u�@s�dZddlmZddlZddlZddlZddlZddlZddlZddl	Z	ddl
Z
ddlZddlZddlm
Z
ddlmZddlZddlmZddlmZddlmZdd	lmZzddlZd
ZWnPe�yZz6ej�dd�Ze�d
�s�e�d�s�e�dZWYdZ[n
dZ[00zddlmZWn e�yBddlmZYn0zddlm Z d
Z!WnJe�y�dZ!zddlm"Z"Wn e�y�ddlm"Z"Yn0Yn0zddl#Z#e#j$Z$Wne�y�dZ$Yn0gd�Z%e�&�a'dd�Z(gZ)d6dd�Z*d7dd�Z+d8dd�Z,dd�Z-d9dd�Z.Gd d!�d!ej/�Z0Gd"d#�d#ej1j2�Z3d:d$d%�Z4d;d&d'�Z5Gd(d)�d)e6�Z7d<d*d+�Z8d,d-�Z9e*d=d.d/��Z:e*d0d1��Z;e*d2d3��Z<e*d>d4d5��Z=dS)?z,Common credentials classes and constructors.�)�print_functionN)�service_account)�tools)�http_client)�urllib)�
exceptions)�utilT�SERVER_SOFTWARE�ZDevelopmentzGoogle App EngineF)�gce)�multiprocess_file_storage)�multistore_file)�CredentialsFromFile�GaeAssertionCredentials�GceAssertionCredentials�GetCredentials�GetUserinfo�!ServiceAccountCredentialsFromFilecCs|adS�N)�cache_file_lock)�lock�r�D/opt/gsutil/third_party/apitools/apitools/base/py/credentials_lib.py�SetCredentialsCacheFileLock_srcCs0|durtt�}nt|tt��}t�||�|S)aPRegister a new method for fetching credentials.

    This new method should be a function with signature:
      client_info, **kwds -> Credentials or None
    This method can be used as a decorator, unless position needs to
    be supplied.

    Note that method must *always* accept arbitrary keyword arguments.

    Args:
      method: New credential-fetching method.
      position: (default: None) Where in the list of methods to
        add this; if None, we append. In all but rare cases,
        this should be either 0 or None.
    Returns:
      method, for use as a decorator.

    N)�len�_CREDENTIALS_METHODS�min�insert)�method�positionrrr�_RegisterCredentialsMethodjs

r c	
Ks�t�|�}||d�t|��|p$d|d�}
tD]$}||
fi|	��}|dur.|Sq.|pbtj�d�}t||
|d�}|dur~|St	�
d��dS)zDAttempt to get credentials, using an oauth dance as the last resort.� z%s-generated/0.1)�	client_id�
client_secret�scope�
user_agentNz~/.apitools.token)�oauth2client_argsz"Could not create valid credentials)r�NormalizeScopes�join�sortedr�os�path�
expanduserrr�CredentialsError)
�package_name�scopesr"r#r%�credentials_filename�api_key�clientr&�kwds�client_infor�credentialsrrrr�s&

�

��rcCs�tj�|�}tjdkr@tjj||d�}|dur<|dur<||_|St	|��}t
�|�}Wd�n1sh0Y|�d�}|tj
jkr�t�d|f��tj|d|d|d|d	||d
�}|SdS)z=Use the credentials in filename to create a token for scopes.�1.5.2�r/N�typez'Invalid service account credentials: %sr"�client_email�private_key_id�private_key)Zservice_account_id�service_account_emailr:Zprivate_key_pkcs8_textr/r%)r*r+r,�oauth2client�__version__r�ServiceAccountCredentialsZfrom_json_keyfile_namer%�open�json�load�getr2�SERVICE_ACCOUNTrr-Z_ServiceAccountCredentials)�filenamer/r%r5�keyfileZservice_account_infoZaccount_typerrrr�s2
��
(
��rcCs�tj�|�}t�|�}tjdkrDtjj	|||d�}|dur@||_
|St|d��(}tjj
||��||d�Wd�S1s|0YdS)z4Create a new credential from the named .p12 keyfile.r6r7N�rb�r%)r*r+r,rr'r=r>rr?Zfrom_p12_keyfiler%r@r2ZSignedJwtAssertionCredentials�read)�service_account_nameZprivate_key_filenamer/r%r5�key_filerrr�$ServiceAccountCredentialsFromP12File�s

��
�rLc	
Cs�|rtj�dd�}ntj�dd�}d|d|}ddi}tjj||d	�}tj�tj�i��}z|�|�}Wn8tj	j
y�}zt�d
|j
��WYd}~n
d}~00|S)z4Request the given url from the GCE metadata service.�GCE_METADATA_IPz169.254.169.254�GCE_METADATA_ROOTzmetadata.google.internalzhttp://z/computeMetadata/v1/zMetadata-Flavor�Google)�headersz$Could not reach metadata service: %sN)r*�environrCr�request�Request�build_opener�ProxyHandlerr@�error�URLErrorr�CommunicationError�reason)	�relative_urlZuse_metadata_ip�base_url�urlrPrR�opener�response�errr�_GceMetadataRequest�s ��r`cs�eZdZdZd�fdd�	Zedd��Zdd	�Zd
d�Zdd
�Z	dd�Z
dd�Zdd�Zdd�Z
�fdd�Zedd��Zedd��Z�ZS)rz(Assertion credentials for GCE instances.N�defaultcs�tj|dd�|_d}|�d�}|r.|�||�}|p:|�|�}|rP|sP|�||�t���4t�	d�t
t|�jfd|i|��Wd�n1s�0YdS)aAInitializes the credentials instance.

        Args:
          scopes: The scopes to get. If None, whatever scopes that are
              available to the instance are used.
          service_account_name: The service account to retrieve the scopes
              from.
          **kwds: Additional keyword args.

        �utf-8��encodingN�cache_filename�ignorer$)
�six�ensure_text�._GceAssertionCredentials__service_account_namerC�_CheckCacheFileForMatch�_ScopesFromMetadataServer�_WriteCacheFile�warnings�catch_warnings�simplefilter�superr�__init__)�selfr/rJr3Z
cached_scopesre��	__class__rrrq�s �
�

z GceAssertionCredentials.__init__cOs,z||i|��WStjy&YdS0dSr�r�Error��cls�argsr3rrr�GetszGceAssertionCredentials.GetcCs�|rtt|��nd|jd�}t|�}zN|��}|s8WdSt�|�}|d|dkrp|dd|dfvrp|dWSWnty��YnYn0dS)a	Checks the cache file to see if it matches the given credentials.

        Args:
          cache_filename: Cache filename to check.
          scopes: Scopes for the desired credentials.

        Returns:
          List of scopes (if cache matches) or None.
        N�r/�
svc_acct_namer|r/)r)�listri�_MultiProcessCacheFile�
LockedReadrA�loads�KeyboardInterrupt)rrrer/�creds�
cache_fileZcached_creds_strZcached_credsrrrrjs �
z/GceAssertionCredentials._CheckCacheFileForMatchcCsbtdd�|D��}||jd�}t�|�}t|�}z|�|�WntyR�YnYn0dS)aBWrites the credential metadata to the cache file.

        This does not save the credentials themselves (CredentialStore class
        optionally handles that after this class is initialized).

        Args:
          cache_filename: Cache filename to check.
          scopes: Scopes for the desired credentials.
        cSsg|]}t�|��qSr)rgrh��.0r$rrr�
<listcomp>C�z;GceAssertionCredentials._WriteCacheFile.<locals>.<listcomp>r{N)r)rirA�dumpsr~�LockedWriter�)rrrer/r�Z	creds_strr�rrrrl8s�
z'GceAssertionCredentials._WriteCacheFilecCsvt��st�d��|�|j�s.t�d|j��|rjt�|�}|��}||krrt�dt	t
||��f��n|��}|S)z5Returns instance scopes based on GCE metadata server.�0GCE credentials requested outside a GCE instancez@GCE credentials requested but service account %s does not exist.z)Instance did not have access to scopes %s)r�	DetectGcer�ResourceUnavailableError�GetServiceAccountrir'�GetInstanceScopesr-r)r})rrr/Zscope_lsZinstance_scopesrrrrkPs*���
��z1GceAssertionCredentials._ScopesFromMetadataServercCs&d}t|�}dd�|��D�}||vS)Nzinstance/service-accountscSsg|]}t�|��d��qS)z/

)rg�
ensure_str�rstrip)r��linerrrr�gs�z=GceAssertionCredentials.GetServiceAccount.<locals>.<listcomp>)r`�	readlines)rrZaccountrZr^Zresponse_linesrrrr�ds�z)GceAssertionCredentials.GetServiceAccountcCs,d�|j�}t|�}t�dd�|��D��S)Nz$instance/service-accounts/{0}/scopescss|]}t�|���VqdSr)rgr��stripr�rrr�	<genexpr>os�z<GceAssertionCredentials.GetInstanceScopes.<locals>.<genexpr>)�formatrir`rr'r�)rrrZr^rrrr�ks�
�z)GceAssertionCredentials.GetInstanceScopescCstjj�||�dS)a7Refresh self.access_token.

        This function replaces AppAssertionCredentials._refresh, which
        does not use the credential store and is therefore poorly
        suited for multi-threaded scenarios.

        Args:
          do_request: A function matching httplib2.Http.request's signature.

        N)r=r2�OAuth2Credentials�_refresh)rrZ
do_requestrrrr�ssz GceAssertionCredentials._refreshcCs�d�|j�}zt|�}Wn.tjyFd|_|jr@|j�|��Yn0t�	|�
��}zt�|�}Wn t
y�t�d|��Yn0|d|_d|vr�t|d�}tj|d�tjjtjjd�jdd	�|_nd|_d
|_|jr�|j�|�dS)z�Refresh self.access_token by querying the metadata server.

        If self.store is initialized, store acquired credentials there.
        z#instance/service-accounts/{0}/tokenTz$Could not parse response as JSON: %s�access_token�
expires_in)�seconds)�tzN)�tzinfoF)r�rir`rrX�invalid�store�
locked_putrgr�rIrAr��
ValueErrorr-r��int�datetime�	timedelta�now�timezone�utc�replace�token_expiry)rrZunused_http_requestrZr^�contentZcredential_infor�rrr�_do_refresh_request�s8��


��z+GceAssertionCredentials._do_refresh_requestcsttj|���Sr)rpr�AppAssertionCredentials�to_json�rrrsrrr��szGceAssertionCredentials.to_jsoncCs�t�|�}i}d|�dg�vr.|dd|d<d}d|vrD|dg}tfd|i|��}d|vrh|d|_d|vr�tj�|dtjj	�|_
d|vr�|d|_|S)Nre�kwargsr$r/r�r�r�)rAr�rCrr�r��strptimer=r2�
EXPIRY_FORMATr�r�)rx�	json_data�datar�Z
scope_listr5rrr�	from_json�s"


�
z!GceAssertionCredentials.from_jsoncCstd��dS)Nz6Cannot serialize credentials for GCE service accounts.��NotImplementedErrorr�rrr�serialization_data�s�z*GceAssertionCredentials.serialization_data)Nra)�__name__�
__module__�__qualname__�__doc__rq�classmethodrzrjrlrkr�r�r�r�r�r��propertyr��
__classcell__rrrsrr�s &
!
rcsHeZdZdZ�fdd�Zedd��Zedd��Zdd	�Zd
d�Z	�Z
S)rz1Assertion credentials for Google App Engine apps.cs<t��st�d��tt�|��|_tt|�j	di|��dS)Nr�)N)
r�	DetectGaerr�r}r'�_scopesrprrq)rrr/r3rsrrrq�s�z GaeAssertionCredentials.__init__cOs,z||i|��WStjy&YdS0dSrrurwrrrrz�szGaeAssertionCredentials.GetcCst�|�}t|d�S)Nr�)rAr�r)rxr�r�rrrr��s
z!GaeAssertionCredentials.from_jsonc
Cs`ddlm}z|�|j�\}}Wn4|jyT}zt�t|���WYd}~n
d}~00||_dS)z�Refresh self.access_token.

        Args:
          _: (ignored) A function matching httplib2.Http.request's signature.
        r)�app_identityN)	Zgoogle.appengine.apir��get_access_tokenr�rvrr-�strr�)rr�_r��tokenr_rrrr��s$z GaeAssertionCredentials._refreshcCstd��dS)auCryptographically sign a blob (of bytes).

        This method is provided to support a common interface, but
        the actual key used for a Google Compute Engine service account
        is not available, so it can't be used to sign content.

        Args:
            blob: bytes, Message to be signed.

        Raises:
            NotImplementedError, always.
        z1Compute Engine service accounts cannot sign blobsNr�)rr�blobrrr�	sign_blob�s
�z!GaeAssertionCredentials.sign_blob)r�r�r�r�rqr�rzr�r�r�r�rrrsrr�s

rcCs\tjtjgd�}|j|d�\}}ttd�r2tj|_ttd�rDtj|_ttd�rXtj	|_
|S)z4Retrieves command line flags based on gflags module.)�parents�ry�auth_host_name�auth_host_port�auth_local_webserver)�argparse�ArgumentParserrZ	argparserZparse_known_args�hasattr�FLAGSr�r�r�Znoauth_local_webserver)ry�parser�flagsr�rrr�_GetRunFlowFlagss



r�cCsL|d}|d}t|tj�s&d�|�}|d||}trHt�||�}nt�||�}t	t
d�rddt
_|��}|dus||j
�rHtd�td	�D]�}z6tjjfi|��}	t|d
�}
t�|	||
�}W�qHWq�tjjtf�y}ztd|f�WYd}~q�d}~0tj�yD}z(td|f�t�d
|��WYd}~q�d}~00q�|S)zRead credentials from a file.r%r$�:r"r�FNz$Generating new OAuth credentials ...�r�zInvalid authorization: %szCommunication error: %sz,Communication error creating credentials: %s)�
isinstancerg�string_typesr(�_NEW_FILESTORErZMultiprocessFileStorager
Z(get_credential_storage_custom_string_keyr�r�r�rCr��print�ranger=r2�OAuth2WebServerFlowr�rZrun_flow�FlowExchangeError�
SystemExit�httplib2�
HttpLib2Errorrr-)r+r4r&r%Z	scope_keyZstorage_keyZcredential_storer5r��flowr�r_rrrrs>
��

"�rc@s\eZdZdZdZdZe��Zdd�Z	e
jdd��Ze
jdd	��Z
d
d�Zdd
�Zdd�ZdS)r~aOSimple multithreading and multiprocessing safe cache file.

    Notes on behavior:
    * the fasteners.InterProcessLock object cannot reliably prevent threads
      from double-acquiring a lock. A threading lock is used in addition to
      the InterProcessLock. The threading lock is always acquired first and
      released last.
    * The interprocess lock will not deadlock. If a process can not acquire
      the interprocess lock within `_lock_timeout` the call will return as
      a cache miss or unsuccessful cache write.
    * App Engine environments cannot be process locked because (1) the runtime
      does not provide monotonic time and (2) different processes may or may
      not share the same machine. Because of this, process locks are disabled
      and locking is only guaranteed to protect against multithreaded access.
    �rbcCs>d|_||_tr,|j|_t�d�|��|_n|j	|_d|_dS)Nz{0}.lock)
�_file�	_filename�_FASTENERS_AVAILABLE�_ProcessLockAcquired�_process_lock_getter�	fastenersZInterProcessLockr��
_process_lock�_DummyLockAcquired)rrrErrrrqSs�z_MultiProcessCacheFile.__init__ccs>z(|jj|jd�}|VW|r:|j��n|r8|j��0dS)z/Context manager for process locks with timeout.)�timeoutN)r��acquire�
_lock_timeout�release)rrZ	is_lockedrrrr�^s�z+_MultiProcessCacheFile._ProcessLockAcquiredccs
dVdS)z<Lock context manager for environments without process locks.TNrr�rrrr�hsz)_MultiProcessCacheFile._DummyLockAcquiredc
Cs�d}|j��|��s$Wd�dS|���n}|sNWd�Wd�dSt|jd��"}|��j|jd�}Wd�n1s�0YWd�n1s�0YWd�n1s�0Y|S)aAcquire an interprocess lock and dump cache contents.

        This method safely acquires the locks then reads a string
        from the cache file. If the file does not exist and cannot
        be created, it will return None. If the locks cannot be
        acquired, this will also return None.

        Returns:
          cache data - string if present, None on failure.
        NrGrc)�_thread_lock�_EnsureFileExistsr�r@r�rI�decode�	_encoding)rr�
file_contents�acquired_plock�frrrrms
lz!_MultiProcessCacheFile.LockedReadc
Cs�t|tj�r|j|jd�}|j��|��s:Wd�dS|���t}|sdWd�Wd�dSt|j	d��}|�
|�Wd�n1s�0YWd�Wd�dS1s�0YWd�n1s�0YdS)a�Acquire an interprocess lock and write a string.

        This method safely acquires the locks then writes a string
        to the cache file. If the string is written successfully
        the function will return True, if the write fails for any
        reason it will return False.

        Args:
          cache_data: string or bytes to write.

        Returns:
          bool: success
        rcNF�wbT)r�rg�	text_type�encoder�r�r�r�r@r��write)rrZ
cache_datar�r�rrrr��s
(z"_MultiProcessCacheFile.LockedWritec	Csntj�|j�sjt�d�}zDzt|jd���Wn tyNYWt�|�dS0Wt�|�nt�|�0dS)z8Touches a file; returns False on error, True on success.�za+bFT)r*r+�existsr��umaskr@�close�OSError)rrZ	old_umaskrrrr��s

�z(_MultiProcessCacheFile._EnsureFileExistsN)r�r�r�r�r�r��	threading�Lockr�rq�
contextlib�contextmanagerr�r�rr�r�rrrrr~>s
	
r~cCs\|p
t��}t|�}|�|�\}}|jtjkrN|�|�t|�}|�|�\}}t�	|pXd�S)a�Get the userinfo associated with the given credentials.

    This is dependent on the token having either the userinfo.email or
    userinfo.profile scope for the given token.

    Args:
      credentials: (oauth2client.client.Credentials) incoming credentials
      http: (httplib2.Http, optional) http instance to use

    Returns:
      The email address for this token, or None if the required scopes
      aren't available.
    z{})
r��Http�_GetUserinfoUrlrR�statusr�BAD_REQUEST�refreshrAr�)r5�httpr\r^r�rrrr�s
rcCs$d}d|ji}d�|tj�|�f�S)Nz'https://oauth2.googleapis.com/tokeninfor��?)r�r(r�parse�	urlencode)r5Zurl_root�
query_argsrrrr�s
rcKsZ|d��}|d}|r&t|||d�S|r.|r6|r@|s@t�d��|durVt||||�SdS)z1Returns ServiceAccountCredentials from give file.r$r%rHz:Service account name or keyfile provided without the otherN)�splitrrr-rL)r4rJZservice_account_keyfileZservice_account_json_keyfile�unused_kwdsr/r%rrr�_GetServiceAccountCredentials�s$�����r
cKs|d�d�}tj|d�S�Nr$r!r7)rrrz�r4rr/rrr�_GetGaeServiceAccount�srcKs|d�d�}tj|d�Sr)rrrzrrrr�_GetGceServiceAccount�src	Ks�|d��}|rdStjj}t�Bz|��}Wn$tjjyRYWd�dS0Wd�n1sh0Yd}|dur�dSt||�r�||vr�|�|�SdS)zReturns ADC with right scopes.r$Nz.https://www.googleapis.com/auth/cloud-platform)	rr=r2�GoogleCredentialsr� _implicit_credentials_from_files�"ApplicationDefaultCredentialsErrorr��
create_scoped)r4Z$skip_application_default_credentialsrr/�gcr5�cprrr�!_GetApplicationDefaultCredentials�s2
r)N)NNNN)N)F)N)N)N)NNN)F)>r��
__future__rr�r�r�rAr*r�rmr�r=�oauth2client.clientrrrg�	six.movesrr�apitools.base.pyrrr�r��ImportErrorZimport_errorrQrCZ
server_env�
startswithZoauth2client.contribrrr�r
Zgflagsr��__all__r�rrrr rrrLr`r�rr2�AssertionCredentialsrr�r�objectr~rrr
rrrrrrr�<module>s�
�


�

 
a6

(n
�

�