o
    ~j6h@                     @   s  d 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ZddlZddl	Z	ddl
mZmZmZmZmZ ddlZddlmZ dZdaejdd	d
Zh dZdd Zdd Zdd Zdd ZdCddZdd ZdDddZdd Zdd Z dd  Z!d!d" Z"d#d$ Z#d%ee$e%f d&ee$e%e&f fd'd(Z'd)e&d&ee& fd*d+Z(d,ej)d&e*fd-d.Z+d,ej)d&e*fd/d0Z,d,ej)d1e&d2e&d3ee- d4eee&e&f  d&dfd5d6Z.dEd3ee- d8e&d&efd9d:Z/d;ed&efd<d=Z0d,ej)d>ed&dfd?d@Z1d,ej)d;ed&dfdAdBZ2dS )Fz-Helper functions for commonly used utilities.    N)Message)AnyDictMappingOptionalUnion)
exceptionsgoogleF   -   )minutesseconds>   id_token	client_idaccessTokenaccess_tokenclient_secretrefresh_tokenc                    s    fdd}|S )a0  Decorator that copies a method's docstring from another class.

    Args:
        source_class (type): The class that has the documented method.

    Returns:
        Callable: A decorator that will copy the docstring of the same
            named method in the source class to the decorated method.
    c                    s(   | j rtdt | j}|j | _ | S )a?  Decorator implementation.

        Args:
            method (Callable): The method to copy the docstring to.

        Returns:
            Callable: the same method passed in with an updated docstring.

        Raises:
            google.auth.exceptions.InvalidOperation: if the method already has a docstring.
        zMethod already has a docstring.)__doc__r   InvalidOperationgetattr__name__)methodsource_methodsource_class c/var/www/html/chefvision.cloud.itp360.com/venv/lib/python3.10/site-packages/google/auth/_helpers.py	decoratorA   s
   
z!copy_docstring.<locals>.decoratorr   )r   r   r   r   r   copy_docstring6   s   r   c                 C   s   t  }| |d< | S )a  Parse a 'content-type' header value to get just the plain media-type (without parameters).

    This is done using the class Message from email.message as suggested in PEP 594
        (because the cgi is now deprecated and will be removed in python 3.13,
        see https://peps.python.org/pep-0594/#cgi).

    Args:
        header_value (str): The value of a 'content-type' header as a string.

    Returns:
        str: A string with just the lowercase media-type from the parsed 'content-type' header.
            If the provided content-type is not parsable, returns 'text/plain',
            the default value for textual files.
    zcontent-type)r   get_content_type)header_valuemr   r   r   parse_content_typeX   s   r#   c                  C   s    t j t jj} | jdd} | S )z_Returns the current UTC datetime.

    Returns:
        datetime: The current time in UTC.
    N)tzinfo)datetimenowtimezoneutcreplace)r&   r   r   r   utcnown   s   r*   c                 C   s   t |  S )zConvert a datetime object to the number of seconds since the UNIX epoch.

    Args:
        value (datetime): The datetime to convert.

    Returns:
        int: The number of seconds since the UNIX epoch.
    )calendartimegmutctimetuplevaluer   r   r   datetime_to_secs~   s   	r0   utf-8c                 C   s6   t | tr
| |n| }t |tr|S td| )a  Converts a string value to bytes, if necessary.

    Args:
        value (Union[str, bytes]): The value to be converted.
        encoding (str): The encoding to use to convert unicode to bytes.
            Defaults to "utf-8".

    Returns:
        bytes: The original value converted to bytes (if unicode) or as
            passed in if it started out as bytes.

    Raises:
        google.auth.exceptions.InvalidValue: If the value could not be converted to bytes.
    z%{0!r} could not be converted to bytes)
isinstancestrencodebytesr   InvalidValueformat)r/   encodingresultr   r   r   to_bytes   s   
r:   c                 C   s6   t | tr
| dn| }t |tr|S td| )ao  Converts bytes to a string value, if necessary.

    Args:
        value (Union[str, bytes]): The value to be converted.

    Returns:
        str: The original value converted to unicode (if bytes) or as passed in
            if it started out as unicode.

    Raises:
        google.auth.exceptions.InvalidValue: If the value could not be converted to unicode.
    r1   z'{0!r} could not be converted to unicode)r2   r5   decoder3   r   r6   r7   )r/   r9   r   r   r   
