o
    tBhd                     @   s0  d dl Z d dlZd dlZd dlZd dlZd dlZd dlZd dlZd dl	m
Z
 d dlmZ d dlmZ ejjZdZdd Zdd	 Zd
d Zejejejf Zdd Zdd Zedg dZdd Z											d$ddZdZdZedddddddddddfddZ dd Z!dd Z"d d! Z#d"d# Z$dS )%    N)
exceptions)requests)_helpersz[https://googleapis.dev/python/google-api-core/latest/auth.html#setting-up-a-service-accountc                 C   s(   t | tjjjstdt| tdS )ai  Raise AttributeError if the credentials are unsigned.

    :type credentials: :class:`google.auth.credentials.Signing`
    :param credentials: The credentials used to create a private key
                        for signing text.

    :raises: :exc:`AttributeError` if credentials is not an instance
            of :class:`google.auth.credentials.Signing`.
    zyou need a private key to sign credentials.the credentials you are currently using {} just contains a token. see {} for more details.N)	
isinstancegoogleauthcredentialsSigningAttributeErrorformattypeSERVICE_ACCOUNT_URL)r    r   t/var/www/html/riverr-enterprise-integrations-main/venv/lib/python3.10/site-packages/google/cloud/storage/_signing.pyensure_signed_credentials(   s   
r   c                 C   s4   t |  | |d}t|}| j}|||dS )a  Gets query parameters for creating a signed URL.

    :type credentials: :class:`google.auth.credentials.Signing`
    :param credentials: The credentials used to create a private key
                        for signing text.

    :type expiration: int or long
    :param expiration: When the signed URL should expire.

    :type string_to_sign: str
    :param string_to_sign: The string to be signed by the credentials.

    :raises: :exc:`AttributeError` if credentials is not an instance
            of :class:`google.auth.credentials.Signing`.

    :rtype: dict
    :returns: Query parameters matching the signing credentials with a
              signed payload.
    asciiGoogleAccessIdExpires	Signature)r   
sign_bytesencodebase64	b64encodesigner_email)r   
expirationstring_to_signsignature_bytes	signatureservice_account_namer   r   r   get_signed_query_params_v2;   s   
r    c                 C   sb   t | tjrt jtjd}||  } t | tjr!t| }|d } t | tj	s/t
dt|  | S )a  Convert 'expiration' to a number of seconds in the future.

    :type expiration: Union[Integer, datetime.datetime, datetime.timedelta]
    :param expiration: Point in time when the signed URL should expire. If
                       a ``datetime`` instance is passed without an explicit
                       ``tzinfo`` set,  it will be assumed to be ``UTC``.

    :raises: :exc:`TypeError` when expiration is not a valid type.

    :rtype: int
    :returns: a timestamp as an absolute number of seconds since epoch.
    tzinfoi@B =Expected an integer timestamp, datetime, or timedelta. Got %s)r   datetime	timedeltaNOWreplacer   UTC_microseconds_from_datetimesixinteger_types	TypeErrorr   )r   nowmicrosr   r   r   get_expiration_seconds_v2Z   s   
r/   c                 C   s   t | tstdt|  t jtjd}t | tj	r| }t | t
j
r3| jdu r/| jtjd} | | } t | t
jr?t|  }|tkrJtdt|S )aV  Convert 'expiration' to a number of seconds offset from the current time.

    :type expiration: Union[Integer, datetime.datetime, datetime.timedelta]
    :param expiration: Point in time when the signed URL should expire. If
                       a ``datetime`` instance is passed without an explicit
                       ``tzinfo`` set,  it will be assumed to be ``UTC``.

    :raises: :exc:`TypeError` when expiration is not a valid type.
    :raises: :exc:`ValueError` when expiration is too large.
    :rtype: Integer
    :returns: seconds in the future when the signed URL will expire
    r#   r!   Nz0Max allowed expiration interval is seven days {})r   _EXPIRATION_TYPESr,   r   r&   r'   r   r(   r*   r+   r$   r"   r%   inttotal_seconds
