
    .
0h 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j!        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+dS )    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                  s5t          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   s    X/var/www/html/nourish/venv/lib/python3.11/site-packages/google/cloud/storage/_signing.pyensure_signed_credentialsr   /   sY     k6;#:#BCC 
 vd;//1DEE	
 
 	

 
    c                     t          |            |                     |                    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   sd    ( k***!,,^-B-B7-K-KLLO 11I&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11 &4jj:%
 *h/00 %5jAAu_
j#&& 
 "&z"2"23
 
 	
 r   c                 
   t          | t                    st          dt          |           z            t	          t
                    }t          | t                    r| }t          | t          j                  r,| j         | 	                    t          j                  } | |z
  } t          | t          j                  r!t          |                                           }|t          k    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)   N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4 
 "&z"2"23
 
 	

 t**C*c"" *h/00 &$#++8<+@@J#%
*h011 2j..0011V*VVWWWNr   c                    | g } n6t          | t                    r!t          |                                           } | sg g fS t	          j        t                    }| D ]m\  }}|                                                                }d                    |	                                          }||         
                    |           nt          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              3   J   K   | ]\  }}|d                      |          fV  dS ),N)join).0keyvals      r   	<genexpr>z(get_canonical_headers.<locals>.<genexpr>   s5      UUhc3c388C==1UUUUUUr   c                 "    g | ]} d j         | S )z{}:{})r   )rB   items     r   
<listcomp>z)get_canonical_headers.<locals>.<listcomp>   s!    KKK4.KKKr   )r   dictlistitemscollectionsdefaultdictlowerstriprA   splitappendsorted)headers
normalizedrC   rD   ordered_headerscanonical_headerss         r   get_canonical_headersrW      s    " 	GT	"	" (w}}'' 2v(..J $ $Siikk!!hhsyy{{##3s####UU*BRBRBTBTUUUUUOKK?KKKo--r   
_Canonical)methodresourcequery_parametersrS   c                 N   t          |          \  }}| dk    rd} |                    d           |t          | |g |          S t          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              3   t   K   | ]3\  }}|                                 |r|                                pd fV  4dS ) N)rN   rO   rB   rC   values      r   rE   z"canonicalize_v2.<locals>.<genexpr>   sY        C 
e-34     r   ?)rW   rQ   rX   rR   rK   urllibparse	urlencode)rY   rZ   r[   rS   _normalized_qp
encoded_qpcanonical_resources           r   canonicalize_v2rk      s    @ 'w//JGQ/000&(B888  *0022    M ''66J$33z33f0-IIIr   r`   GETc                 t   t          |          }t          ||||
          }|j        |pd|pdt          |          g}|                    |j                   |                    |j                   d                    |          }|r|rt          ||||          }|||d}nt          | ||          }|||d<   |||d<   |	|	|d<   |                    |j                   t          |                                          }d                    ||t           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   Nresponse-content-typeresponse-content-disposition
generationz"{endpoint}{resource}?{querystring})endpointrZ   querystring)r1   rk   rY   strextendrS   rQ   rZ   rA   _sign_messager'   updater[   rR   rK   r   rd   re   rf   )r   rZ   r"   api_access_endpointrY   content_md5content_typeresponse_typeresponse_dispositionrq   rS   r[   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LLI 	r	 I-...I.///YY/00N
  
- 
!L*?
 
	 4'"
 
 9)>
 
  7D34'>R:;,6L)y9:::!'(;(A(A(C(C!D!D 066$L**+EFF 7   r   i:	 zhttps://storage.googleapis.comc                 b   t          |          }|t                      \  }}n|}|dd         }|}|r|st          |            | j        }| d}| d| }|
i }
|||
d<   |||
d<   d |
D             }d|vr't          j                            |          j        |
d	<   |                                d
k    rd}d|
d<   t          |
          \  }}d
                    |          dz   }d
                    d |D                       }|i }nd |                                D             }d|d<   ||d<   ||d<   ||d<   ||d<   |||d<   |||d<   |	|	|d<   t          |          }t          |          }d|v r	|d         }nd}||||||g}d
                    |          }t          j        |                    d                                                    } d||| g}!d
                    |!          }"|rP|rNt%          |"|||          }#t'          j        |#          }$t+          j        |$                              d          }#nO|                     |"                    d                    }$t+          j        |$                              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                 6    g | ]}|                                 S  )rN   )rB   rC   s     r   rH   z*generate_signed_url_v4.<locals>.<listcomp>6  s     333CCIIKK333r   hostHostr]   r^   startzx-goog-resumablern   ;c                     g | ]\  }}|S r   r   )rB   rC   rg   s      r   rH   z*generate_signed_url_v4.<locals>.<listcomp>B  s    AAAvsAsAAAr   c                     i | ]
