
    M              	          S r SSKJr  SSKJr  SSKJr  SSKrSSKrSSKrSSKrSSK	r	SSK
r
SSKrSSKrSSKrSSKrSSKrSSKrSSKJr  SSKJr  SSKJr  SS	KJr  SS
KJr  SSKJr  SSKJr  SSKJr  SSKJr  SSKJr  SSK r SSKrSSK!r!SSK"J#r$  SSK"J%r%  SSK&r&SSK'J(r(   SSK)J*r+  Sr-Sq.       S:S jr/ " S S\R`                  " S/ SQ5      5      r1S r2 " S S\Rf                  Rh                  5      r4S r5Sr6 " S S\75      r8 " S  S!\Rf                  Rh                  5      r9S"\Rt                  S#\Rf                  Rv                  4S$ jr<S% r=      S;S& jr>  S<S' jr?S( r@ " S) S*\R                  5      rA " S+ S,\R                  5      rB " S- S.\R                  5      rCS/ rD " S0 S15      rES=S2 jrF " S3 S4\!R                  " \R                  5      5      rI " S5 S65      rJS7 rKS8 rLS9 rMg! \, a    SSK%r+ GNUf = f)>z;A module to get an unauthenticated requests.Session object.    )absolute_import)division)unicode_literalsN)requests)_MutualTlsOffloadAdapter)context_aware)execution_utils)log)
properties)	transport)encoding)http_proxy_types)	platforms)http_client)urllibcreate_urllib3_contextah  It appears that the current proxy configuration is using an HTTPS scheme for contacting the proxy server, which likely indicates an error in your HTTPS_PROXY environment variable setting. This can usually be resolved by setting HTTPS_PROXY=http://... instead of HTTPS_PROXY=https://... See https://cloud.google.com/sdk/docs/proxy-settings for more information.Fc                 R    [        XUXV5      n[        5       R                  UUUS9nU$ )a  Get a requests.Session that is properly configured for use by gcloud.

This method does not add credentials to the client. For a requests.Session
that has been authenticated, use core.credentials.requests.GetSession().

Args:
  timeout: double, The timeout in seconds. This is the
      socket level timeout. If timeout is None, timeout is infinite. If
      default argument 'unset' is given, a sensible default is selected using
      transport.GetDefaultTimeout().
  ca_certs: str, absolute filename of a ca_certs file that overrides the
      default. The gcloud config property for ca_certs, in turn, overrides
      this argument.
  session: requests.Session instance
  streaming_response_body: bool, True indicates that the response body will
      be a streaming body.
  redact_request_body_reason: str, the reason why the request body must be
      redacted if --log-http is used. If None, the body is not redacted.
  client_certificate: str, absolute filename of a client_certificate file that
      is set explicitly for client certificate authentication
  client_key: str, absolute filename of a client_key file that
      is set explicitly for client certificate authentication

Returns:
  A requests.Session object configured with all the required settings
  for gcloud.
)streaming_response_bodyredact_request_body_reason)_CreateRawSessionRequestWrapperWrapWithDefaults)timeoutca_certssessionr   r   client_certificate
client_keyr   s           #lib/googlecloudsdk/core/requests.py
GetSessionr    E   s@    D "'W"4B+ 115!; 2 =+ 
    c                   0   ^  \ rS rSrSrSU 4S jjrSrU =r$ )ClientSideCertificatep   zHolds information about a client side certificate.

Attributes:
  certfile: str, path to a cert file.
  keyfile: str, path to a key file.
  password: str, password to the private key.