SEVEN_DAYS
ValueErrorr   )r   r-   secondsr   r   r   get_expiration_seconds_v4|   s(   

r6   c                 C   s   | du rg } nt | trt|  } | sg g fS tt}| D ]\}}|  }d|	 }|| 
| qtdd | D }dd |D }||fS )am  Canonicalize headers for signing.

    See:
    https://cloud.google.com/storage/docs/access-control/signed-urls#about-canonical-extension-headers

    :type headers: Union[dict|List(Tuple(str,str))]
    :param headers:
        (Optional) Additional HTTP headers to be included as part of the
        signed URLs.  See:
        https://cloud.google.com/storage/docs/xml-api/reference-headers
        Requests using the signed URL *must* pass the specified header
        (name and value) with each request for the URL.

    :rtype: str
    :returns: List of headers, normalized / sortted per the URL refernced above.
    N c                 s   s"    | ]\}}|d  |fV  qdS ),N)join).0keyvalr   r   r   	<genexpr>   s     z(get_canonical_headers.<locals>.<genexpr>c                 S   s   g | ]}d j | qS )z{}:{})r   )r:   itemr   r   r   
<listcomp>   s    z)get_canonical_headers.<locals>.<listcomp>)r   dictlistitemscollectionsdefaultdictlowerstripr9   splitappendsorted)headers
normalizedr;   r<   ordered_headerscanonical_headersr   r   r   get_canonical_headers   s   

rN   
_Canonical)methodresourcequery_parametersrJ   c                 C   sx   t |\}}| dkrd} |d |du rt| |g |S tdd | D }tjjj	|}d
||}t| |||S )ah  Canonicalize method, resource per the V2 spec.

    :type method: str
    :param method: The HTTP verb that will be used when requesting the URL.
                   Defaults to ``'GET'``. If method is ``'RESUMABLE'`` then the
                   signature will additionally contain the `x-goog-resumable`
                   header, and the method changed to POST. See the signed URL
                   docs regarding this flow:
                   https://cloud.google.com/storage/docs/access-control/signed-urls

    :type resource: str
    :param resource: A pointer to a specific resource
                     (typically, ``/bucket-name/path/to/blob.txt``).

    :type query_parameters: dict
    :param query_parameters:
        (Optional) Additional query parameters to be included as part of the
        signed URLs.  See:
        https://cloud.google.com/storage/docs/xml-api/reference-headers#query

    :type headers: Union[dict|List(Tuple(str,str))]
    :param headers:
        (Optional) Additional HTTP headers to be included as part of the
        signed URLs.  See:
        https://cloud.google.com/storage/docs/xml-api/reference-headers
        Requests using the signed URL *must* pass the specified header
        (name and value) with each request for the URL.

    :rtype: :class:_Canonical
    :returns: Canonical method, resource, query_parameters, and headers.
    	RESUMABLEPOSTzx-goog-resumable:startNc                 s   s,    | ]\}}|  |r| pd fV  qdS ) N)rE   rF   r:   r;   valuer   r   r   r=      s
    