from_bytes   s   
r<   c                    sn    du rg  t j| }t j|j}||  fdd| D }t jj|dd}|j|d}t j	|S )a  Updates a URL's query parameters.

    Replaces any current values if they are already present in the URL.

    Args:
        url (str): The URL to update.
        params (Mapping[str, str]): A mapping of query parameter
            keys to values.
        remove (Sequence[str]): Parameters to remove from the query string.

    Returns:
        str: The URL with updated query parameters.

    Examples:

        >>> url = 'http://example.com?a=1'
        >>> update_query(url, {'a': '2'})
        http://example.com?a=2
        >>> update_query(url, {'b': '3'})
        http://example.com?a=1&b=3
        >> update_query(url, {'b': '3'}, remove=['a'])
        http://example.com?b=3

    Nc                    s   i | ]\}}| vr||qS r   r   ).0keyr/   remover   r   
<dictcomp>   s    z update_query.<locals>.<dictcomp>T)doseq)query)
urllibparseurlparseparse_qsrC   updateitems	urlencode_replace
urlunparse)urlparamsr@   partsquery_params	new_query	new_partsr   r?   r   update_query   s   

rS   c                 C   s
   d | S )zConverts scope value to a string suitable for sending to OAuth 2.0
    authorization servers.

    Args:
        scopes (Sequence[str]): The sequence of scopes to convert.

    Returns:
        str: The scopes formatted as a single string.
     )joinscopesr   r   r   scopes_to_string   s   

rX   c                 C   s   | sg S |  dS )zConverts stringifed scopes value to a list.

    Args:
        scopes (Union[Sequence, str]): The string of space-separated scopes
            to convert.
    Returns:
        Sequence(str): The separated scopes.
    rT   )splitrV   r   r   r   string_to_scopes   s   	
rZ   c                 C   s(   t | }|dt| d   }t|S )zDecodes base64 strings lacking padding characters.

    Google infrastructure tends to omit the base64 padding characters.

    Args:
        value (Union[str, bytes]): The encoded value.

    Returns:
        bytes: The decoded value
       =   )r:   lenbase64urlsafe_b64decode)r/   	b64stringpaddedr   r   r   padded_urlsafe_b64decode  s   
rb   c                 C   s   t | dS )au  Encodes base64 strings removing any padding characters.

    `rfc 7515`_ defines Base64url to NOT include any padding
    characters, but the stdlib doesn't do that by default.

    _rfc7515: https://tools.ietf.org/html/rfc7515#page-6

    Args:
        value (Union[str|bytes]): The bytes-like value to encode

    Returns:
        Union[str|bytes]: The encoded value
    r[   )r^   urlsafe_b64encoderstripr.   r   r   r   unpadded_urlsafe_b64encode  s   re   c                   C   s
   t jdkS )zCheck if the Python interpreter is Python 2 or 3.

    Returns:
        bool: True if the Python interpreter is Python 3 and False otherwise.
    )r
   r   )sysversion_infor   r   r   r   is_python_3"  s   
rh   datareturnc                 C   s   t | tr7i }|  D ])\}}|tv r"t |ttfs"t||||< qt |ttfr0t|||< q|||< q|S t | trLg }| D ]	}|t| q@|S tt	| S )a  
    Hashes sensitive information within a dictionary.

    Args:
        data: The dictionary containing data to be processed.

    Returns:
        A new dictionary with sensitive values replaced by their SHA512 hashes.
        If the input is a list, returns a list with each element recursively processed.
        If the input is neither a dict nor a list, returns the type of the input as a string.

    )
r2   dictrI   _SENSITIVE_FIELDSlist_hash_value_hash_sensitive_infoappendr3   type)ri   hashed_datar>   r/   hashed_listvalr   r   r   ro   +  s   


ro   
field_namec                 C   sD   | du rdS t | d}t }|| | }d| d| S )z3Hashes a value and returns a formatted hash string.Nr1   hashed_-)r3   r4   hashlibsha512rH   	hexdigest)r/   ru   encoded_valuehash_object
hex_digestr   r   r   rn   N  s   
rn   loggerc                 C   s   | j g kp| jtjkp| j S )zDetermines whether `logger` has non-default configuration

    Args:
      logger: The logger to check.

    Returns:
      bool: Whether the logger has any non-default configuration.
    )handlerslevelloggingNOTSET	propagate)r~   r   r   r   _logger_configuredY  s   