c                 ,   > [         [        U ]  XX#5      $ N)superr#   __new__)clscertfilekeyfilepassword	__class__s       r   r(   ClientSideCertificate.__new__{   s    &4w* *r!    r&   )__name__
__module____qualname____firstlineno____doc__r(   __static_attributes____classcell__r-   s   @r   r#   r#   p   s    * *r!   r#   )r*   r+   r,   c                      [        5       $ )zReturns a urrlib3 SSL context.r   r/   r!   r   CreateSSLContextr9      s    		!!r!   c                   J   ^  \ rS rSrSrU 4S jrU 4S jrU 4S jrS rSr	U =r
$ )HTTPAdapter   a3  Transport adapter for requests.

Transport adapters provide an interface to extend the default behavior of the
requests library using the full power of the underlying urrlib3 library.

See https://requests.readthedocs.io/en/master/user/advanced/
    #transport-adapters for more information about adapters.
c                 :   > Xl         [        [        U ]  " U0 UD6  g r&   )
_cert_infor'   r;   __init__)selfclient_side_certificateargskwargsr-   s       r   r?   HTTPAdapter.__init__   s    -O	+t%t6v6r!   c                 N   > U R                  U5        [        [        U ]  " U0 UD6$ r&   )_add_ssl_contextr'   r;   init_poolmanagerr@   rB   rC   r-   s      r   rG   HTTPAdapter.init_poolmanager   s(    &!d4dEfEEr!   c                 N   > U R                  U5        [        [        U ]  " U0 UD6$ r&   )rF   r'   r;   proxy_manager_forrH   s      r   rK   HTTPAdapter.proxy_manager_for   s(    &!d5tFvFFr!   c                    U R                   (       d  g [        5       nUR                  5         0 nU R                   R                  (       a  U R                   R                  US'   U R                   R                  (       a  U R                   R                  US'   UR
                  " U R                   R                  40 UD6  X!S'   g )Nr+   r,   ssl_context)r>   r9   load_default_certsr+   r,   load_cert_chainr*   )r@   rC   contextcert_chain_kwargss       r   rF   HTTPAdapter._add_ssl_context   s    ?? G %)__%<%<	"&*oo&>&>
#DOO44J8IJ#=r!   )r>   )r0   r1   r2   r3   r4   r?   rG   rK   rF   r5   r6   r7   s   @r   r;   r;      s#    7FG$ $r!   r;   c                     [         R                  R                  R                  R	                  5       n [         R                  R                  R
                  R	                  5       n[         R                  R                  R                  R                  5       n[        XU4 Vs/ s H  o3(       d  M  UPM     sn5      nUS:  a  US:w  a  [         R                  " S5      eU(       d  g[         R                  R                  R                  R                  5       n[         R                  R                  R                  R	                  5       n[         R                  R                  R                  R	                  5       n[        R                  U    nU[         R"                  :X  a  U(       a  SOSn	OQU[         R$                  :X  a  U(       a  SOSn	O1U[         R&                  :X  a  S	n	O[)        S
R+                  U 5      5      eU(       d  U(       a  SR-                  S Xg4 5       5      n
U
S-  n
OSn
SR+                  XUU5      $ s  snf )zReturns the proxy string for use by requests from gcloud properties.

See https://requests.readthedocs.io/en/master/user/advanced/#proxies.
r      z\Please set all or none of the following properties: proxy/type, proxy/address and proxy/portNsocks4asocks4socks5hsocks5httpzUnsupported proxy type: {}:c              3   r   #    U  H-  n[         R                  R                  U5      =(       d    S v   M/     g7f) N)r   parsequote).0xs     r   	<genexpr>GetProxyInfo.<locals>.<genexpr>   s,      G-E1##-Es   57@r]   z{}://{}{}:{})r   VALUESproxy
proxy_typeGetaddressportGetIntlenInvalidValueErrorrdnsGetBoolusernamer,   r   PROXY_TYPE_MAPsocksPROXY_TYPE_SOCKS4PROXY_TYPE_SOCKS5PROXY_TYPE_HTTP
ValueErrorformatjoin)rg   proxy_address
proxy_portfproxy_prop_set
proxy_rdns
proxy_user
proxy_passhttp_proxy_typeproxy_scheme
proxy_auths              r   GetProxyInfor      s   
   &&11557*##))11557-  &&++224*j9?9QQq9?A.aNa/

&
&	34 4 

  &&++335*  &&//335*  &&//335*$33J?//// *9L%111 *9L%///L
188D
EE: G.8-EG GJ#JJ			|)
+ +; @s   "
I0Ia  Please use the installed gcloud CLI (`apt install google-cloud-cli`)
 This version of gcloud you are currently using will encounter issues due to
 changes in internal security policy enforcement in the near future.

 If this is not possible due to dev requirements, please apply for
 policy exemption at go/gcloud-cba-exemption-internal-version-gcloud using this error message to self-exempt or reach out to
 go/gcloud-cba-investigation for investigation.
c                   0   ^  \ rS rSrSrSU 4S jjrSrU =r$ )ECPProxyError   zCustom exception for errors related to the ECP proxy communication.

For example, startup failures or receiving a specific proxy error header.
c                 V   > X l         [        TU ]	  U(       a  U SU 35        g U5        g )N: )original_exceptionr'   r?   )r@   messager   r-   s      r   r?   ECPProxyError.__init__   s0    0	G.@7)2()*FMr!   r   r&   )r0   r1   r2   r3   r4   r?   r5   r6   r7   s   @r   r   r      s    
 r!   r   c                      ^  \ rS rSrSr  SS\S\S\4U 4S jjjrS\4S	 jr SS
\S\S\4S jjr	S\S\SS4S jr
S\S
\SS4S jrU 4S jrS rU 4S jrSrU =r$ )_LocalECPProxyAdapter   a#  A requests adapter that routes HTTPS requests through a local ECP proxy.

This adapter starts the ECP proxy as a background process upon instantiation
and manages its lifecycle, terminating it when the adapter is closed.
This avoids the overhead of starting a new process for every request.
Ncertificate_config_file_pathgcloud_proxy_urlstartup_timeoutc                    > Xl         X l        [        TU ]  " S0 UD6  [        R
                  " U R                  5        SU l        SU l        [        R                  " S5      U l        U R                  USS9U l        g)aJ  Initializes the adapter and starts the local ECP proxy process.

Args:
    certificate_config_file_path: Path to the JSON certificate config file.
    gcloud_proxy_url: Optional URL for proxy chaining.
    startup_timeout: Seconds to wait for the proxy to become available.
    **kwargs: Additional arguments for the HTTPAdapter.
N	localhost      )max_retriesr/   )r   r   r'   r?   atexitregistercloseproxy_process
proxy_hostsecrets	token_hexnonce_token_start_ecp_proxy_with_retriesrz   )r@   r   r   r   rC   r-   s        r   r?   _LocalECPProxyAdapter.__init__   sr     )E%,	Gv
 OODJJD!DO((,D88Q 9 DOr!   returnc                     [         R                   " 5        nUR                  S5        UR                  5       S   sSSS5        $ ! , (       d  f       g= f)z4Dynamically finds and returns an available TCP port.)r]   r   r   N)socketbindgetsockname)r@   ss     r   _find_free_port%_LocalECPProxyAdapter._find_free_port  s0    	AffWo]]_Q 
s   $A
Ar   r   c                    [         R                  " U R                  5      nUR                  S0 5      R                  S5      nU(       d$  [	        SR                  U R                  5      5      e[        US-   5       H4  nU R                  5       nU R                  XFS9   U R                  XaS9  Us  $    g! [         a  nU R                  (       a5  U R                  R                  5       c  U R                  R                  5         XR:  a"  [        R                  " SU S	U 35         SnAM  [        R                  " S
U SU 35        e SnAff = f)ag  Attempts to start the ECP Proxy, retrying on failure.

This method orchestrates the proxy startup by finding an available port,
launching the proxy process, and waiting for it to become responsive.
If the proxy fails to start, it retries the process until either succeeds
or the maximum number of retries is reached.

Args:
  timeout: The maximum time in seconds to wait for the proxy to start
  max_retries: The maximum number of times to retry starting the proxy.

Returns:
  The port number on which the proxy successfully started.

Raises:
  ECPProxyError: If the proxy fails to start after all retry attempts.
libsecp_http_proxya  ECP HTTP proxy binary path is not specified in enterprise certificate config file. Cannot use mTLS with ECP if the ECP HTTP proxy binary does not exist. Please check the ECP configuration. See `gcloud topic client-certificate` to learn more about ECP. 
If this error is unexpected either delete {} or generate a new configuration with `$ gcloud auth enterprise-certificate-config create --help` r   )r   rz   )rz   r   Nz"ECP proxy failed to start on port r   z ECP proxy failed to start after z
 retries: )r   GetCertificateConfigr   getr   rw   ranger   _start_ecp_proxy_wait_for_proxyr   poll	terminater
   warningerror)r@   r   r   cert_configr   attemptrz   es           r   r   3_LocalECPProxyAdapter._start_ecp_proxy_with_retries  s8   *  44))K !__VR0445EFN $VD$E$EF  q)'')j
