o
    ×èFh3d  ã                   @   sL  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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jZdZdd	„ Zd
d„ Zdd„ Ze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)Ú_helpers)Ú_NOW)Ú_UTCz[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`.
    z…you 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   úV/var/www/html/loop/nvenv/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   sX   t | tjƒrttƒ}||  } t | tjƒrt | ¡}|d } t | tƒ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.
    i@B ú=Expected an integer timestamp, datetime, or timedelta. Got %s)
r   ÚdatetimeÚ	timedeltar   r   r   Ú_microseconds_from_datetimeÚintÚ	TypeErrorr   )r   ÚnowÚmicrosr   r   r   Úget_expiration_seconds_v2_   s   

ÿÿr+   c                 C   sŽ   t | tƒstdt| ƒ ƒ‚ttƒ}t | tƒr| }t | tjƒr.| jdu r*| j	t
jd�} | | } t | tjƒr:t|  ¡ ƒ}|tkrEt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#   N©Útzinfoz.Max allowed expiration interval is seven days )r   Ú_EXPIRATION_TYPESr(   r   r   r   r'   r$   r-   Úreplacer   ÚUTCr%   Útotal_secondsÚ
SEVEN_DAYSÚ
ValueError)r   r)   Úsecondsr   r   r   Úget_expiration_seconds_v4�   s$   
ÿÿ

r5   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   )r9   Úitemr   r   r   Ú
<listcomp>È   s    z)get_canonical_headers.<locals>.<listcomp>)r   ÚdictÚlistÚitemsÚcollectionsÚdefaultdictÚlowerÚstripr8   ÚsplitÚappendÚsorted)ÚheadersÚ
normalizedr:   r;   Úordered_headersÚcanonical_headersr   r   r   Úget_canonical_headers§   s   

rM   Ú
_Canonical)ÚmethodÚresourceÚquery_parametersrI   c                 C   sv   t |ƒ\}}| dkrd} | d¡ |du rt| |g |ƒS tdd„ | ¡ D ƒƒ}t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)rD   rE   ©r9   r:   Úvaluer   r   r   r<   ú   s
   € ÿ
ÿz"canonicalize_v2.<locals>.<genexpr>ú?)rM   rG   rN   rH   rA   ÚurllibÚparseÚ	urlencode)rO   rP   rQ   rI   Ú_Únormalized_qpÚ
encoded_qpÚcanonical_resourcer   r   r   Úcanonicalize_v2Ñ   s    
þr_   rT   Ú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 |¡d	�S )
a‰  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.
        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](https://cloud.google.com/storage/docs/reference-headers)
    for more details on optional arguments.

    :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.
    rT   Ú
r   Núresponse-content-typeúresponse-content-dispositionÚ
generationz"{endpoint}{resource}?{querystring})ÚendpointrP   Úquerystring)r+   r_   rO   ÚstrÚextendrI   rG   rP   r8   Ú_sign_messager"   ÚupdaterQ   rH   rA   r   rX   rY   rZ   )r
   rP   r   Úapi_access_endpointrO   Úcontent_md5Úcontent_typeÚresponse_typeÚresponse_dispositionrd   rI   rQ   Ú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@   mü
ýÿ
ýrw   i€:	 zhttps://storage.googleapis.comc           $      C   s>  t |ƒ}|du rtƒ \}}n|}|dd… }|}|r|s#t| ƒ | j}|› d�}|› d|› �}|
du r5i }
|dur=||
d< |durE||
d< dd„ |
D ƒ}d	|vrYtj |¡j|
d
< | ¡ dkred}d|
d< t	|
ƒ\}}d 
|¡d }d 
dd„ |D ƒ¡}|du rƒi }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.
        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](https://cloud.google.com/storage/docs/reference-headers)
    for more details on optional arguments.

    :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: 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_requestú/zContent-TypezContent-MD5c                 S   s   g | ]}|  ¡ ‘qS r   )rD   )r9   r:   r   r   r   r>   0  ó    z*generate_signed_url_v4.<locals>.<listcomp>ÚhostÚHostrR   rS   Ústartzx-goog-resumablera   ú;c                 S   s   g | ]\}}|‘qS r   r   )r9   r:   r[   r   r   r   r>   <  rz   c                 S   s   i | ]	\}}||p
d “qS )rT   r   rU   r   r   r   Ú
<dictcomp>A  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-SignedHeadersrb   rc   rd   zx-goog-content-sha256zUNSIGNED-PAYLOADr   z{}{}?{}&X-Goog-Signature={})r5   Úget_v4_now_dtstampsr   r   rX   rY   ÚurlparseÚnetlocÚupperrM   r8   rA   Ú_url_encoder?   ÚhashlibÚsha256r   Ú	hexdigestri   r   Ú	b64decodeÚbinasciiÚhexlifyÚdecoder   r   )$r
   rP   r   rk   rO   rl   rm   rn   ro   rd   rI   rQ   rp   rq   Ú_request_timestampÚexpiration_secondsÚrequest_timestampÚ	datestampÚclient_emailÚcredential_scopeÚ
credentialÚheader_namesrL   rK   Ú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”   q
ÿ
ú
ÿþü

ÿr�   c                  C   s0   t tƒjdd�} |  d¡}|  ¡  d¡}||fS )z~Get current timestamp and datestamp in V4 valid format.

    :rtype: str, str
    :returns: Current timestamp, datestamp.
    Nr,   z%Y%m%dT%H%M%SZz%Y%m%d)r   r   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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.

    rS   zXhttps://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/{}:signBlob?alt=jsonzBearer zapplication/json)ÚAuthorizationzContent-typer˜   zutf-8)ÚurlrO   ÚbodyrI   z%Error calling the IAM signBytes API: Ú
signedBlob)r   Ú	_to_bytesr   ÚjsonÚdumpsr   r   r‹   r   ÚRequestÚstatusÚhttpÚclientÚOKr   ÚTransportErrorÚdataÚloads)
Úmessagerq   rp   rO   r¢   rI   r£   ÚrequestÚresponser®   r   r   r   ri   Š  s"   
ÿþ
ÿri   c                 C   s    dd„ |   ¡ D ƒ}d t|ƒ¡S )z®Encode 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 | ]\}}t |ƒ› d t |ƒ› �‘qS )ú=)Ú_quote_param)r9   ÚnamerV   r   r   r   r>   ¾  s    ÿÿz_url_encode.<locals>.<listcomp>ú&)rA   r8   rH   )Úquery_paramsÚparamsr   r   r   r„   µ  s   	þr„   c                 C   s"   t | tƒs	t| ƒ} tjj| dd�S )z’Quote query param.

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

    :rtype: str
    :returns: URL encoded query param.
    ú~)Úsafe)r   Úbytesrg   rX   rY   Úquote)Úparamr   r   r   r´   Æ  s   
	r´   )rT   r`   NNNNNNNNN))r   r‰   rB   r$   r…   r¦   rª   rX   Úgoogle.auth.credentialsr   Úgoogle.authr   Úgoogle.auth.transportr   Úgoogle.cloudr   Úgoogle.cloud.storage._helpersr   r   ÚutcnowÚNOWr   r   r"   r+   r'   r%   r.   r5   rM   Ú
namedtuplerN   r_   rw   r2   ÚDEFAULT_ENDPOINTr�   r€   ri   r„   r´   r   r   r   r   Ú<module>   sx   ÿ&%ÿ6
ò 
ñ [+