diff --git a/CHANGELOG.md b/CHANGELOG.md index ec4719355..edec4834a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,7 @@ # Unreleased - Support `credentials_provider` on kernel connections (`use_kernel=True`), with the same header refresh and token federation as Thrift. - Honor `_port` and `_connection_uri` on kernel connections (`use_kernel=True`), as Thrift does. Requires a databricks-sql-kernel release that includes databricks/databricks-sql-kernel#505. +- Support `_proxy_auth_method="negotiate"` (Kerberos proxy authentication) on kernel connections. It requires the `requests-kerberos` package and a kernel release with Negotiate proxy support. - Speed up `fetchone()`, `fetchmany()` and `fetchall()` by building each result `Row` with fewer Python calls. The rows are unchanged. Large results and many concurrent cursors in one process benefit most. # 4.10.0 (2026-11-24) diff --git a/CONNECTION_PARAMETERS.md b/CONNECTION_PARAMETERS.md index 4ee60d483..7363661a7 100644 --- a/CONNECTION_PARAMETERS.md +++ b/CONNECTION_PARAMETERS.md @@ -117,7 +117,7 @@ to change without notice. | `_socket_timeout` | `float` (s) | ✅ | ✅ | `900` (Thrift); `120` (kernel) | Thrift: socket send/recv/connect timeout. Kernel: total HTTP request deadline from connect through response-body completion. A positive value is forwarded; unset or `0` selects the kernel's 120s default. On the kernel path, `0` is neither unlimited nor an immediate timeout. | | `_pool_connections` | `int` | ⚠️ | ❌ | `10` | Number of pools in the shared Python HTTP client. On Thrift this affects auxiliary auth/feature-flag/telemetry traffic, not the separate Thrift query transport. Kernel-owned network traffic does not use this client. | | `_pool_maxsize` | `int` | ⚠️ | ⚠️ | `20` (Python); `100` (kernel when unset) | Max idle connections retained per host. It configures the shared Python client but not the Thrift query transport. With kernel ≥ 1.1.0, a positive value also configures the kernel's Rust HTTP pool. Unset or `0` keeps each client's default. | -| `_proxy_auth_method` | `str` | ✅ | ❌ | `None` | `basic` or `negotiate` (Kerberos). Applied to both Thrift query traffic and the shared Python client. It is not forwarded to the kernel's Rust transport. See [`docs/proxy.md`](docs/proxy.md). | +| `_proxy_auth_method` | `str` | ✅ | ✅ | `None` | `basic` or `negotiate` (Kerberos). Applied to both Thrift query traffic and the shared Python client. On Kernel, `negotiate` sends the system proxy and Kerberos tokens (from `requests-kerberos`) to the kernel and fails the connection if no token can be created; unset and `basic` keep the kernel's own environment-proxy handling. See [`docs/proxy.md`](docs/proxy.md). | | `_retry_stop_after_attempts_count` | `int` | ✅ | ✅ | `30` | Max attempts in a retry sequence. Bounded to `[1, 60]` on Thrift; forwarded to the kernel's retry policy. | | `_retry_stop_after_attempts_duration`| `float` (s) | ✅ | ⚠️ | `900` | Max total wall-clock seconds spent retrying. Kernel rounds to whole seconds. | | `_retry_delay_min` | `float` (s) | ✅ | ⚠️ | `1` | Minimum backoff delay. Kernel rounds to whole seconds and floors a positive sub-second value at one second. | @@ -233,8 +233,7 @@ are forwarded when supported by the installed kernel binding. `_retry_dangerous_codes`, `_respect_server_retry_after_header`, `_retry_max_redirects`, `_enable_v3_retries`. 8. `force_enable_telemetry`. -9. `_pool_connections` and `_proxy_auth_method` do not configure the - kernel-owned network stack. +9. `_pool_connections` does not configure the kernel-owned network stack. ### Supported on Kernel, missing / ignored on Thrift @@ -253,7 +252,8 @@ are forwarded when supported by the installed kernel binding. Databricks OAuth U2M. Kernel requires an explicit U2M `auth_type` or another supported credential flow. - **Connection pooling / proxy**: `_pool_connections` configures only the - shared Python client and `_proxy_auth_method` is not forwarded to Kernel. + shared Python client. Of the `_proxy_auth_method` values, only `negotiate` + changes the kernel's proxy handling. `_pool_maxsize` also configures the kernel's Rust HTTP pool when positive and using kernel ≥ 1.1.0. A value of `0` is treated as unset: the Python client keeps 20 and the kernel keeps 100. diff --git a/docs/proxy.md b/docs/proxy.md index 2e0bec292..fc1cdc607 100644 --- a/docs/proxy.md +++ b/docs/proxy.md @@ -115,6 +115,17 @@ export HTTPS_PROXY="http://proxy.company.com:8080" python your_script.py ``` +**Kernel backend (`use_kernel=True`):** `negotiate` also works on the kernel +backend, including Reyden connections that recover onto it. It needs the +`requests-kerberos` package, which the `[kernel]` extra does not install. The +proxy and `NO_PROXY` are discovered the same way as above, and a bypassed host +connects directly. The macOS and Windows system bypass lists apply only to the +workspace host; for other hosts, such as CloudFetch storage, the kernel honors +only `NO_PROXY`. A token is created when the session opens and once more if +the proxy answers 407, and it is sent only to the proxy. If no token can be +created (no ticket, expired ticket, missing package), the connection fails +before any request; it never falls back to Basic or a direct connection. + ## Proxy Bypass The connector respects system proxy bypass rules. Requests to hosts listed in `NO_PROXY` or system bypass lists will connect directly, bypassing the proxy. diff --git a/src/databricks/sql/backend/kernel/client.py b/src/databricks/sql/backend/kernel/client.py index 87fcea919..1117275bd 100644 --- a/src/databricks/sql/backend/kernel/client.py +++ b/src/databricks/sql/backend/kernel/client.py @@ -22,9 +22,12 @@ from __future__ import annotations +import functools import inspect import logging import threading +import urllib.parse +import urllib.request import uuid from typing import ( Any, @@ -53,6 +56,7 @@ CommandState, SessionId, ) +from databricks.sql.common.http_utils import detect_proxy, negotiate_proxy_token from databricks.sql.exc import ( InterfaceError, NotSupportedError, @@ -238,6 +242,43 @@ def _kernel_geospatial_kwargs(value: bool) -> Dict[str, bool]: return {"enable_geospatial_support": value} +def _kernel_proxy_kwargs(host: str, proxy_auth_method: Optional[str]) -> Dict[str, Any]: + """Build the kernel proxy kwargs for ``_proxy_auth_method="negotiate"``. + + The proxy is discovered as on Thrift (``getproxies()`` + ``proxy_bypass``). + When a proxy applies, the kernel gets its URL, the ``NO_PROXY`` list and a + callable that creates a fresh token for ``HTTP@``. The kernel + calls it at session open and once more on a proxy 407, and fails closed if + it raises. No proxy, a bypassed host, unset and ``basic`` pass nothing, so + the kernel keeps its environment-proxy behavior. + """ + if proxy_auth_method != "negotiate": + return {} + # A ``_connection_uri`` host is ``scheme://host[:port]``; look the proxy up by + # its scheme and bare hostname, as Thrift does. + target = urllib.parse.urlsplit(host if "://" in host else f"https://{host}") + proxy = detect_proxy(target.scheme, target.hostname) + if not proxy: + return {} + if not _kernel_session_accepts_kwarg("proxy_negotiate_token"): + raise NotSupportedError( + "_proxy_auth_method='negotiate' requires a newer databricks-sql-kernel " + "wheel that supports Negotiate proxy authentication." + ) + parsed = urllib.parse.urlparse(proxy) + # Negotiate replaces Basic, so drop any user:password@ from the URL. + kwargs: Dict[str, Any] = { + "proxy_url": parsed._replace(netloc=parsed.netloc.rpartition("@")[2]).geturl(), + "proxy_negotiate_token": functools.partial( + negotiate_proxy_token, parsed.hostname + ), + } + bypass = urllib.request.getproxies().get("no") + if bypass: + kwargs["proxy_bypass_hosts"] = bypass + return kwargs + + def _validate_telemetry_flush_interval_ms(value: Any) -> None: # PyO3 would accept True as 1ms and report other bad values without # naming the option, so reject them before the kernel sees them. @@ -365,6 +406,8 @@ def __init__( # Kernel telemetry phase 7 adds binding/runtime identity and # telemetry config kwargs directly to ``databricks_sql_kernel.Session``. self._telemetry_options = kwargs.get("telemetry_options") or {} + # Only "negotiate" changes the kernel's proxy handling. + self._proxy_auth_method = kwargs.get("proxy_auth_method") _validate_telemetry_flush_interval_ms( self._telemetry_options.get("telemetry_flush_interval_ms") ) @@ -506,6 +549,9 @@ def open_session( "that accepts a connection port." ) port_kwargs["port"] = self._port + proxy_kwargs = _kernel_proxy_kwargs( + self._server_hostname, self._proxy_auth_method + ) max_connections_kwargs: Dict[str, Any] = {} if _kernel_session_accepts_kwarg("max_connections"): max_connections_kwargs["max_connections"] = self._max_connections @@ -557,6 +603,7 @@ def open_session( **port_kwargs, **max_connections_kwargs, **http_headers_kwargs, + **proxy_kwargs, ) except Exception as exc: raise _wrap_kernel_exception("open_session", exc) from exc diff --git a/src/databricks/sql/common/http_utils.py b/src/databricks/sql/common/http_utils.py index b4e3c1c51..80885ea88 100644 --- a/src/databricks/sql/common/http_utils.py +++ b/src/databricks/sql/common/http_utils.py @@ -1,3 +1,4 @@ +import base64 import ssl import urllib.parse import urllib.request @@ -31,18 +32,7 @@ def detect_and_parse_proxy( Returns: Tuple of (proxy_uri, proxy_headers) or (None, None) if no proxy """ - try: - # returns a dictionary of scheme -> proxy server URL mappings. - # https://docs.python.org/3/library/urllib.request.html#urllib.request.getproxies - proxy = urllib.request.getproxies().get(scheme) - except (KeyError, AttributeError): - # No proxy found or getproxies() failed - disable proxy - proxy = None - else: - # Proxy found, but check if this host should bypass proxy (unless skipped) - if not skip_bypass and host and urllib.request.proxy_bypass(host): - proxy = None # Host bypasses proxy per system rules - + proxy = detect_proxy(scheme, host, skip_bypass) if not proxy: return None, None @@ -60,6 +50,63 @@ def detect_and_parse_proxy( return proxy, proxy_headers +def detect_proxy( + scheme: str, host: Optional[str], skip_bypass: bool = False +) -> Optional[str]: + """Return the system proxy URL for ``scheme``, or None if there is none + or ``host`` bypasses it.""" + try: + # returns a dictionary of scheme -> proxy server URL mappings. + # https://docs.python.org/3/library/urllib.request.html#urllib.request.getproxies + proxy = urllib.request.getproxies().get(scheme) + except (KeyError, AttributeError): + # No proxy found or getproxies() failed - disable proxy + return None + # Proxy found, but check if this host should bypass proxy (unless skipped) + if not skip_bypass and host and urllib.request.proxy_bypass(host): + return None # Host bypasses proxy per system rules + return proxy + + +class _DropSpnegoTokenLogs(logging.Filter): + """Drop pyspnego's DEBUG " step input/output: " records.""" + + def filter(self, record: logging.LogRecord) -> bool: + return " step " not in str(record.msg) + + +_SPNEGO_TOKEN_FILTER = _DropSpnegoTokenLogs() + + +def _hide_spnego_tokens() -> None: + for name in ("spnego._gss", "spnego._negotiate", "spnego._sspi"): + spnego_logger = logging.getLogger(name) + if _SPNEGO_TOKEN_FILTER not in spnego_logger.filters: + spnego_logger.addFilter(_SPNEGO_TOKEN_FILTER) + + +def negotiate_proxy_token(proxy_hostname: Optional[str]) -> bytes: + """Return one fresh raw Kerberos token for ``HTTP@``. + + Uses requests-kerberos like the Thrift path, but raises instead of + returning nothing so the caller fails closed. + """ + try: + from requests_kerberos import HTTPKerberosAuth + except ImportError as e: + raise ImportError( + "_proxy_auth_method='negotiate' requires the requests-kerberos package" + ) from e + _hide_spnego_tokens() + header = HTTPKerberosAuth().generate_request_header( + None, proxy_hostname, is_preemptive=True + ) + scheme, _, token = (header or "").partition(" ") + if scheme != "Negotiate" or not token: + raise ValueError("requests-kerberos returned no Negotiate token") + return base64.b64decode(token) + + def _generate_negotiate_headers( proxy_hostname: Optional[str], ) -> Optional[Dict[str, str]]: @@ -67,6 +114,7 @@ def _generate_negotiate_headers( try: from requests_kerberos import HTTPKerberosAuth + _hide_spnego_tokens() logger.debug( "Attempting to generate Kerberos SPNEGO token for proxy: %s", proxy_hostname ) diff --git a/src/databricks/sql/session.py b/src/databricks/sql/session.py index 3cee629c3..0856ebe6d 100644 --- a/src/databricks/sql/session.py +++ b/src/databricks/sql/session.py @@ -392,6 +392,7 @@ def _create_backend( ), telemetry_options=kernel_telemetry_options, escape_catalog_name=kwargs.get("escape_catalog_name", False), + proxy_auth_method=kwargs.get("_proxy_auth_method"), ) # These reference the lazily-resolved module attributes defined via diff --git a/tests/unit/test_kernel_client.py b/tests/unit/test_kernel_client.py index 8cd6b6b6d..fc03052e2 100644 --- a/tests/unit/test_kernel_client.py +++ b/tests/unit/test_kernel_client.py @@ -669,6 +669,202 @@ def fake_session_without_header_provider( _provider_client(_CountingProvider()).open_session( session_configuration=None, catalog=None, schema=None ) +_HOST = "example.cloud.databricks.com" + + +@pytest.mark.parametrize( + "method, env, expected", + [ + pytest.param(None, {"HTTPS_PROXY": "http://p:3128"}, {}, id="unset"), + pytest.param("basic", {"HTTPS_PROXY": "http://u:pw@p:3128"}, {}, id="basic"), + pytest.param("negotiate", {}, {}, id="no-proxy"), + pytest.param( + "negotiate", + {"HTTPS_PROXY": "http://p:3128", "NO_PROXY": ".databricks.com"}, + {}, + id="host-bypassed", + ), + pytest.param( + "negotiate", + {"HTTPS_PROXY": "http://p.corp:3128"}, + {"proxy_url": "http://p.corp:3128", "token_host": "p.corp"}, + id="proxy", + ), + pytest.param( + "negotiate", + {"HTTPS_PROXY": "http://u:pw@p.corp:3128"}, + {"proxy_url": "http://p.corp:3128", "token_host": "p.corp"}, + id="userinfo-dropped", + ), + pytest.param( + "negotiate", + {"HTTPS_PROXY": "http://p.corp:3128", "NO_PROXY": "localhost,.internal"}, + { + "proxy_url": "http://p.corp:3128", + "token_host": "p.corp", + "proxy_bypass_hosts": "localhost,.internal", + }, + id="bypass-list-forwarded", + ), + pytest.param( + "unknown", {"HTTPS_PROXY": "http://p:3128"}, {}, id="unknown-unchanged" + ), + ], +) +def test_open_session_proxy_kwargs(monkeypatch, method, env, expected): + """Only ``negotiate`` with an applicable proxy reaches the kernel.""" + for name in ("HTTPS_PROXY", "https_proxy", "NO_PROXY", "no_proxy"): + monkeypatch.delenv(name, raising=False) + for name, value in env.items(): + monkeypatch.setenv(name, value) + tokens = [] + monkeypatch.setattr( + kernel_client, + "negotiate_proxy_token", + lambda host: tokens.append(host) or b"tok", + ) + captured = {} + + def fake_session(*, proxy_negotiate_token=None, **kw): + captured.update(kw) + if proxy_negotiate_token is not None: + assert proxy_negotiate_token() == b"tok" + captured["token_host"] = tokens[-1] + sess = MagicMock() + sess.session_id = "sess-id" + return sess + + monkeypatch.setattr(kernel_client._kernel, "Session", fake_session) + c = kernel_client.KernelDatabricksClient( + server_hostname=_HOST, + http_path="/sql/1.0/warehouses/abc", + auth_provider=AccessTokenAuthProvider("dapi-test"), + ssl_options=None, + proxy_auth_method=method, + ) + c.open_session(session_configuration=None, catalog=None, schema=None) + + proxy = {k: v for k, v in captured.items() if k.startswith(("proxy", "token"))} + assert proxy == expected + + +@pytest.mark.parametrize( + "uri_host, env, expected_url", + [ + pytest.param( + "https://example.cloud.databricks.com:8443", + {"HTTPS_PROXY": "http://p.corp:3128"}, + "http://p.corp:3128", + id="uri-proxied", + ), + pytest.param( + "https://example.cloud.databricks.com:8443", + { + "HTTPS_PROXY": "http://p.corp:3128", + "NO_PROXY": "example.cloud.databricks.com", + }, + None, + id="uri-host-bypassed", + ), + pytest.param( + "http://example.cloud.databricks.com", + {"HTTP_PROXY": "http://h.corp:3128", "HTTPS_PROXY": "http://p.corp:3128"}, + "http://h.corp:3128", + id="uri-http-scheme", + ), + ], +) +def test_negotiate_proxy_kwargs_for_connection_uri_host( + monkeypatch, uri_host, env, expected_url +): + """A ``_connection_uri`` host (``scheme://host:port``) is matched by its scheme + and bare hostname, like Thrift.""" + for name in ("HTTPS_PROXY", "https_proxy", "HTTP_PROXY", "http_proxy"): + monkeypatch.delenv(name, raising=False) + for name in ("NO_PROXY", "no_proxy"): + monkeypatch.delenv(name, raising=False) + for name, value in env.items(): + monkeypatch.setenv(name, value) + monkeypatch.setattr( + kernel_client, "_kernel_session_accepts_kwarg", lambda name: True + ) + + kwargs = kernel_client._kernel_proxy_kwargs(uri_host, "negotiate") + + assert kwargs.get("proxy_url") == expected_url + + +def test_negotiate_proxy_with_old_kernel_fails_closed(monkeypatch): + monkeypatch.setenv("HTTPS_PROXY", "http://p.corp:3128") + monkeypatch.delenv("NO_PROXY", raising=False) + monkeypatch.delenv("no_proxy", raising=False) + monkeypatch.setattr( + kernel_client, "_kernel_session_accepts_kwarg", lambda name: False + ) + with pytest.raises(NotSupportedError, match="newer databricks-sql-kernel"): + kernel_client._kernel_proxy_kwargs(_HOST, "negotiate") + + +@pytest.mark.parametrize( + "header, expected", + [ + pytest.param("Negotiate dG9r", b"tok", id="token"), + pytest.param(None, ValueError, id="no-header"), + pytest.param("Basic dG9r", ValueError, id="wrong-scheme"), + pytest.param(RuntimeError("No Kerberos credentials"), RuntimeError, id="gss"), + ], +) +def test_negotiate_proxy_token(monkeypatch, header, expected): + from databricks.sql.common import http_utils + + calls = [] + + class FakeAuth: + def generate_request_header(self, response, host, is_preemptive=False): + calls.append((response, host, is_preemptive)) + if isinstance(header, Exception): + raise header + return header + + fake = types.ModuleType("requests_kerberos") + fake.HTTPKerberosAuth = FakeAuth # type: ignore[attr-defined] + monkeypatch.setitem(sys.modules, "requests_kerberos", fake) + if isinstance(expected, bytes): + assert http_utils.negotiate_proxy_token("p.corp") == expected + else: + with pytest.raises(expected): + http_utils.negotiate_proxy_token("p.corp") + assert calls == [(None, "p.corp", True)] + + +def test_negotiate_proxy_token_hides_spnego_token_logs(monkeypatch, caplog): + import logging + + from databricks.sql.common import http_utils + + fake = types.ModuleType("requests_kerberos") + + class FakeAuth: + def generate_request_header(self, response, host, is_preemptive=False): + spnego_log = logging.getLogger("spnego._gss") + spnego_log.debug("GSSAPI step output: %s", "c2VjcmV0LXRva2Vu") + spnego_log.debug("other spnego detail") + return "Negotiate c2VjcmV0LXRva2Vu" + + fake.HTTPKerberosAuth = FakeAuth # type: ignore[attr-defined] + monkeypatch.setitem(sys.modules, "requests_kerberos", fake) + with caplog.at_level(logging.DEBUG): + assert http_utils.negotiate_proxy_token("p.corp") == b"secret-token" + assert "c2VjcmV0LXRva2Vu" not in caplog.text + assert "other spnego detail" in caplog.text + + +def test_negotiate_proxy_token_requires_requests_kerberos(monkeypatch): + from databricks.sql.common import http_utils + + monkeypatch.setitem(sys.modules, "requests_kerberos", None) + with pytest.raises(ImportError, match="requires the requests-kerberos package"): + http_utils.negotiate_proxy_token("p.corp") def test_open_session_passes_phase_7_telemetry_kwargs_to_kernel(monkeypatch): diff --git a/tests/unit/test_session.py b/tests/unit/test_session.py index bf0d7942f..64ab0e9c5 100644 --- a/tests/unit/test_session.py +++ b/tests/unit/test_session.py @@ -1112,6 +1112,29 @@ def test_kernel_routing_preserves_geospatial_representation( finally: conn.close() + @pytest.mark.parametrize("route", ["explicit", "recovery", "cached"]) + @pytest.mark.parametrize("method", [None, "basic", "negotiate"]) + @patch("%s.session.ThriftDatabricksClient" % PACKAGE) + def test_kernel_routing_preserves_proxy_auth_method( + self, mock_thrift, method, route + ): + from databricks.sql.backend import reyden_warehouse_cache + + mock_thrift.return_value.open_session.side_effect = self._reject() + if route == "cached": + reyden_warehouse_cache.mark_reyden(self.HOST, "wh-reyden") + kwargs = {} if method is None else {"_proxy_auth_method": method} + if route == "explicit": + kwargs["use_kernel"] = True + + with self._fake_kernel() as mock_kernel: + conn = self._connect(**kwargs) + try: + assert conn.session.use_kernel is True + assert mock_kernel.call_args.kwargs["proxy_auth_method"] == method + finally: + conn.close() + @patch("%s.session.ThriftDatabricksClient" % PACKAGE) def test_thrift_rejection_recovers_onto_kernel(self, mock_thrift): mock_thrift.return_value.open_session.side_effect = self._reject()