z"canonicalize_v2.<locals>.<genexpr>z{}?{})rN   rH   rO   rI   rB   r*   movesurllibparse	urlencoder   )rP   rQ   rR   rJ   _normalized_qp
encoded_qpcanonical_resourcer   r   r   canonicalize_v2   s    
r`   rU   GETc                 C   s   t |}t||||
}|j|pd|pdt|g}||j ||j d|}|r:|r:t	|||}|||d}nt
| ||}|durH||d< |durP||d< |	durX|	|d< ||j t| }dj||tjjj|d	S )
a6  Generate a V2 signed URL to provide query-string auth'n to a resource.

    .. note::

        Assumes ``credentials`` implements the
        :class:`google.auth.credentials.Signing` interface. Also assumes
        ``credentials`` has a ``signer_email`` property which
        identifies the credentials.

    .. note::

        If you are on Google Compute Engine, you can't generate a signed URL.
        Follow `Issue 922`_ for updates on this. If you'd like to be able to
        generate a signed URL from GCE, you can use a standard service account
        from a JSON file rather than a GCE service account.

    See headers `reference`_ for more details on optional arguments.

    .. _Issue 922: https://github.com/GoogleCloudPlatform/                   google-cloud-python/issues/922
    .. _reference: https://cloud.google.com/storage/docs/reference-headers

    :type credentials: :class:`google.auth.credentials.Signing`
    :param credentials: Credentials object with an associated private key to
                        sign text.

    :type resource: str
    :param resource: A pointer to a specific resource
                     (typically, ``/bucket-name/path/to/blob.txt``).
                     Caller should have already URL-encoded the value.

    :type expiration: Union[Integer, datetime.datetime, datetime.timedelta]
    :param expiration: Point in time when the signed URL should expire. If
                       a ``datetime`` instance is passed without an explicit
                       ``tzinfo`` set,  it will be assumed to be ``UTC``.

    :type api_access_endpoint: str
    :param api_access_endpoint: (Optional) URI base. Defaults to empty string.

    :type method: str
    :param method: The HTTP verb that will be used when requesting the URL.
                   Defaults to ``'GET'``. If method is ``'RESUMABLE'`` then the
                   signature will additionally contain the `x-goog-resumable`
                   header, and the method changed to POST. See the signed URL
                   docs regarding this flow:
                   https://cloud.google.com/storage/docs/access-control/signed-urls


    :type content_md5: str
    :param content_md5: (Optional) The MD5 hash of the object referenced by
                        ``resource``.

    :type content_type: str
    :param content_type: (Optional) The content type of the object referenced
                         by ``resource``.

    :type response_type: str
    :param response_type: (Optional) Content type of responses to requests for
                          the signed URL. Ignored if content_type is set on
                          object/blob metadata.

    :type response_disposition: str
    :param response_disposition: (Optional) Content disposition of responses to
                                 requests for the signed URL.

    :type generation: str
    :param generation: (Optional) A value that indicates which generation of
                       the resource to fetch.

    :type headers: Union[dict|List(Tuple(str,str))]
    :param headers:
        (Optional) Additional HTTP headers to be included as part of the
        signed URLs.  See:
        https://cloud.google.com/storage/docs/xml-api/reference-headers
        Requests using the signed URL *must* pass the specified header
        (name and value) with each request for the URL.

    :type service_account_email: str
    :param service_account_email: (Optional) E-mail address of the service account.

    :type access_token: str
    :param access_token: (Optional) Access token for a service account.

    :type query_parameters: dict
    :param query_parameters:
        (Optional) Additional query parameters to be included as part of the
        signed URLs.  See:
        https://cloud.google.com/storage/docs/xml-api/reference-headers#query

    :raises: :exc:`TypeError` when expiration is not a valid type.
    :raises: :exc:`AttributeError` if credentials is not an instance
            of :class:`google.auth.credentials.Signing`.

    :rtype: str
    :returns: A signed URL you can use to access the resource
              until expiration.
    rU   
r   Nresponse-content-typeresponse-content-disposition
generationz"{endpoint}{resource}?{querystring})endpointrQ   querystring)r/   r`   rP   strextendrJ   rH   rQ   r9   _sign_messager    updaterR   rI   rB   r   r*   rX   rY   rZ   r[   )r   rQ   r   api_access_endpointrP   content_md5content_typeresponse_typeresponse_dispositionre   rJ   rR   service_account_emailaccess_tokenexpiration_stamp	canonicalelements_to_signr   r   signed_query_paramssorted_signed_query_paramsr   r   r   generate_signed_url_v2  s@   q
rx   i:	 zhttps://storage.googleapis.comc           $      C   s@  t |}|du rt \}}n|}|dd }|}|r|s#t|  | j}d|}d||}|
du r4i }
|dur<||
d< |durD||
d< dd |
D }d	|vrZtjjj	|j
|
d
< | dkrfd}d|
d< t|
\}}d|d }ddd |D }|du ri }n	dd | D }d|d< ||d< ||d< ||d< ||d< |dur||d< |dur||d< |	dur|	|d< t|}t|}d|v r|d }nd}||||||g}d|}t|d }d|||g} d| }!|r|rt|!||}"t|"}#t|#d}"n| |!d}#t|#d}"d ||||"S )!a  Generate a V4 signed URL to provide query-string auth'n to a resource.

    .. note::

        Assumes ``credentials`` implements the
        :class:`google.auth.credentials.Signing` interface. Also assumes
        ``credentials`` has a ``signer_email`` property which
        identifies the credentials.

    .. note::

        If you are on Google Compute Engine, you can't generate a signed URL.
        Follow `Issue 922`_ for updates on this. If you'd like to be able to
        generate a signed URL from GCE, you can use a standard service account
        from a JSON file rather than a GCE service account.

    See headers `reference`_ for more details on optional arguments.

    .. _Issue 922: https://github.com/GoogleCloudPlatform/                   google-cloud-python/issues/922
    .. _reference: https://cloud.google.com/storage/docs/reference-headers


    :type credentials: :class:`google.auth.credentials.Signing`
    :param credentials: Credentials object with an associated private key to
                        sign text. That credentials must provide signer_email
                        only if service_account_email and access_token are not
                        passed.

    :type resource: str
    :param resource: A pointer to a specific resource
                     (typically, ``/bucket-name/path/to/blob.txt``).
                     Caller should have already URL-encoded the value.

    :type expiration: Union[Integer, datetime.datetime, datetime.timedelta]
    :param expiration: Point in time when the signed URL should expire. If
                       a ``datetime`` instance is passed without an explicit
                       ``tzinfo`` set,  it will be assumed to be ``UTC``.

    :type api_access_endpoint: str
    :param api_access_endpoint: (Optional) URI base. Defaults to
                                "https://storage.googleapis.com/"

    :type method: str
    :param method: The HTTP verb that will be used when requesting the URL.
                   Defaults to ``'GET'``. If method is ``'RESUMABLE'`` then the
                   signature will additionally contain the `x-goog-resumable`
                   header, and the method changed to POST. See the signed URL
                   docs regarding this flow:
                   https://cloud.google.com/storage/docs/access-control/signed-urls


    :type content_md5: str
    :param content_md5: (Optional) The MD5 hash of the object referenced by
                        ``resource``.

    :type content_type: str
    :param content_type: (Optional) The content type of the object referenced
                         by ``resource``.

    :type response_type: str
    :param response_type: (Optional) Content type of responses to requests for
                          the signed URL. Ignored if content_type is set on
                          object/blob metadata.

    :type response_disposition: str
    :param response_disposition: (Optional) Content disposition of responses to
                                 requests for the signed URL.

    :type generation: str
    :param generation: (Optional) A value that indicates which generation of
                       the resource to fetch.

    :type headers: dict
    :param headers:
        (Optional) Additional HTTP headers to be included as part of the
        signed URLs.  See:
        https://cloud.google.com/storage/docs/xml-api/reference-headers
        Requests using the signed URL *must* pass the specified header
        (name and value) with each request for the URL.

    :type query_parameters: dict
    :param query_parameters:
        (Optional) Additional query parameters to be included as part of the
        signed URLs.  See:
        https://cloud.google.com/storage/docs/xml-api/reference-headers#query

    :type service_account_email: str
    :param service_account_email: (Optional) E-mail address of the service account.

    :type access_token: str
    :param access_token: (Optional) Access token for a service account.

    :raises: :exc:`TypeError` when expiration is not a valid type.
    :raises: :exc:`AttributeError` if credentials is not an instance
            of :class:`google.auth.credentials.Signing`.

    :rtype: str
    :returns: A signed URL you can use to access the resource
              until expiration.
    N   z{}/auto/storage/goog4_requestz{}/{}zContent-TypezContent-MD5c                 S   s   g | ]}|  qS r   )rE   )r:   r;   r   r   r   r?   4      z*generate_signed_url_v4.<locals>.<listcomp>hostHostrS   rT   startzx-goog-resumablerb   ;c                 S   s   g | ]\}}|qS r   r   )r:   r;   r\   r   r   r   r?   @  rz   c                 S   s   i | ]	\}}||p