\  }}||pd S )r`   r   ra   s      r   
<dictcomp>z*generate_signed_url_v4.<locals>.<dictcomp>G  s"    XXXeC"XXXr   zGOOG4-RSA-SHA256zX-Goog-AlgorithmzX-Goog-CredentialzX-Goog-DatezX-Goog-ExpireszX-Goog-SignedHeadersro   rp   rq   zx-goog-content-sha256zUNSIGNED-PAYLOADr   z{}{}?{}&X-Goog-Signature={})r<   get_v4_now_dtstampsr   r!   rd   re   urlparsenetlocupperrW   rA   rK   _url_encoderI   hashlibsha256r   	hexdigestrv   r   	b64decodebinasciihexlifydecoder   r   )%r   rZ   r"   rx   rY   ry   rz   r{   r|   rq   rS   r[   r}   r~   r   _request_timestampexpiration_secondsrequest_timestamp	datestampclient_emailcredential_scope
credentialheader_namesrV   rU   canonical_header_stringsigned_headerscanonical_query_stringlowercased_headerspayloadcanonical_elementscanonical_requestcanonical_request_hashstring_elementsr#   r%   r$   s%                                        r   generate_signed_url_v4r     s   d 3:>>!':'<'<$99.&rr*	 )L 04 0!+..."/#@@@ 55#355J".!,337333L\!! ,//0CDDK||~~$$&-"#)>w)G)G&		#$$t+  XXAAAAABBNXX?O?U?U?W?WXXX+='(,6()&7]#);%&/=+, 4A01';O78)3&()9::o.."444$%<=$ 	 		"455$^  )) ikk 
 		O YY//N F- F!L*?
 
	 !*955$_55<<WEE		%001F1Fw1O1OPP$_55<<WEE	(//X'=y  r   c                      t          t                                        d          } |                     d          }|                                                     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     sX     t**

D

)
)C-..I

##H--Iir   c                   	
 t          j        |           } dd| d| dd|z   dd
t          j        dt	          j        |                               d	          i          	t          j                    	
fd
}t          } ||          } |            }|j
        t          j        j        k    rt          j        d|j                   t          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)urlrY   bodyrS   r   )responser   rS   rY   requestr   s    r   retriable_requestz(_sign_message.<locals>.retriable_request  s     7s6gNN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~   r}   r   r   retrycallr   r   r   rS   rY   r   r   s            @@@@@r   rv   rv     s9   0  ))GF
}O
}
}Ti
}
}
}C"\1* G :y&"27";";"B"B7"K"KLMMD  G        
 E5"##DtvvH$+.(('CHMCC
 
 	
 :hm**73344Dr   c                     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                 V    g | ]&\  }}t          |           d t          |           'S )=)_quote_param)rB   namerb   s      r   rH   z_url_encode.<locals>.<listcomp>  sJ       D% 55U 3 355  r   &)rK   rA   rR   )query_paramsparamss     r   r   r     sF     '--//  F
 88F6NN###r   c                     t          | t                    st          |           } t          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   bytesrt   rd   re   quote)params    r   r   r     s<     eU## E

<e#...r   )r`   rl   NNNNNNNNNN),r   r   rL   r*   r   r   r   rd   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<   rW   
namedtuplerX   rk   r   r9   DEFAULT_ENDPOINTr   r   rv   r   r   r   r   r   <module>r      si                   " " " " " " * * * * * * ! ! ! ! ! ! B B B B B B . . . . . . . . . . . . 4 4 4 4 4 4
 - 
 
 
&  >  > (+X-?@ # # #L". ". ".J $[#GGG 

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