
    4P@iX@                         d Z ddlZddlmZ ddlZddlZddlZddlm	Z	 ddl
Z
ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ dd	lmZ dd
lmZ  ej*                  e      ZdZdZeegZ ej6                  ej8                  d      Zes ej6                  ej<                  e      Zd Zde fdZ!de fdZ"dZ#dZ$e#e$iZ%	  e& ej6                  dd            Z'dZ)dZ*d Z+d Z,d!d"dZ-e'dfdZ.dddddde'fdZ/d Z0d Z1d#dZ2d$d Z3y# e($ r dZ'Y 8w xY w)%zProvides helper methods for talking to the Compute Engine metadata server.

See https://cloud.google.com/compute/docs/metadata for more details.
    N)urljoin)_helpers)environment_vars)
exceptions)metrics)	transport)ExponentialBackoff)_mtlsz169.254.169.254zmetadata.google.internalc                      t        j                         } | t         j                  j                  k(  r"t        t
        vrt        j                  d      yy)a  Validates the GCE metadata server environment configuration for mTLS.

    mTLS is only supported when connecting to the default metadata server hosts.
    If we are in strict mode (which requires mTLS), ensure that the metadata host
    has not been overridden to a custom value (which means mTLS will fail).

    Raises:
        google.auth.exceptions.MutualTLSChannelError: if the environment
            configuration is invalid for mTLS.
    zMutual TLS is required, but the metadata host has been overridden. mTLS is only supported when connecting to the default metadata host.N)r
   _parse_mds_modeMdsMtlsModeSTRICT_GCE_METADATA_HOST_GCE_DEFAULT_MDS_HOSTSr   MutualTLSChannelError)modes    n/home/www/lebenam.kofcorporation.com/venv/lib/python3.12/site-packages/google/auth/compute_engine/_metadata.py(_validate_gce_mds_configured_environmentr   7   sT       "Du  ''' %;;22W  <	 (    use_mtlsc                 :    | rdnd}dj                  |t              S )z%Returns the metadata server root URL.httpshttpz{}://{}/computeMetadata/v1/)formatr   r   schemes     r   _get_metadata_rootr   N   s!     !WfF(//8JKKr   c                 ~    | rdnd}dj                  |t        j                  t        j                  t
                    S )z(Returns the metadata server IP root URL.r   r   z{}://{})r   osgetenvr   GCE_METADATA_IP_GCE_DEFAULT_MDS_IPr   s     r   _get_metadata_ip_rootr#   U   s6     WfF		*::<OP r   zmetadata-flavorGoogleGCE_METADATA_TIMEOUT   z/sys/class/dmi/id/product_namec                 V    t        |       ryt        j                  dk(  ryt               S )a  Checks to see if the code runs on Google Compute Engine

    Args:
        request (google.auth.transport.Request): A callable used to make
            HTTP requests.

    Returns:
        bool: True if the code runs on Google Compute Engine, False otherwise.
    TntF)pingr   namedetect_gce_residency_linuxrequests    r   	is_on_gcer.   m   s'     G}	ww$ &''r   c                      	 t        t        d      5 } | j                         j                         }ddd       j                  t              S # 1 sw Y   xY w# t        $ r Y yw xY w)zDetect Google Compute Engine residency by smbios check on Linux

    Returns:
        bool: True if the GCE product name file is detected, False otherwise.
    rNF)open_GCE_PRODUCT_NAME_FILEreadstrip	Exception
