
    (                     
   d dl Z d dlZd dlZd dlmZ d dlmZ  e j                  e      Z	dZ
ej                  fZ G d de      Zd Zd Zd	 Zd
 Zd Zd Zd Zdddej,                  dfdZ ej0                   e             Zy)    N)http_client)_helpers)readseektellc                   (    e Zd ZdZd Zd Zd Zd Zy)MemoryCachez8httplib2 Cache implementation which only caches locally.c                     i | _         y Ncache)selfs    5platform/bq/third_party/oauth2client_4_0/transport.py__init__zMemoryCache.__init__$   s	    
    c                 8    | j                   j                  |      S r   )r   getr   keys     r   r   zMemoryCache.get'   s    zz~~c""r   c                 "    || j                   |<   y r   r   )r   r   values      r   setzMemoryCache.set*   s    

3r   c                 <    | j                   j                  |d        y r   )r   popr   s     r   deletezMemoryCache.delete-   s    

sD!r   N)__name__
__module____qualname____doc__r   r   r   r    r   r   r	   r	   !   s    B# "r   r	   c                      t         S )a  Return an HTTP object which caches results returned.

    This is intended to be used in methods like
    oauth2client_4_0.client.verify_id_token(), which calls to the same URI
    to retrieve certs.

    Returns:
        httplib2.Http, an HTTP object with a MemoryCache
    )_CACHED_HTTPr    r   r   get_cached_httpr#   1   s
     r   c                  ,    t        j                  | i |S )a>  Return a new HTTP object.

    Args:
        *args: tuple, The positional arguments to be passed when
               contructing a new HTTP object.
        **kwargs: dict, The keyword arguments to be passed when
                  contructing a new HTTP object.

    Returns:
        httplib2.Http, an HTTP object.
    )httplib2Http)argskwargss     r   get_http_objectr)   >   s     ==$)&))r   c                      | i S t        |       S )zCreates a copy of the headers.

    Args:
        headers: dict, request headers to copy.

    Returns:
        dict, the copied headers or a new dictionary if the headers
        were None.
    )dict)headerss    r   _initialize_headersr-   M   s     23d7m3r   c                 <    |d| v r|dz   | d   z   | d<   | S || d<   | S )a,  Adds a user-agent to the headers.

    Args:
        headers: dict, request headers to add / modify user
                 agent within.
        user_agent: str, the user agent to add.

    Returns:
        dict, the original headers passed in, but modified if the
        user agent is not None.
    z
user-agent r    )r,   
user_agents     r   _apply_user_agentr1   Z   sC     7"%/#%58M%MGL! N %/GL!Nr   c                 l   i }	 t        j                  |       D ]z  \  }}t        |t         j                        st	        |      }t        |t         j                        st	        |      }t        j                  |      |t        j                  |      <   | 	 |S # t        $ r ddlm	}  |d      w xY w)a  Forces header keys and values to be strings, i.e not unicode.

    The httplib module just concats the header keys and values in a way that
    may make the message header a unicode string, which, if it then tries to
    contatenate to a binary request body may result in a unicode decode error.

    Args:
        headers: dict, A dictionary of headers.

    Returns:
        The same dictionary but with all the keys converted to strings.
    r   )NonAsciiHeaderErrorz: )
six	iteritems
isinstancebinary_typestrr   	_to_bytesUnicodeEncodeErroroauth2client_4_0.clientr3   )r,   cleankvr3   s        r   clean_headersr?   o   s     E	.MM'*DAqa1Fa1F+3+=+=a+@E($$Q'( + L  .?!!T1--.s   BB B3c                      |j                   dddt        j                  df fd	}||_          |j                   _        y)a  Prepares an HTTP object's request method for auth.

    Wraps HTTP requests with logic to catch auth failures (typically
    identified via a 401 status code). In the event of failure, tries
    to refresh the token used and then retry the original request.

    Args:
        credentials: Credentials, the credentials used to identify
                     the authenticated user.
        http: httplib2.Http, an http object to be used to make
              auth requests.
    GETNc           
         j                   s&t        j                  d       j                         t	        |      }j                  |       t        |j                         d }t        fdt        D              rj                         }t        | |t        |      ||      \  }}d}	t        |	      D ]  }