d qS )rU   r   rV   r   r   r   
<dictcomp>E  s    z*generate_signed_url_v4.<locals>.<dictcomp>zGOOG4-RSA-SHA256zX-Goog-AlgorithmzX-Goog-CredentialzX-Goog-DatezX-Goog-ExpireszX-Goog-SignedHeadersrc   rd   re   zx-goog-content-sha256zUNSIGNED-PAYLOADr   z{}{}?{}&X-Goog-Signature={})r6   get_v4_now_dtstampsr   r   r   r*   rX   rY   rZ   urlparsenetlocupperrN   r9   rB   _url_encoder@   hashlibsha256r   	hexdigestrj   r   	b64decodebinasciihexlifydecoder   )$r   rQ   r   rl   rP   rm   rn   ro   rp   re   rJ   rR   rq   rr   _request_timestampexpiration_secondsrequest_timestamp	datestampclient_emailcredential_scope
credentialheader_namesrM   rL   canonical_header_stringsigned_headerscanonical_query_stringlowercased_headerspayloadcanonical_elementscanonical_requestcanonical_request_hashstring_elementsr   r   r   r   r   r   generate_signed_url_v4  s   v




r   c                  C   s&   t  } | d}|  d}||fS )z~Get current timestamp and datestamp in V4 valid format.

    :rtype: str, str
    :returns: Current timestamp, datestamp.
    z%Y%m%dT%H%M%SZz%Y%m%d)r&   strftimedate)r-   	timestampr   r   r   r   r     s   
