
    >h f                        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 d dlmZ d dlmZ ej                  j,                  Zd	Zd
 Zd Zd Zeej                  ej:                  fZd Zd Z  ejB                  dg d      Z"d Z#	 	 	 	 	 	 	 	 	 	 	 	 ddZ$dZ%dZ&e&ddddddddddddfdZ'd Z(efdZ)d Z*d Z+y)    N)
exceptions)requests)_helpers)_DEFAULT_UNIVERSE_DOMAIN)_NOW)_UTC)DEFAULT_RETRYz[https://googleapis.dev/python/google-api-core/latest/auth.html#setting-up-a-service-accountc                     t        | t        j                  j                  j                        s(t        dj                  t        |       t                    y)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   s    a/var/www/html/DP/alpha_backend/venv/lib/python3.12/site-packages/google/cloud/storage/_signing.pyensure_signed_credentialsr   /   sJ     k6;;#:#:#B#BC vd;/1DE	
 	
 D    c                     t        |        | j                  |j                  d            }t        j                  |      }| 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_names         r   get_signed_query_params_v2r'   B   sV    ( k*!,,^-B-B7-KLO  1I&33. r   c                    t        | t        j                        rt        t              }|| z   } t        | t        j                        rt        j                  |       }|dz  } t        | t              st        dt        |       z        | 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micross      r   get_expiration_seconds_v2r1   a   s     *h0014j:%
 *h//055jAu_
j#& "&z"23
 	
 r   c                    t        | t              st        dt        |       z        t	        t
              }t        | t              r| }t        | t        j                        r1| j                   | j                  t        j                        } | |z
  } t        | t        j                        rt        | j                               }t        kD  rt        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)   tzinfoz.Max allowed expiration interval is seven days )r   _EXPIRATION_TYPESr.   r   r   r   r-   r*   r4   replacer   UTCr+   total_seconds
SEVEN_DAYS
ValueError)r"   r/   secondss      r   get_expiration_seconds_v4r<      s     j"34 "&z"23
 	

 t*C*c"*h//0$#++8<<+@J#%
*h001j..01I*VWWNr   c                    | g } n)t        | t              rt        | j                               } | sg g fS t	        j
                  t              }| D ]V  \  }}|j                         j                         }dj                  |j                               }||   j                  |       X t        d |j                         D              }|D cg c]  } dj                  |  }}||fS c c}w )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.
     c              3   H   K   | ]  \  }}|d j                  |      f  yw),N)join).0keyvals      r   	<genexpr>z(get_canonical_headers.<locals>.<genexpr>   s$     UBThc3c388C=1BTs    "z{}:{})r   dictlistitemscollectionsdefaultdictlowerstriprA   splitappendsortedr   )headers
normalizedrC   rD   ordered_headersitemcanonical_headerss          r   get_canonical_headersrU      s    " 	GT	"w}}'2v((.JSiik!hhsyy{#3s# 
 U*BRBRBTUUO;JK?4.?Ko-- Ls   C)
_Canonical)methodresourcequery_parametersrP   c                    t        |      \  }}| dk(  rd} |j                  d       |t        | |g |      S t        d |j	                         D              }t
        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:startc              3   r   K   | ]/  \  }}|j                         |xr |j                         xs d f 1 yw) N)rK   rL   )rB   rC   values      r   rE   z"canonicalize_v2.<locals>.<genexpr>   s7      2JC 
e-342s   57?)rU   rN   rV   rO   rH   urllibparse	urlencode)rW   rX   rY   rP   _normalized_qp
encoded_qpcanonical_resources           r   canonicalize_v2rh      s    @ 'w/JGQ/0&(B88 *002 M ''6J$:Qzl3f0-IIr   GETc                 D   t        |      }t        ||||
      }|j                  |xs d|xs dt        |      g}|j	                  |j
                         |j                  |j                         dj                  |      }|r|rt        ||||      }|||d}nt        | ||      }|||d<   |||d<   |	|	|d<   |j                  |j                         t        |j                               }dj                  ||t         j"                  j%                  |            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.
    r^   
r   response-content-typeresponse-content-disposition
generationz"{endpoint}{resource}?{querystring})endpointrX   querystring)r1   rh   rW   strextendrP   rN   rX   rA   _sign_messager'   updaterY   rO   rH   r   ra   rb   rc   )r   rX   r"   api_access_endpointrW   content_md5content_typeresponse_typeresponse_dispositionrn   rP   rY   service_account_emailaccess_tokenuniverse_domainexpiration_stamp	canonicalelements_to_signr#   r%   signed_query_paramssorted_signed_query_paramss                         r   generate_signed_url_v2r     s]   \ 1<2BGLI 	r	 I--.I../YY/0N
 -!L*?
	 4'"
 9)>
  7D34'>R:;,6L)y99:!'(;(A(A(C!D 066$LL**+EF 7  r   i:	 zhttps://storage.googleapis.comc                 <   t        |      }|t               \  }}n|}|dd }|}|r|st        |        | j                  }| d}| d| }|
i }
|||
d<   |||
d<   |
D cg c]  }|j	                          }}d|vr,t
        j                  j                  |      j                  |