'  

D *  $"4"4"9"9";"C



&
&
( 
++::,bL
M
		4[MA3OPs   B44
E>A'E+EEr   rz   c                   [         R                  " SU 35        SU R                  S[        U5      SU R                  /nU R
                  (       a  UR                  SU R
                  /5        [        R                  " U/UQ76 n [        R                  " USSS9U l        g! [        [        4 a)  n[         R                  " SU 35        [        S	US
9UeSnAff = f)a  Launches the local ECP proxy executable as a subprocess.

Constructs the necessary command-line arguments, including the ECP config
path, port, nonce token, and an optional upstream proxy URL. It then uses
subprocess.Popen to start the proxy process in the background.

Args:
  ecp_http_proxy: The path to the ECP HTTP proxy binary.
  proxy_port: The TCP port for the proxy to listen on.

Raises:
  ECPProxyError: If the subprocess fails to start due to OSError or
    ValueError.
z(Starting local ECP proxy server on port z!-enterprise_certificate_file_pathz-portz-nonce_tokenz%-gcloud_configured_upstream_proxy_urlN)stdoutstderrz&Failed to start ECP proxy executable: z!Failed to start ECP proxy processr   )r
   debugr   strr   r   extendr	   ArgsForExecutableTool
subprocessPopenr   OSErrorrv   r   r   )r@   r   rz   rB   
proxy_argsr   s         r   r   &_LocalECPProxyAdapter._start_ecp_proxyT  s     II8EF 	,))JD 
kk2D4I4I
J !66~MMJ
%++
d
 Z  	ii8<=
-!s   B! !C1$CCc          	          [         R                  " SU S35        [        R                  " 5       n[        R                  " 5       U-
  U:  ak  U R                  R                  5       b#  [        SU R                  R                   S35      e [        R                  " U R                  U4SS9    SSS5        O/U R                  5         [        SU R                   S	U S
U S35      e SU R                   S	U S3n[        R                  " USS9nUR                   S:w  a  [        SUR                    S35      eUR"                  nX`R$                  :w  a  [        S5      e[         R                  " S5        g! , (       d  f       O+= f! [         a    [        R                  " S5         GMz  f = f[        R                  " 5       U-
  U:  a  GM  GN! [        R&                  R(                   a  n[        SUS9UeSnAff = f)a}  Waits for the proxy to become available and verifies its identity.

This method first waits for the proxy's TCP port to accept connections.
Once the port is open, it sends a request to the `/readyz` endpoint to
confirm that the proxy is fully operational and to verify a security nonce,
ensuring that gcloud is communicating with the correct proxy instance.

Args:
  proxy_port: The port where the proxy is expected to be listening.
  timeout: The maximum time in seconds to wait for the proxy.

Raises:
  ECPProxyError: If the proxy process terminates unexpectedly, fails to
    respond within the timeout, or returns an invalid nonce.
z*Waiting for the proxy to be ready on port z...Nz0Proxy process terminated unexpectedly with code z while waiting for it to start.g?r   zECP Proxy on r[   z did not become ready in z	 seconds.http://z/readyzr      z'Proxy /readyz endpoint returned status .z+Nonce mismatch from proxy /readyz endpoint.z"Proxy is ready and nonce verified.z6Failed to verify proxy readiness via /readyz endpoint.r   )r
   r   time	monotonicr   r   r   
returncoder   create_connectionr   r   sleepr   r   r   status_codetextr   
exceptionsRequestException)r@   rz   r   
start_time
readyz_urlresponseserver_noncer   s           r   r   %_LocalECPProxyAdapter._wait_for_proxy  s   " II::,cJK!J ..
Z
''
1				 	 	"	.>!!,,--LN
 	

%%__j)3
 	
 
 jjl$//*!J< 8Yi! T__-Qzl'Bjj!4h				$5h6J6J5K1M
 	
 ]]l	))	)IJJ	ii45?
 

  

3 ..
Z
''
1
1R // 
B sI   !F ,E5.F 'BG 5
F?F F  F+*F+G=-G88G=c                 X  > [         R                  R                  UR                  5      nUR                  UR
                  S'   [         R                  R                  SSUR                  UR                  S45      nSU R                   SU R                   U 3Ul        SUS'   [        R                  " SUR                  5        SUR                   35         [        TU ]<  " U40 UD6nU R)                  U5      $ ! [         R"                  R$                   a  n['        S	US
9UeSnAff = f)a|  Intercepts an outgoing request and reroutes it through the local ECP proxy.

This method modifies the request's URL to point to the local proxy and
adds a custom header (`x-goog-ecpproxy-target-host`) to inform the proxy
of the original destination. It then sends the modified request and passes
the response to `_handle_proxy_response` for inspection.

Args:
  request: The `requests.PreparedRequest` object to send.
  **kwargs: Additional arguments passed to the underlying `send` method.

Returns:
  The `requests.Response` object from the proxy.

Raises:
  ECPProxyError: If the proxy returns an error or fails to send the request.
zx-goog-ecpproxy-target-hostr]   r   r[   FverifyzRedirecting request for z to proxy at zFailed to send request to proxyr   N)r   r^   urlspliturlhostnameheaders
urlunsplitpathqueryr   rz   r
   r   geturlr'   sendr   r   r   r   _handle_proxy_response)r@   requestrC   original_url
proxy_pathr   r   r-   s          r   r   _LocalECPProxyAdapter.send  s    & <<((5L5A5J5JGOO12 ((	R""L$6$6;J DOO,Adoo->zlKGK F8II
"<#6#6#8"9 :KK=	g00h &&x00 // 
+s   C; ;D)D$$D)c                 *   UR                   R                  S5      nU(       aG  [        R                  " S5         UR	                  5       R                  SS5      nSU 3n[        U5      eU$ ! [        R
                   a    SUR                   3n N2f = f)a'  Inspects the proxy's response for custom error headers.

If the `x-goog-ecpproxy-error` header is present in the response, this
method assumes the proxy encountered an internal error. It attempts to parse
a detailed error message from the JSON response body and raises an
`ECPProxyError` with the relevant information.

Args:
  response: The `requests.Response` object received from the proxy.

Returns:
  The original `requests.Response` object if no error header is found.

Raises:
  ECPProxyError: If the `x-goog-ecpproxy-error` header is present.
zx-goog-ecpproxy-errorzECP Proxy returned an errorr   zNo message in body.z'ECP Proxy indicated an internal error: z6ECP Proxy indicated an internal error. Response body: )r   r   r
   r   jsonJSONDecodeErrorr   r   )r@   r   proxy_error_headererror_detailsr   s        r   r   ,_LocalECPProxyAdapter._handle_proxy_response  s    " "))--.EF	ii-.
 ++I7LM;M?K '""O !! 
  	
s   %A, ,#BBc                   > [         R                  " S5        U R                  (       aO  U R                  R                  5       c4  U R                  R	                  5          U R                  R                  SS9  [        TU ]-  5         g! [        R                   a3    [         R                  " S5        U R                  R                  5          NUf = f)ar  Terminates the background ECP proxy process to clean up resources.

This method ensures that the local proxy subprocess is properly shut down
when the session is closed. It first attempts a graceful termination and
waits briefly, then forcefully kills the process if it does not exit in
time. Finally, it calls the parent class's `close` method to complete
the cleanup.
z:Closing ECP Proxy Adapter and terminating proxy process...Ng      ?r   z7Proxy process did not terminate gracefully, killing it.)r
   r   r   r   r   waitr   TimeoutExpiredr   killr'   r   )r@   r-   s    r   r   _LocalECPProxyAdapter.close  s     IIJKd00557?
""$", 
GMO && "MN!"s   B ACC)r   r   r   r   rz   r   )N   )r   )r0   r1   r2   r3   r4   r   intr?   r   r   r   r   r   r   r   r5   r6   r7   s   @r   r   r      s     #	$'  	 @ s   ./44'*4
4l* * * *XC3 C C CJ.1`B r!   r   	ca_configr   c                     U (       a  U R                   (       d  [        S5      eU R                  (       a  [        U R                   S9$ [	        U R                   5      $ )a  Creates a requests adapter for mTLS offloading via ECP.

This function decides which adapter to use based on the provided
configuration:
- If `ca_config.use_local_proxy` is True, it returns a
  `_LocalECPProxyAdapter`, which routes traffic through a local ECP proxy
  subprocess.
- Otherwise, it returns a `_MutualTlsOffloadAdapter` from the google-auth
  library, which uses the ECP binary for TLS offloading without a local proxy.

Args:
    ca_config: The enterprise certificate configuration object.

Returns:
    An instance of a requests adapter for mTLS offloading.

Raises:
    ValueError: If the certificate configuration file path is not provided.
z.Certificate config file path must be provided.)r   )r   rv   use_local_proxyr   r   )r   s    r   _CreateMutualTlsOffloadAdapterr   +  sM    , 
)@@
E
FF %.%K%K  $I$J$JKKr!   c                  T   [         R                  R                  5       [         R                  R                  :H  n [        R
                  =(       a    S[        R
                  ;   n[        R                  " 5       nU (       a)  U(       d"  U(       a  [        R                  " [        5        gg)a]  Warn users if running non-bundled Python on Linux and is a Googler.

Checks if the current OS is Linux, running Python that is not bundled and if
the user is a Googler. If all conditions are true, a warning message will be
emitted, along with returning true to bypass the mTLS code path.

Returns:
  True if the conditions are met, False otherwise.
bundledTF)r   OperatingSystemCurrentLINUXsys
executabler   IsInternalUserCheckr
   r   _GOOGLER_BUNDLED_PYTHON_WARNING)is_linuxis_bundled_pythonis_internal_users      r   %_LinuxNonbundledPythonAndGooglerCheckr  L  so     '')Y-F-F-L-LL nnDcnn)D335',<KK/0r!   c                   ^ ^
^ U=(       d    [         R                  " 5       n[        5       mUR                  m
U
UU 4S jnXcl        T(       a  SUl        TTS.Ul        O6[        5       (       a'  [        (       d  Sq[        R                  " [        5        SnUb5  Ub2  Ub/  [        R                  " SXU5        [        XE5      n[        U5      nO[        R                  " 5       n	U	(       a  [!        5         U	R"                  [        R$                  R&                  :X  a  [)        U	5      nOU	R"                  [        R$                  R*                  :X  aX  [        R                  " SU	R,                  5        [        U	R,                  U	R,                  U	R.                  5      n[        U5      nO[        S5      nO[        S5      nU(       a  SUl        OU(       a  Xl        UR3                  SU5        U$ )	a  Returns a requests.Session subclass.

Args:
  timeout: float, Request timeout, in seconds.
  ca_certs: str, absolute filename of a ca_certs file
  disable_ssl_certificate_validation: bool, If true, disable ssl certificate
      validation.
  session: requests.Session instance. Otherwise, a new requests.Session will
      be initialized.
  client_certificate: str, absolute filename of a client_certificate file
  client_key: str, absolute filename of a client_key file

Returns: A requests.Session subclass.
c                     > SU;  a  TUS'   [        5       (       a-  SU;  a'  [        T[        R                  " 5       T/U Q70 UD6US'   T" U 0 UD6$ )Nr   proxies)_HasBpo42627_AdjustProxiesKwargForBpo42627urllib_requestgetproxies_environment)rB   rC   orig_request_method
proxy_infor   s     r   WrappedRequestSession.<locals>.WrappedRequestz  sg    !fY ~~)618
n;;=
0 $0(.0fY ///r!   F)rZ   httpsTNzVUsing provided server certificate %s, client certificate %s, client certificate key %szUsing client certificate %shttps://)r   Sessionr   r   	trust_envr	  !_HasInvalidHttpsProxyEnvVarScheme*_invalid_https_proxy_env_var_warning_shownr
   r   $_INVALID_HTTPS_PROXY_ENV_VAR_WARNINGr   r#   r;   r   Configr  config_type
ConfigTypeENTERPRISE_CERTIFICATEr   ON_DISK_CERTIFICATEencrypted_client_cert_pathencrypted_client_cert_passwordr   mount)r   r   "disable_ssl_certificate_validationr   r   r   r  rA   adapterr   r  r  s   `         @@r   r  r  a  s   * )x'')'~*
0 #/GGO )** 65 480	kk67 #
(>8CWII`j2 4(12G$$&I+-			-":":"Q"Q	Q0;  M$<$<$P$PP		/66	8"7000044#6 56d#D!g'GNN	--
G$	.r!   c           	      X   U S:w  a  U nO[         R                  " 5       n[        R                  R                  R
                  R                  5       =(       d    Sn[        R                  R                  R                  R                  5       nU(       a  UnU(       a  Sn[        UUUUUUS9$ )zECreate a requests.Session matching the appropriate gcloud properties.unsetFN)r   r   r!  r   r   r   )r   GetDefaultTimeoutr   re   authdisable_ssl_validationro   corecustom_ca_certs_filerh   r  )r   r   r   r   r   effective_timeoutno_validateca_certs_propertys           r   r   r     s     !335!!&&==EEGP5+ '',,AAEEG HH	*"4? $6&
( (r!   c                 ~   [         R                  R                  U 5      n[         R                  R                  UR                  SS9n[
        R                  " U=(       d    0 5       H	  u  pEXSU'   M     [        U5      n[         R                  R                  USS9US'   [         R                  R                  U5      $ )zFGets the complete URI by merging url and params from the request args.T)keep_blank_values)doseqrU   )
r   r^   r   parse_qsr   six	iteritemslist	urlencoder   )r   params	url_partsquery_paramsparamvalues         r   _GetURIFromRequestArgsr:    s    ll##C()&&y$&O,mmFLb1le 2 9o)''D'A)A, 
	 	 	++r!   c                   F   ^  \ rS rSrSr\S 5       rSU 4S jjrS rSr	U =r
$ )Requesti  a  Encapsulates parameters for making a general HTTP request.

This implementation does additional manipulation to ensure that the request
parameters are specified in the same way as they were specified by the
caller. That is, if the user calls:
    request('URI', 'GET', None, {'header': '1'})

After modifying the request, we will call request using positional
parameters, instead of transforming the request into:
    request('URI', method='GET', body=None, headers={'header': '1'})
c                     U " U0 UD6$ r&   r/   )r)   rB   rC   s      r   FromRequestArgsRequest.FromRequestArgs  s    r!   c                 d   > X`l         [        X#5      n[        [        U ]  XqU=(       d    0 U5        g r&   )_kwargsr:  r'   r<  r?   )	r@   methodr   r5  datar   rC   urir-   s	           r   r?   Request.__init__  s)    L
 
-C	'4!#w}"dCr!   c                     U R                   U R                  /n[        U R                  5      nU R                  US'   U R
                  (       a  U R
                  US'   X4$ )Nr   rC  )rB  rD  dictrA  r   body)r@   rB   rC   s      r   ToRequestArgsRequest.ToRequestArgs  sL    KK"D$,,FF9yyyyfVn<r!   )rA  )NNN)r0   r1   r2   r3   r4   classmethodr>  r?   rI  r5   r6   r7   s   @r   r<  r<    s,    
    D r!   r<  c                   (    \ rS rSrSr\S 5       rSrg)Responsei  z:Encapsulates responses from making a general HTTP request.c                 R    U " UR                   UR                  UR                  5      $ r&   )r   r   content)r)   r   s     r   FromResponseResponse.FromResponse
  s#    x##X%5%5x7G7GHHr!   r/   N)r0   r1   r2   r3   r4   rK  rP  r5   r/   r!   r   rM  rM    s    BI Ir!   rM  c                   &    \ rS rSrSr\r\rS r	Sr
g)r   i  z,Class for wrapping request.Session requests.c                     AU$ )z&Returns the response without decoding.r/   )r@   r   response_encodings      r   DecodeResponseRequestWrapper.DecodeResponse  s
    Or!   r/   N)r0   r1   r2   r3   r4   r<  request_classrM  response_classrU  r5   r/   r!   r   r   r     s    4-.r!   r   c            	      h   [        5       n [        R                  " [        R                  S[        R                  " [        R                  SS5      5      n[        R                  " [        R                  SS5      nU R
                  R                  SU 3SSU 3S05        [        R                  " U S9$ )	zGReturns a gcloud's requests session to refresh google-auth credentials.GCE_METADATA_HOSTGCE_METADATA_ROOTzmetadata.google.internalGCE_METADATA_IPz169.254.169.254r   r]   )r   )	r    r   GetEncodedValueosenvironr	  updategoogle_auth_requestsr<  )r   metadata_rootmetadata_ip_roots      r   GoogleAuthRequestrd    s    L'
 **jj
**

$&'- --jj#%68 
// !"B 
 
	%	%g	66r!   c                        \ rS rSrS rS rSrg)_GoogleAuthApitoolsCredentialsi9  c                     Xl         g r&   credentials)r@   ri  s     r   r?   '_GoogleAuthApitoolsCredentials.__init__;  s    "r!   c                 P    A[        5       nU R                  R                  U5        g r&   )rd  ri  refresh)r@   r   auth_requests      r   rl  &_GoogleAuthApitoolsCredentials.refresh>  s!    $&L\*r!   rh  N)r0   r1   r2   r3   r?   rl  r5   r/   r!   r   rf  rf  9  s    #+r!   rf  c                    ^ [        XU5      n[        U S5      (       aD  [        U R                  5      nUR                  mU4S jnXSl        [        UR                  SU5        U$ )zGReturns an authenticated httplib2.Http-like object for use by apitools._googlecloudsdk_credentialsc                     > T" U 0 UD6$ r&   r/   )rB   rC   r  s     r   HttpRequest(GetApitoolsRequests.<locals>.HttpRequestO  s     $1&11r!   ri  )_ApitoolsRequestshasattrrf  rp  r   setattr)r   response_handlerrT  r   credsrr  r  s         @r   GetApitoolsRequestsry  D  sa    !'=NO+ W344*7+N+NOE%--2 &K6	r!   c                   B    \ rS rSrSrS r\R                  S 5       rSr	g)ResponseHandleriX  zHandler to process the Http Response.

Attributes:
  use_stream: bool, if True, the response body gets returned as a stream
      of data instead of returning the entire body at once.
c                     Xl         g)zInitializes ResponseHandler.

Args:
  use_stream: bool, if True, the response body gets returned as a stream of
    data instead of returning the entire body at once.
N
use_stream)r@   r~  s     r   r?   ResponseHandler.__init__`  s	     !Or!   c                     g)zHandles the http response.Nr/   )r@   response_streams     r   handleResponseHandler.handlei  s    r!   r}  N)
r0   r1   r2   r3   r4   r?   abcabstractmethodr  r5   r/   r!   r   r{  r{  X  s&    ! % %r!   r{  c                   <    \ rS rSrSrSS jrS r     S	S jrSrg)
rt  in  z0A httplib2.Http-like object for use by apitools.Nc                     Xl         0 U l        U(       a   [        U[        5      (       d  [	        S5      eX l        X0l        g )Nz3response_handler should be of type ResponseHandler.)r   connections
isinstancer{  rv   _response_handler_response_encoding)r@   r   rw  rT  s       r   r?   _ApitoolsRequests.__init__q  s:    L D(/::NOO-/r!   c                 4   AAUR                   [        R                  [        R                  4;  a  [        R
                  " S5        gU R                  R                  (       a  [        R                  R                  R                  R                  5       (       aX  [        R                  R                  R                  R                  5       (       a!  [        R                  " UR                   5      nOUR"                  nU R                  R%                  U5        g)z:Response hook to be used if response_handler has been set.z1Skipping response_handler as response is invalid.N)r   httplibOKPARTIAL_CONTENTr
   r   r  r~  r   re   r(  log_httpro   log_http_streaming_bodyioBytesIOrO  rawr  )r@   r   rB   rC   streams        r   ResponseHook_ApitoolsRequests.ResponseHook|  s    fGJJ0G0G#HH	iiCD))''//1166>>@@ zz(**+f||f!!&)r!   c           	         AUS:  a  XPR                   l        0 nU R                  b&  U R                  US'   U R                  R                  nOSnU R                   R                  X!X4XS9n	[        U	R                  5      nU	R                  US'   U(       a  Sn
O7U R                  b  U R                  U	l
        U	R                  n
OU	R                  n
[        R                  " U5      U
4$ )z/Makes an HTTP request using httplib2 semantics.r   r   F)rC  r   r  hooksstatusr!   )r   max_redirectsr  r  r~  r   rG  r   r   r  r   r   rO  httplib2rM  )r@   rD  rB  rH  r   redirectionsconnection_typer  r~  r   rO  s              r   r   _ApitoolsRequests.request  s     	a#/ll E)++eJ))44jj||##$
 $ QH8##$G ,,GH g		 	 	,
 11hg  gW%w..r!   )r  r  r  r   NN)GETNNr   N)	r0   r1   r2   r3   r4   r?   r  r   r5   r/   r!   r   rt  rt  n  s%    8	0** )/r!   rt  c                  n    [         R                  " 5       n U R                  SS5      R                  S5      $ )zAReturns whether the HTTPS proxy env var is using an HTTPS scheme.r  r]   r  )r  r  r   
startswith)env_proxiess    r   r  r    s.    
 557+	"	%	0	0	<<r!   c                     [         R                  R                  5       [         R                  R                  :H  =(       aK    [	        [
        S5      =(       a4    [
        R                  " 5       R                  SS5      R                  S5      $ )a  Returns whether Python is affected by https://bugs.python.org/issue42627.

Due to a bug in Python's standard library, urllib.request misparses the
Windows registry proxy settings and assumes that HTTPS URLs should use an
HTTPS proxy, when in fact they should use an HTTP proxy.

This bug affects PY<3.9, as well as lower patch versions of 3.9, 3.10, and
3.11.

Returns:
  True if proxies read from the Windows registry are being parsed incorrectly.
getproxies_registryr  r]   r  )	r   r   r   WINDOWSru  r  r  r   r  r/   r!   r   r
  r
    sh     '')Y-F-F-N-NN 
."7
8

,
,
.
2
27B
?
J
J
r!   c                 "   U (       d  U(       a  g[         R                  " U/UQ70 UD6S   n[        R                  R	                  U5      nUR                  S5      nU(       d  gUR                  S5      (       d  gSUR                  SSS5      0$ )a  Returns proxies to workaround https://bugs.python.org/issue42627 if needed.

Args:
  gcloud_proxy_info: str, Proxy info from gcloud properties.
  environment_proxies: dict, Proxy config from http/https_proxy env vars.
  orig_request_method: function, The original requests.Session.request method.
  *args: Positional arguments to the original request method.
  **kwargs: Keyword arguments to the original request method.
Returns:
  Optional[dict], Adjusted proxies to pass to the request method, or None if
    no adjustment is necessary.
Nr   r  r  r   r   )inspectgetcallargsr   utilsget_environ_proxiesr   r  replace)gcloud_proxy_infoenvironment_proxiesr  rB   rC   r   r	  https_proxys           r   r  r    s    & - 	/A$A&A%H#NN..s3'G$+				
	+	+
  {"":y!<
 r!   )r$  NNFNNN)NNFNNN)r$  NNNNr  )Nr4   
__future__r   r   r   r  r   collectionsr  r  r   r^  r   r   r   r   r   google.auth.transportr   ra  google.auth.transport.requestsr   googlecloudsdk.corer   r	   r
   r   r   googlecloudsdk.core.utilr   r   r   r  r1  	six.movesr   r  r   rr   urllib3.util.ssl_r   urllib.requestr   r  ImportErrorr  r  r    
namedtupler#   r9   adaptersr;   r   r  	Exceptionr   r   _EnterpriseCertConfigImplBaseAdapterr   r  r  r   r:  r<  rM  r   rd  rf  ry  with_metaclassABCMetar{  rt  r  r
  r  r/   r!   r   <module>r     s    B &  ' 
    	  	    
  B C - / # * ) - 5 .   
 ,   4")Q % .3 * ',*."&(V*2>@* "
%$(##// %$P(+X8  
I 
xH--99 xv	L66L""LB, ',Zz ?C:>(4,i @Iy!! I
Y-- 
7:+ +(%c((5 %,I/ I/X=*,C  "!"s   $G2 2
H ?H 