r   c           
      C   s   t | } d}d|}d| dd}tdt| di}t	 }|||||d}|j
tjjjkr=td	|jt|jd}	|	d
 S )a  Signs a message.

    :type message: str
    :param message: The message to be signed.

    :type access_token: str
    :param access_token: Access token for a service account.


    :type service_account_email: str
    :param service_account_email: E-mail address of the service account.

    :raises: :exc:`TransportError` if an `access_token` is unauthorized.

    :rtype: str
    :returns: The signature of the message.

    rT   zXhttps://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/{}:signBlob?alt=jsonzBearer zapplication/json)AuthorizationzContent-typer   zutf-8)urlrP   bodyrJ   z'Error calling the IAM signBytes API: {}
signedBlob)r   	_to_bytesr   jsondumpsr   r   r   r   Requeststatusr*   rX   http_clientOKr   TransportErrordataloads)
messagerr   rq   rP   r   rJ   r   requestresponser   r   r   r   rj     s"   

rj   c                 C   s    dd |   D }dt|S )zEncode query params into URL.

    :type query_params: dict
    :param query_params: Query params to be encoded.

    :rtype: str
    :returns: URL encoded query params.
    c                 S   s$   g | ]\}}d  t|t|qS )z{}={})r   _quote_param)r:   namerW   r   r   r   r?     s    z_url_encode.<locals>.<listcomp>&)rB   r9   rI   )query_paramsparamsr   r   r   r     s   	r   c                 C   s&   t | ts	t| } tjjjj| ddS )zQuote query param.

    :type param: Any
    :param param: Query param to be encoded.

    :rtype: str
    :returns: URL encoded query param.
    ~)safe)r   bytesrh   r*   rX   rY   rZ   quote)paramr   r   r   r     s   
	r   )rU   ra   NNNNNNNNN)%r   r   rC   r$   r   r   r*   google.auth.credentialsr   google.authr   google.auth.transportr   google.cloudr   utcnowr&   r   r   r    r/   r+   r%   r0   r6   rN   
namedtuplerO   r`   rx   r3   DEFAULT_ENDPOINTr   r   rj   r   r   r   r   r   r   <module>   sr   *%6
  
 ^,