d<   |j                         d	k(  rd
}d|
d<   t        |
      \  }}dj                  |      dz   }dj                  |D cg c]  \  }}|	 c}}      }|i }n'|j                         D ci c]  \  }}||xs d }}}d|d<   ||d<   ||d<   ||d<   ||d<   |||d<   |||d<   |	|	|d<   t        |      }t        |      }d|v r|d   } nd} |||||| g}!dj                  |!      }"t        j                   |"j#                  d            j%                         }#d|||#g}$dj                  |$      }%|rJ|rHt'        |%|||      }&t)        j*                  |&      }'t-        j.                  |'      j1                  d      }&nD| j3                  |%j#                  d            }'t-        j.                  |'      j1                  d      }&dj5                  ||||&      S c c}w c c}}w c c}}w )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-MD5hostHostr[   r\   startzx-goog-resumablerk   ;r^   zGOOG4-RSA-SHA256zX-Goog-AlgorithmzX-Goog-CredentialzX-Goog-DatezX-Goog-ExpireszX-Goog-SignedHeadersrl   rm   rn   zx-goog-content-sha256zUNSIGNED-PAYLOADr   z{}{}?{}&X-Goog-Signature={})r<   get_v4_now_dtstampsr   r!   rK   ra   rb   urlparsenetlocupperrU   rA   rH   _url_encoderF   hashlibsha256r   	hexdigestrs   r   	b64decodebinasciihexlifydecoder   r   )(r   rX   r"   ru   rW   rv   rw   rx   ry   rn   rP   rY   rz   r{   r|   _request_timestampexpiration_secondsrequest_timestamp	datestampclient_emailcredential_scope
credentialrC   header_namesrT   rR   canonical_header_stringrd   signed_headersr_   canonical_query_stringlowercased_headerspayloadcanonical_elementscanonical_requestcanonical_request_hashstring_elementsr#   r%   r$   s(                                           r   generate_signed_url_v4r     sG   d 3:>!':'<$9.&r*	 )L4!+."//#$?@ >#3"45J".!,+237CCIIK7L3\! ,,//0CDKK||~$&-"#)>w)G&		#$t+  XXAvsAsABN?O?U?U?WX?WeC",?WX+='(,6()&7]#);%&/=+, 4A01';O78)3&()9:o."44$%<=$ 	 		"45$^^  )ik 
 		O YY/N-!L*?
	 !**95$$_5<<WE	%001F1Fw1OP$$_5<<WE	(//X'=y W 4 B
 Ys   "J7J
#Jc                      t        t              j                  d      } | j                  d      }| j	                         j                  d      }||fS )z~Get current timestamp and datestamp in V4 valid format.

    :rtype: str, str
    :returns: Current timestamp, datestamp.
    Nr3   z%Y%m%dT%H%M%SZz%Y%m%d)r   r   r6   strftimedate)r/   	timestampr   s      r   r   r     sK     t*

D

)C-.I
##H-Iir   c                 *  	
 t        j                  |       } dd| d| dd|z   dd
t        j                  dt	        j
                  |       j                  d	      i      	t        j                         	
fd
}t        } ||      } |       }|j                  t        j                  j                  k7  r"t        j                  d|j                          t        j"                  |j                   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.

    r\   zhttps://iamcredentials.z/v1/projects/-/serviceAccounts/z:signBlob?alt=jsonzBearer zapplication/json)AuthorizationzContent-typer   zutf-8c                              } | S )N)urlrW   bodyrP    )responser   rP   rW   requestr   s    r   retriable_requestz(_sign_message.<locals>.retriable_request  s    s6gNr   z%Error calling the IAM signBytes API: 
signedBlob)r   	_to_bytesjsondumpsr   r    r   r   Requestr	   statushttpclientOKr   TransportErrordataloads)messager{   rz   r|   r   retrycallr   r   r   rP   rW   r   r   s            @@@@@r   rs   rs     s    0   )GF#O#44STiSjj|
}C"\1*G ::y&"2"27";"B"B7"KLMD G 
 E"#DvH$++..(''3HMM?C
 	
 ::hmm**734Dr   c           	          | j                         D cg c]  \  }}t        |       dt        |         }}}dj                  t        |            S c c}}w )zEncode query params into URL.

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

    :rtype: str
    :returns: URL encoded query params.
    =&)rH   _quote_paramrA   rO   )query_paramsnamer_   paramss       r   r   r     sb     (--//KD% 
aU 345/  
 88F6N##s   #Ac                 z    t        | t              st        |       } t        j                  j                  | d      S )zQuote query param.

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

    :rtype: str
    :returns: URL encoded query param.
    ~)safe)r   bytesrq   ra   rb   quote)params    r   r   r     s1     eU#E
<<e#..r   )r^   ri   NNNNNNNNNN),r   r   rI   r*   r   r   r   ra   google.auth.credentialsr   google.authr   google.auth.transportr   google.cloudr   google.cloud.storage._helpersr   r   r   google.cloud.storage.retryr	   utcnowNOWr   r   r'   r1   r-   r+   r5   r<   rU   
namedtuplerV   rh   r   r9   DEFAULT_ENDPOINTr   r   rs   r   r   r   r   r   <module>r      s/             " * ! B . . 4
 - 
&>> (++X-?-?@ #L".J $[##G

/Jl ]@ 
3  )!Zz	   -	2j$"/r   