r   c                 C   s,   t stt}t|sd|_da | tjS )z
    Checks if debug logging is enabled for the given logger.

    Args:
        logger: The logging.Logger instance to check.

    Returns:
        True if debug logging is enabled, False otherwise.
    FT)_LOGGING_INITIALIZEDr   	getLogger_BASE_LOGGER_NAMEr   r   isEnabledForDEBUG)r~   base_loggerr   r   r   is_logging_enabledg  s   
r   r   rM   bodyheadersc                 C   sX   t | r*|rd|v r|d nd}t||d}t|}| jdd||||did dS dS )	aE  
    Logs an HTTP request at the DEBUG level if logging is enabled.

    Args:
        logger: The logging.Logger instance to use.
        method: The HTTP method (e.g., "GET", "POST").
        url: The URL of the request.
        body: The request body (can be None).
        headers: The request headers (can be None).
    zContent-Type )content_typezMaking request...httpRequest)r   rM   r   r   extraN)r   _parse_request_bodyro   debug)r~   r   rM   r   r   r   	json_bodylogged_bodyr   r   r   request_log  s    
r   r   r   c              	   C   s   | du rdS z|  d}W n ttfy   Y dS w | }|r$d|v r9zt|W S  tjtfy8   | Y S w d|v rNtj	
|}dd | D }|S d|v rT|S dS )a  
    Parses a request body, handling bytes and string types, and different content types.

    Args:
        body (Optional[bytes]): The request body.
        content_type (str): The content type of the request body, e.g., "application/json",
            "application/x-www-form-urlencoded", or "text/plain". If empty, attempts
            to parse as JSON.

    Returns:
        Parsed body (dict, str, or None).
        - JSON: Decodes if content_type is "application/json" or None (fallback).
        - URL-encoded: Parses if content_type is "application/x-www-form-urlencoded".
        - Plain text: Returns string if content_type is "text/plain".
        - None: Returns if body is None, UTF-8 decode fails, or content_type is unknown.
    Nr1   zapplication/jsonz!application/x-www-form-urlencodedc                 S   s   i | ]	\}}||d  qS )r   r   )r=   kvr   r   r   rA     s    z'_parse_request_body.<locals>.<dictcomp>z
text/plain)r;   UnicodeDecodeErrorAttributeErrorlowerjsonloadsJSONDecodeError	TypeErrorrD   rE   rG   rI   )r   r   body_strparsed_queryr9   r   r   r   r     s*   r   responsec                 C   s$   z|   }|W S  ty   Y dS w )a  
    Parses a response, attempting to decode JSON.

    Args:
        response: The response object to parse. This can be any type, but
            it is expected to have a `json()` method if it contains JSON.

    Returns:
        The parsed response. If the response contains valid JSON, the
        decoded JSON object (e.g., a dictionary or list) is returned.
        If the response does not have a `json()` method or if the JSON
        decoding fails, None is returned.
    N)r   	Exception)r   json_responser   r   r   _parse_response  s   r   parsed_responsec                 C   s   t |}| jdd|id dS )a  
    Logs a parsed HTTP response at the DEBUG level.

    This internal helper function takes a parsed response and logs it
    using the provided logger. It also applies a hashing function to
    potentially sensitive information before logging.

    Args:
        logger: The logging.Logger instance to use for logging.
        parsed_response: The parsed HTTP response object (e.g., a dictionary,
            list, or the original response if parsing failed).
    zResponse received...httpResponser   N)ro   r   )r~   r   logged_responser   r   r   _response_log_base  s   r   c                 C   s"   t | rt|}t| | dS dS )z
    Logs an HTTP response at the DEBUG level if logging is enabled.

    Args:
        logger: The logging.Logger instance to use.
        response: The HTTP response object to log.
    N)r   r   r   )r~   r   r   r   r   r   response_log  s   r   )r1   )N)r   )3r   r^   r+   r%   email.messager   rx   r   r   rf   typingr   r   r   r   r   rD   google.authr   r   r   	timedeltaREFRESH_THRESHOLDrl   r   r#   r*   r0   r:   r<   rS   rX   rZ   rb   re   rh   rk   rm   r3   ro   rn   Loggerboolr   r   r5   r   r   r   r   r   r   r   r   r   <module>   sb   
"

-$	#
$&