startswith_GOOGLE)file_objcontents     r   r+   r+      sc    (#. 	.(mmo++-G	. g&&	. 	.  s'   A AA AA 	A&%A&Fc                     |re| j                   st        j                         | _         t        j                         }t
        D ]"  }| j                   j                  d| d|       $ yy)a  Prepares a request for the metadata server.

    This will check if mTLS should be used and mount the mTLS adapter if needed.

    Args:
        request (google.auth.transport.Request): A callable used to make
            HTTP requests.
        use_mtls (bool): Whether to use mTLS for the request.

    Returns:
        google.auth.transport.Request: A request object to use.
            If mTLS is enabled, the request will have the mTLS adapter mounted.
            Otherwise, the original request will be returned unchanged.
    zhttps:///N)sessionrequestsSessionr
   MdsMtlsAdapterr   mount)r-   r   adapterhosts       r   _prepare_request_for_mdsrC      s]      &..0GO&&(* 	?DOO!!HTF!"4g>	? r   c                 
   t        j                         }t        | |       t        j	                         }t        j                         |t
        j                  <   t        |      }|D ]`  }	  | t        |      d||      }|j                  j                  t              }|j                  t        j                  k(  xr	 |t         k(  c S  y# t"        j$                  $ r"}	t&        j)                  d|||	       Y d}	~	d}	~	ww xY w)a  Checks to see if the metadata server is available.

    Args:
        request (google.auth.transport.Request): A callable used to make
            HTTP requests.
        timeout (int): How long to wait for the metadata server to respond.
        retry_count (int): How many times to attempt connecting to metadata
            server using above timeout.

    Returns:
        bool: True if the metadata server is reachable, False otherwise.
    r   total_attemptsGETurlmethodheaderstimeoutJCompute Engine Metadata server unavailable on attempt %s of %s. Reason: %sNF)r
   should_use_mds_mtlsrC   _METADATA_HEADERScopyr   mds_pingAPI_CLIENT_HEADERr	   r#   rL   get_METADATA_FLAVOR_HEADERstatushttp_clientOK_METADATA_FLAVOR_VALUEr   TransportError_LOGGERwarning)
r-   rM   retry_countr   rL   backoffattemptresponsemetadata_flavores
             r   r)   r)      s     ((*HWx8  $$&G)0)9)9);GG%%& <G 	)(3	H '..223JKO;>>1 >#'==0  (( 	OO/ 	s   -ACD C==D   c	                 4   t        j                         }	t        | |	       |t        |	      }t	                t        ||      }
|i n|}t        j                         }|r|j                  |       |rd|d<   t        j                  |
|      }t        |      }d}|D ]  }	  | |d||      }|j                  t        j                  v r`t        j!                  d|||j                         t#        |j$                  d	      r|j$                  j'                  d
      n|j$                  } n& t)        j*                  dj-                  ||            t        j.                  |j$                        }|j                  t0        j2                  k(  r|ry|j                  t0        j4                  k(  r=t        j6                  |j8                  d         dk(  r	 t;        j<                  |      S |S t)        j*                  dj-                  ||j                  |j$                        |      # t(        j*                  $ r%}t        j!                  d|||       |}Y d}~d}~ww xY w# t>        $ r,}t)        j*                  dj-                  |            }||d}~ww xY w)ak  Fetch a resource from the metadata server.

    Args:
        request (google.auth.transport.Request): A callable used to make
            HTTP requests.
        path (str): The resource to retrieve. For example,
            ``'instance/service-accounts/default'``.
        root (Optional[str]): The full path to the metadata server root. If not
            provided, the default root will be used.
        params (Optional[Mapping[str, str]]): A mapping of query parameter
            keys to values.
        recursive (bool): Whether to do a recursive query of metadata. See
            https://cloud.google.com/compute/docs/metadata#aggcontents for more
            details.
        retry_count (int): How many times to attempt connecting to metadata
            server using above timeout.
        headers (Optional[Mapping[str, str]]): Headers for the request.
        return_none_for_not_found_error (Optional[bool]): If True, returns None
            for 404 error instead of throwing an exception.
        timeout (int): How long to wait, in seconds for the metadata server to respond.

    Returns:
        Union[Mapping, str]: If the metadata server returns JSON, a mapping of
            the decoded JSON is returned. Otherwise, the response content is
            returned as a string.

    Raises:
        google.auth.exceptions.TransportError: if an error occurred while
            retrieving metadata.
        google.auth.exceptions.MutualTLSChannelError: if using mtls and the environment
            configuration is invalid for mTLS (for example, the metadata host
            has been overridden in strict mTLS mode).

    rE   Ntrue	recursiverF   rH   rI   zSCompute Engine Metadata server unavailable on attempt %s of %s. Response status: %sdecodezutf-8rN   z{Failed to retrieve {} from the Google Compute Engine metadata service. Compute Engine Metadata server unavailable due to {}zcontent-typezapplication/jsonzMReceived invalid JSON from the Google Compute Engine metadata service: {:.20}z^Failed to retrieve {} from the Google Compute Engine metadata service. Status: {} Response:
{}) r
   rO   rC   r   r   r   rP   rQ   updater   update_queryr	   rV   r   DEFAULT_RETRYABLE_STATUS_CODESr[   r\   hasattrdatarg   r   rZ   r   
from_bytesrW   	NOT_FOUNDrX   parse_content_typerL   jsonloads
ValueError)r-   pathrootparamsrf   r]   rL   return_none_for_not_found_errorrM   r   base_urlquery_paramsheaders_to_userJ   r^   failure_reasonr_   r`   rb   r9   
caught_excnew_excs                         r   rT   rT      s{   Z ((*H Wx8|!(+
 -.tT"H2VL&++-Ng&$*[!


,
7C <GN %
	~wH )"J"JJ<OO x}}h7 MM((1! 
 )%
@ ''UU[U[^V
 	
 !!(--0G+///4S+..(''(8(8(HI!".zz'** N

#
#	55;V(--6
 	 M (( 	OO/ N	:  .$33//5vg :-.s1   #BH'I" 'I:II"	J+'JJc                     t        | d      S )aO  Get the Google Cloud Project ID from the metadata server.

    Args:
        request (google.auth.transport.Request): A callable used to make
            HTTP requests.

    Returns:
        str: The project ID

    Raises:
        google.auth.exceptions.TransportError: if an error occurred while
            retrieving metadata.
    zproject/project-idrT   r,   s    r   get_project_idr   o  s     w,--r   c                 (    t        | dd      }|sy|S )a  Get the universe domain value from the metadata server.

    Args:
        request (google.auth.transport.Request): A callable used to make
            HTTP requests.

    Returns:
        str: The universe domain value. If the universe domain endpoint is not
        not found, return the default value, which is googleapis.com

    Raises:
        google.auth.exceptions.TransportError: if an error other than
            404 occurs while retrieving metadata.
    zuniverse/universe-domainT)rv   zgoogleapis.comr~   )r-   universe_domains     r   get_universe_domainr     s$     +TO r   c                 D    dj                  |      }t        | |ddi      S )a  Get information about a service account from the metadata server.

    Args:
        request (google.auth.transport.Request): A callable used to make
            HTTP requests.
        service_account (str): The string 'default' or a service account email
            address. The determines which service account for which to acquire
            information.

    Returns:
        Mapping: The service account's information, for example::

            {
                'email': '...',
                'scopes': ['scope', ...],
                'aliases': ['default', '...']
            }

    Raises:
        google.auth.exceptions.TransportError: if an error occurred while
            retrieving metadata.
    zinstance/service-accounts/{0}/rf   re   )ru   )r   rT   )r-   service_accountrs   s      r   get_service_account_infor     s*    . ,22?CD wk6%:;;r   c                 H   |r&t        |t              sdj                  |      }d|i}nd}t        j                  t        j
                         i}dj                  |      }t        | |||      }t        j                         t        j                  |d         z   }|d   |fS )	a  Get the OAuth 2.0 access token for a service account.

    Args:
        request (google.auth.transport.Request): A callable used to make
            HTTP requests.
        service_account (str): The string 'default' or a service account email
            address. The determines which service account for which to acquire
            an access token.
        scopes (Optional[Union[str, List[str]]]): Optional string or list of
            strings with auth scopes.
    Returns:
        Tuple[str, datetime]: The access token and its expiration.

    Raises:
        google.auth.exceptions.TransportError: if an error occurred while
            retrieving metadata.
    ,scopesNz#instance/service-accounts/{0}/token)ru   rL   
expires_in)secondsaccess_token)
isinstancestrjoinr   rS   token_request_access_token_mdsr   rT   r   utcnowdatetime	timedelta)r-   r   r   ru   metrics_headerrs   
token_jsontoken_expirys           r   get_service_account_tokenr     s    $ &#&XXf%FF# 	!!7#I#I#KN 177HDWd6>JJ??$x'9'9<(( L n%|33r   )F)returnN)default)r   N)4__doc__r   http.clientclientrW   rp   loggingr   urllib.parser   r=   google.authr   r   r   r   r    google.auth._exponential_backoffr	   google.auth.compute_enginer
   	getLogger__name__r[   r"   _GCE_DEFAULT_HOSTr   r    GCE_METADATA_HOSTr   GCE_METADATA_ROOTr   boolr   r#   rU   rY   rP   int_METADATA_DEFAULT_TIMEOUTrr   r7   r2   r.   r+   rC   r)   rT   r   r   r   r    r   r   <module>r      sh  
  !   	      ( "  ! ? , '

H
%' . +-@A  RYY/AA4H "**,=
.L LD  , ! ,.DE " #IBII.Da$H I
 9 (*' ?6 4 2p 
$)%JZ.".<:"4_
  " !"s   ;D DD