|
| 1 | +import ssl |
| 2 | +import urllib.parse |
| 3 | +import urllib.request |
| 4 | +import logging |
| 5 | +from typing import Dict, Any, Optional, Tuple, Union |
| 6 | + |
| 7 | +from urllib3 import HTTPConnectionPool, HTTPSConnectionPool, ProxyManager |
| 8 | +from urllib3.util import make_headers |
| 9 | + |
| 10 | +from databricks.sql.auth.retry import DatabricksRetryPolicy |
| 11 | +from databricks.sql.types import SSLOptions |
| 12 | + |
| 13 | +logger = logging.getLogger(__name__) |
| 14 | + |
| 15 | + |
| 16 | +def detect_and_parse_proxy( |
| 17 | + scheme: str, |
| 18 | + host: Optional[str], |
| 19 | + skip_bypass: bool = False, |
| 20 | + proxy_auth_method: Optional[str] = None, |
| 21 | +) -> Tuple[Optional[str], Optional[Dict[str, str]]]: |
| 22 | + """ |
| 23 | + Detect system proxy and return proxy URI and headers using standardized logic. |
| 24 | +
|
| 25 | + Args: |
| 26 | + scheme: URL scheme (http/https) |
| 27 | + host: Target hostname (optional, only needed for bypass checking) |
| 28 | + skip_bypass: If True, skip proxy bypass checking and return proxy config if found |
| 29 | + proxy_auth_method: Authentication method ('basic', 'negotiate', or None) |
| 30 | +
|
| 31 | + Returns: |
| 32 | + Tuple of (proxy_uri, proxy_headers) or (None, None) if no proxy |
| 33 | + """ |
| 34 | + try: |
| 35 | + # returns a dictionary of scheme -> proxy server URL mappings. |
| 36 | + # https://docs.python.org/3/library/urllib.request.html#urllib.request.getproxies |
| 37 | + proxy = urllib.request.getproxies().get(scheme) |
| 38 | + except (KeyError, AttributeError): |
| 39 | + # No proxy found or getproxies() failed - disable proxy |
| 40 | + proxy = None |
| 41 | + else: |
| 42 | + # Proxy found, but check if this host should bypass proxy (unless skipped) |
| 43 | + if not skip_bypass and host and urllib.request.proxy_bypass(host): |
| 44 | + proxy = None # Host bypasses proxy per system rules |
| 45 | + |
| 46 | + if not proxy: |
| 47 | + return None, None |
| 48 | + |
| 49 | + parsed_proxy = urllib.parse.urlparse(proxy) |
| 50 | + |
| 51 | + # Generate appropriate auth headers based on method |
| 52 | + if proxy_auth_method == "negotiate": |
| 53 | + proxy_headers = _generate_negotiate_headers(parsed_proxy.hostname) |
| 54 | + elif proxy_auth_method == "basic" or proxy_auth_method is None: |
| 55 | + # Default to basic if method not specified (backward compatibility) |
| 56 | + proxy_headers = create_basic_proxy_auth_headers(parsed_proxy) |
| 57 | + else: |
| 58 | + raise ValueError(f"Unsupported proxy_auth_method: {proxy_auth_method}") |
| 59 | + |
| 60 | + return proxy, proxy_headers |
| 61 | + |
| 62 | + |
| 63 | +def _generate_negotiate_headers( |
| 64 | + proxy_hostname: Optional[str], |
| 65 | +) -> Optional[Dict[str, str]]: |
| 66 | + """Generate Kerberos/SPNEGO authentication headers""" |
| 67 | + try: |
| 68 | + from requests_kerberos import HTTPKerberosAuth |
| 69 | + |
| 70 | + logger.debug( |
| 71 | + "Attempting to generate Kerberos SPNEGO token for proxy: %s", proxy_hostname |
| 72 | + ) |
| 73 | + auth = HTTPKerberosAuth() |
| 74 | + negotiate_details = auth.generate_request_header( |
| 75 | + None, proxy_hostname, is_preemptive=True |
| 76 | + ) |
| 77 | + if negotiate_details: |
| 78 | + return {"proxy-authorization": negotiate_details} |
| 79 | + else: |
| 80 | + logger.debug("Unable to generate kerberos proxy auth headers") |
| 81 | + except Exception as e: |
| 82 | + logger.error("Error generating Kerberos proxy auth headers: %s", e) |
| 83 | + |
| 84 | + return None |
| 85 | + |
| 86 | + |
| 87 | +def create_basic_proxy_auth_headers(parsed_proxy) -> Optional[Dict[str, str]]: |
| 88 | + """ |
| 89 | + Create basic auth headers for proxy if credentials are provided. |
| 90 | +
|
| 91 | + Args: |
| 92 | + parsed_proxy: Parsed proxy URL from urllib.parse.urlparse() |
| 93 | +
|
| 94 | + Returns: |
| 95 | + Dictionary of proxy auth headers or None if no credentials |
| 96 | + """ |
| 97 | + if parsed_proxy is None or not parsed_proxy.username: |
| 98 | + return None |
| 99 | + ap = f"{urllib.parse.unquote(parsed_proxy.username)}:{urllib.parse.unquote(parsed_proxy.password)}" |
| 100 | + return make_headers(proxy_basic_auth=ap) |
0 commit comments