|j                  t        vr ||fS t        j                  d|j                  |
dz   |	       j                         j                  |       |j!                  |       t        | |t        |      ||      \  }} ||fS )Nz1Attempting refresh to obtain initial access_tokenc              3   8   K   | ]  }t        |d         y wr   )getattr).0stream_propbodys     r   	<genexpr>z:wrap_http_for_auth.<locals>.new_request.<locals>.<genexpr>   s#      #! 5@wt[$/!s      z&Refreshing due to a %s (attempt %s/%s)   )access_token_LOGGERinfo_refreshr-   applyr1   r0   all_STREAM_PROPERTIESr   requestr?   rangestatusREFRESH_STATUS_CODESr   )urimethodrG   r,   redirectionsconnection_typebody_stream_positionrespcontentmax_refresh_attemptsrefresh_attemptcredentialsorig_request_methods     `        r   new_requestz'wrap_http_for_auth.<locals>.new_request   s\    ''LL 0 1  !45 &g.'"';#9#9:# #!# ##'99;  3S&$ -g 6 ,o?g  !$%9:O{{"66 W} LLAo&9-/   !45g&#/		./#$7fd$1'$:$0/CMD'  ; W}r   )rR   r%   DEFAULT_MAX_REDIRECTSr_   )r_   httpra   r`   s   `  @r   wrap_http_for_authrd      sA     ,, !&D$!)!?!?$(*Z DL  +DLLr   c                      |j                   t         |       |j                   dddt        j                  df fd	}||_          |j                   _        y)a  Prepares an HTTP object's request method for JWT access.

    Wraps HTTP requests with logic to catch auth failures (typically
    identified via a 401 status code). In the event of failure, tries
    to refresh the token used and then retry the original request.

    Args:
        credentials: _JWTAccessCredentials, the credentials used to identify
                     a service account that uses JWT access tokens.
        http: httplib2.Http, an http object to be used to make
              auth requests.
    rA   Nc           	      p   d
j                   v r:
j                  
j                  r
j                  d        t	        	| |||||      S t        |      }t        |
j                         | j                  dd      d   }
j                  d|i      \  }}d|z   |d<   t	        | ||t        |      ||      S )Naud?rJ   r   zBearer Authorization)_kwargsrK   access_token_expiredrefreshrR   r-   r1   r0   split_create_tokenr?   )rV   rW   rG   r,   rX   rY   uri_roottokenunused_expiryauthenticated_request_methodr_   r`   s            r   ra   z-wrap_http_for_jwt_access.<locals>.new_request   s     K'''((044##D)7!4,*, , *'2Gg{'='=>yya(+H#.#<#<eX=N#O E='05'8GO$.VT(1': :r   )rR   rd   r%   rb   r_   )r_   rc   ra   rr   r`   s   `  @@r   wrap_http_for_jwt_accessrs      sT     ,,{D)#'<<  !&D$!)!?!?$(:2 DL  +DLLr   rA   c                 f    t         j                  d||       t        | d|       } |||||||      S )a  Make an HTTP request with an HTTP object and arguments.

    Args:
        http: httplib2.Http, an http object to be used to make requests.
        uri: string, The URI to be requested.
        method: string, The HTTP method to use for the request. Defaults
                to 'GET'.
        body: string, The payload / body in HTTP request. By default
              there is no payload.
        headers: dict, Key-value pairs of request headers. By default
                 there are no headers.
        redirections: int, The number of allowed 203 redirects for
                      the request. Defaults to 5.
        connection_type: httplib.HTTPConnection, a subclass to be used for
                         establishing connection. If not set, the type
                         will be determined from the ``uri``.

    Returns:
        tuple, a pair of a httplib2.Response with the status code and other
        headers and the bytes of the content returned.
    zRequesting: %s %srR   )rW   rG   r,   rX   rY   )rL   rM   rD   )rc   rV   rW   rG   r,   rX   rY   http_callables           r   rR   rR      s>    2 LL$fc2D)T2MV$&2)8: :r   )loggingr%   r4   	six.movesr   oauth2client_4_0r   	getLoggerr   rL   rQ   UNAUTHORIZEDrU   objectr	   r#   r)   r-   r1   r?   rd   rs   rb   rR   r&   r"   r    r   r   <module>r|      s       
 ! % '

H
%-  $002 "& " 
*
4*6@+F/+d $$!77 :@ x}}[]+r   