diff --git a/CHANGELOG.md b/CHANGELOG.md index 43fda3bed..c6806d832 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,7 @@ # Release History # Unreleased +- Honor `_port` and `_connection_uri` on kernel connections (`use_kernel=True`), as Thrift does. The kernel applies `_port`: a port other than 443 (or 80 for an `http://` host) makes the connection use `scheme://host:port`, bare IPv6 hosts are bracketed, and `0`, unset or `443` change nothing. A port embedded in `server_hostname` wins over a differing `_port`, with a warning. For a non-default `_port`, the kernel rejects credentials, a path, query or fragment in the host, an empty host, and a bad embedded port with `InvalidArgument`, which surfaces as `ProgrammingError`. `_connection_uri` (`http(s)://host[:port]/path?query`) sets host, port, path and query and wins over `_port`; URI-only connections work. Invalid `_port` values and malformed URIs raise `ValueError`. With OAuth, a `_connection_uri` origin that differs from `server_hostname` raises. With OAuth and a non-default `_port`, the token exchange goes to the same host:port, unlike Thrift (documented, not guarded). This needs a databricks-sql-kernel release that includes databricks-sql-kernel#505. - 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 f0b3d2ee7..c7f891fce 100644 --- a/CONNECTION_PARAMETERS.md +++ b/CONNECTION_PARAMETERS.md @@ -73,8 +73,8 @@ to change without notice. | ----------------- | ----- | :----: | :----: | ------------- | ----------------------------------------------------------------------------------------------------------------------- | | `server_hostname` | `str` | ✅ | ✅ | — (required) | Workspace hostname, e.g. `dbc-12345.cloud.databricks.com`. | | `http_path` | `str` | ✅ | ✅ | — (required) | Thrift accepts a SQL-warehouse path **or** an all-purpose-cluster path; Kernel requires a warehouse/endpoint path. | -| `_port` | `int` | ✅ | — | `443` | TCP port (advanced). Not threaded to the kernel; it derives host/port from `server_hostname` + `http_path`. | -| `_connection_uri` | `str` | ✅ | — | `None` | Thrift-only internal override of `server_hostname`/`http_path`. No kernel equivalent. | +| `_port` | `int` | ✅ | ✅ | `443` | TCP port (advanced). On Kernel the kernel applies it: a port other than 443 makes the connection use `host:port` (bare IPv6 is bracketed); `0`, unset and `443` change nothing; a port embedded in `server_hostname` wins over a differing `_port` (with a warning). Needs a databricks-sql-kernel release that includes databricks-sql-kernel#505. | +| `_connection_uri` | `str` | ✅ | ✅ | `None` | Overrides `server_hostname`, `_port` and `http_path` on both, and wins over `_port`. On Kernel with OAuth, the URI origin must match `server_hostname`, and OAuth uses the same host:port as the connection (Thrift keeps OAuth on the bare host). An `access_token` that is exchanged counts as OAuth here: a JWT from an issuer other than `server_hostname`, or any token with `identity_federation_client_id`. | | `http_headers` | `List[Tuple[str, str]]` | ✅ | ⚠️ | `None` | Extra headers sent on requests. Kernel filters `Authorization` and `x-databricks-org-id` because it manages them itself; other headers are forwarded. | | `user_agent_entry`| `str` | ✅ | ✅ | `None` | Custom tag folded into the composed `User-Agent` on both. (`_user_agent_entry` is a deprecated alias that warns.) | @@ -213,8 +213,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. `_port` and `_connection_uri`. -10. `_pool_connections` and `_proxy_auth_method` do not configure the +9. `_pool_connections` and `_proxy_auth_method` do not configure the kernel-owned network stack. ### Supported on Kernel, missing / ignored on Thrift diff --git a/KERNEL_REV b/KERNEL_REV index 2add322e2..bb1a004ed 100644 --- a/KERNEL_REV +++ b/KERNEL_REV @@ -1 +1 @@ -5c3a909771f749174567af074bfe18c24a335f5c +22ae6ec250837b38d0e3dc720310d4dcfb81fa98 diff --git a/src/databricks/sql/backend/kernel/client.py b/src/databricks/sql/backend/kernel/client.py index eab9847ca..48b9baab4 100644 --- a/src/databricks/sql/backend/kernel/client.py +++ b/src/databricks/sql/backend/kernel/client.py @@ -238,6 +238,22 @@ def _kernel_geospatial_kwargs(value: bool) -> Dict[str, bool]: return {"enable_geospatial_support": value} +def _kernel_port_kwargs(port: Optional[int]) -> Dict[str, int]: + """Build the kernel ``port`` kwarg. Only a port that applies is passed: unset, 0 and the + default 443 send nothing, so the default path sends the same kwargs as before. The kernel + applies the port to ``host``. A wheel without the kwarg raises rather than silently + connecting to the default port. + """ + if not port or port == 443: + return {} + if not _kernel_session_accepts_kwarg("port"): + raise NotSupportedError( + "_port requires a newer databricks-sql-kernel wheel that exposes the " + "port kwarg." + ) + return {"port": port} + + 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. @@ -321,10 +337,12 @@ def __init__( # toggles, mTLS client cert/key). ``http_headers`` is forwarded # to the kernel as custom request headers (it carries the # connector's composed ``User-Agent`` + any caller headers + the - # SPOG ``x-databricks-org-id``). ``http_client`` / ``port`` are - # still accept-and-ignore — the kernel manages its own HTTP - # stack. + # SPOG ``x-databricks-org-id``). ``port`` (the resolved ``_port``, + # or ``None``) is forwarded as the kernel's ``port`` kwarg, which + # the kernel applies to ``server_hostname``. ``http_client`` is + # accept-and-ignore — the kernel manages its own HTTP stack. self._server_hostname = server_hostname + self._port: Optional[int] = kwargs.get("port") self._http_path = http_path self._auth_provider = auth_provider self._ssl_options = ssl_options @@ -488,6 +506,7 @@ def open_session( geospatial_kwargs = _kernel_geospatial_kwargs( self._enable_geospatial_support ) + port_kwargs = _kernel_port_kwargs(self._port) max_connections_kwargs: Dict[str, Any] = {} if _kernel_session_accepts_kwarg("max_connections"): max_connections_kwargs["max_connections"] = self._max_connections @@ -536,6 +555,7 @@ def open_session( **retry_kwargs, **telemetry_kwargs, **geospatial_kwargs, + **port_kwargs, **max_connections_kwargs, **http_headers_kwargs, ) diff --git a/src/databricks/sql/client.py b/src/databricks/sql/client.py index d8240efaf..bf6a63840 100755 --- a/src/databricks/sql/client.py +++ b/src/databricks/sql/client.py @@ -193,6 +193,15 @@ def __init__( decision. This is an intentional divergence from the Thrift/SEA paths, where an explicit ``True`` can still be suppressed by the feature flag. + + Kernel overrides: _port sends the connection to that port + (the default 443 adds nothing; a falsy _port means the default). A port + embedded in server_hostname wins over a differing _port, with a warning. + _connection_uri (https://host[:port]/path?query) + sets host, port, path and query, as on Thrift, and wins over _port. + With OAuth, _connection_uri must have the same origin as + server_hostname. With OAuth and a non-default _port, the token + exchange goes to the same host:port, unlike Thrift. :param enable_geospatial_support: `bool`, optional (default is False) Kernel backend only. Controls the public representation of ``GEOMETRY`` and ``GEOGRAPHY`` result values. ``True`` returns diff --git a/src/databricks/sql/session.py b/src/databricks/sql/session.py index cd91693d3..309d686f8 100644 --- a/src/databricks/sql/session.py +++ b/src/databricks/sql/session.py @@ -1,12 +1,15 @@ import logging import re from functools import cached_property +from urllib.parse import urlsplit from typing import Dict, Tuple, List, Optional, Any, Type, TYPE_CHECKING from databricks.sql.types import SSLOptions from databricks.sql.auth.auth import get_python_sql_connector_auth_provider +from databricks.sql.auth.auth_utils import decode_token, is_same_host from databricks.sql.auth.authenticators import AccessTokenAuthProvider from databricks.sql.auth.common import ClientContext +from databricks.sql.common.url_utils import normalize_host_with_protocol from databricks.sql.exc import SessionAlreadyClosedError, DatabaseError, RequestError from databricks.sql import __version__ from databricks.sql import USER_AGENT_NAME @@ -47,6 +50,189 @@ def __getattr__(name: str) -> Any: raise AttributeError(f"module {__name__!r} has no attribute {name!r}") +_OAUTH_AUTH_TYPES = ("databricks-oauth", "azure-oauth", "azure-sp-m2m") + + +def _port_or_none(value: Any) -> Optional[int]: + """Validate ``_port``. A falsy value (None, 0, '', False) means the default, as on + Thrift (``port or 443``); a truthy value must be an integer between 1 and 65535. + """ + if not value or (isinstance(value, str) and not value.strip()): + return None + text = ( + str(value).strip() + if isinstance(value, (int, str)) and not isinstance(value, bool) + else "" + ) + # isdigit with isascii rejects signs, whitespace and underscores that int() would accept. + if not (text.isascii() and text.isdigit()) or int(text) > 65535: + raise ValueError( + f"Invalid _port {value!r}: expected an integer between 1 and 65535" + ) + return int(text) or None + + +def _redact(value: str) -> str: + """Keep only scheme and host[:port] of a URI or host string for an error message. + + Userinfo, path, query and fragment can carry credentials, so they never reach an + exception text or log line. + """ + scheme, sep, rest = value.partition("://") + if not sep: + scheme, rest = "", value + elif scheme.lower() not in ("http", "https"): + # Not a real scheme: in a scheme-less URI such as "h.io/x?token=t&next=https://e", + # everything before "://" is path and query, so none of it is shown. + scheme = "" + # A "/" or "?" can sit inside a password, and "@" can sit in a path, so once any + # userinfo marker is present the whole authority is dropped rather than guessed at. + if "@" in value or "%40" in value.lower(): + return f"{scheme}{sep}" + try: + host = urlsplit(f"//{rest}").netloc + except ValueError: + # urlsplit refuses some hosts (bad IPv6, NFKC-unsafe text); show none of them. + return f"{scheme}{sep}" + return f"{scheme}{sep}{host}" + + +def _uri_host_and_path(uri: str) -> Tuple[str, str]: + """Split a ``_connection_uri`` into the kernel host (scheme, authority) and path.""" + try: + parts = urlsplit(uri) + except ValueError: + parts = None + if parts is None: + # Raised outside the except block so no chained exception carries urlsplit's netloc. + raise ValueError( + f"Invalid _connection_uri {_redact(uri)!r}: could not be parsed" + ) + try: + port = parts.port + except ValueError: + port = 0 + if ( + parts.scheme not in ("http", "https") + or not parts.hostname + or "@" in parts.netloc + or port == 0 + # urlsplit reads "h.io:" as no port; an empty port is malformed. + or parts.netloc.endswith(":") + or parts.path in ("", "/") + ): + raise ValueError( + f"Invalid _connection_uri {_redact(uri)!r}: expected http(s)://host[:port]/path with a " + "warehouse path and no credentials" + ) + return f"{parts.scheme}://{parts.netloc}", parts.path + ( + f"?{parts.query}" if parts.query else "" + ) + + +def _kernel_endpoint( + server_hostname: str, http_path: str, kwargs: dict +) -> Tuple[str, str, Optional[int]]: + """Resolve the kernel ``(host, http_path, port)``. ``_connection_uri`` gives the host + (with any port in it) and the path, and wins over ``_port``, so no port is passed. + Otherwise ``server_hostname`` and ``http_path`` pass through and ``_port`` is passed as + the kernel's ``port``, which applies it. ``None`` and the default 443 pass no port. + """ + if kwargs.get("_connection_uri"): + host, path = _uri_host_and_path(kwargs["_connection_uri"]) + return host, path, None + port = _port_or_none(kwargs.get("_port")) + return server_hostname, http_path, None if port == 443 else port + + +def _is_foreign_jwt(access_token: str, server_hostname: str) -> bool: + """True when ``access_token`` is a JWT whose issuer is not ``server_hostname``. Thrift + token-exchanges such a token at server_hostname (TokenFederationProvider); the kernel + wraps every provider with the connection host, so it exchanges at the connection host. + """ + claims = decode_token(access_token) + if not claims: + return False + issuer = claims.get("iss", "") + return not is_same_host(issuer, normalize_host_with_protocol(server_hostname)) + + +def _server_origin(server_hostname: str) -> Tuple[str, Optional[int]]: + """Host and port of ``server_hostname`` for the OAuth origin check. A value with no + comparable origin (credentials, a bare IPv6 literal, an empty or out-of-range port) + returns ``("", None)``, so it never matches and is reported as an origin mismatch. + """ + netloc = server_hostname.rstrip("/").rpartition("://")[2] + # urlsplit reads a trailing ':' as an empty port, which has no origin. + if netloc.endswith(":"): + return "", None + try: + parts = urlsplit(f"//{netloc}") + port = parts.port + except ValueError: + return "", None + if port == 0 or ("@" in parts.netloc and parts.password is not None): + return "", None + return parts.hostname or "", port + + +def _check_oauth_origin(server_hostname: str, kernel_host: str, kwargs: dict) -> None: + """AC-P4: with OAuth, a ``_connection_uri`` origin must equal ``https://server_hostname``. + Thrift keeps OAuth on server_hostname; the kernel uses one host for API and token calls. + URI-only use (empty server_hostname) has no server origin to compare and is not checked. + """ + if not (kwargs.get("_connection_uri") and server_hostname): + return + access_token = kwargs.get("access_token") + # A JWT from a foreign issuer is exchanged, so it is an OAuth credential even though + # it arrives as access_token. Thrift judges the issuer against server_hostname and the + # kernel against its connection host, so a token foreign to either is exchanged. + foreign_jwt = bool( + access_token + and ( + _is_foreign_jwt(access_token, server_hostname) + or _is_foreign_jwt(access_token, kernel_host) + ) + ) + # identity_federation_client_id makes the kernel exchange the access_token at the + # connection host (mandatory workload-identity exchange), so it is exchanged like a + # foreign JWT, whatever the token's issuer. + federated = bool(access_token and kwargs.get("identity_federation_client_id")) + exchanged = foreign_jwt or federated + oauth = ( + kwargs.get("auth_type") in _OAUTH_AUTH_TYPES + or kwargs.get("oauth_jwt_key_file") + or (kwargs.get("oauth_client_id") and kwargs.get("oauth_client_secret")) + or exchanged + ) + # The kernel auth bridge routes an access_token with no JWT or client-secret + # M2M credentials to PAT, even for auth_type='databricks-oauth'; azure-sp-m2m + # is resolved before that branch and stays OAuth. A custom credentials_provider + # is rejected by the bridge, so it is not an OAuth origin here. + routed_to_pat = ( + bool(access_token) + and not exchanged + and kwargs.get("auth_type") != "azure-sp-m2m" + and not kwargs.get("oauth_jwt_key_file") + and not (kwargs.get("oauth_client_id") and kwargs.get("oauth_client_secret")) + ) + if routed_to_pat or not oauth: + return + server_host, port = _server_origin(server_hostname) + uri = urlsplit(kernel_host) + if (uri.scheme, uri.hostname or "", uri.port or 443) != ( + "https", + server_host, + port or 443, + ): + raise ValueError( + f"OAuth requires the _connection_uri origin to match " + f"https://{_redact(server_hostname)}; " + f"the kernel would send the credentials to {_redact(kernel_host)}. " + "Use a PAT or match the origin." + ) + + class Session: def __init__( self, @@ -323,9 +509,24 @@ def _create_backend( "_telemetry_circuit_breaker_enabled" ), } + kernel_host, kernel_http_path, kernel_port = _kernel_endpoint( + server_hostname, http_path, kwargs + ) + _check_oauth_origin(server_hostname, kernel_host, kwargs) + if kernel_http_path != http_path: + # A _connection_uri can point at another workspace: re-derive the + # SPOG org-id header from the resolved path (a caller header still wins). + base_headers = [ + h for h in all_headers if h not in self._spog_headers.items() + ] + self._spog_headers = self._extract_spog_headers( + kernel_http_path, base_headers + ) + all_headers = base_headers + list(self._spog_headers.items()) return KernelDatabricksClient( - server_hostname=server_hostname, - http_path=http_path, + server_hostname=kernel_host, + http_path=kernel_http_path, + port=kernel_port, http_headers=all_headers, auth_provider=auth_provider, ssl_options=self.ssl_options, diff --git a/tests/unit/test_kernel_client.py b/tests/unit/test_kernel_client.py index 5bad2040b..6d1ae5e72 100644 --- a/tests/unit/test_kernel_client.py +++ b/tests/unit/test_kernel_client.py @@ -541,6 +541,96 @@ def test_geospatial_option_rejects_non_bool(): kernel_client._kernel_geospatial_kwargs("false") +@pytest.mark.parametrize("port", [1, 8443, 65535]) +def test_open_session_passes_port_to_kernel_as_port_kwarg(monkeypatch, port): + """A resolved ``_port`` reaches the binding as ``port=``. The host is passed + unchanged: the kernel applies the port, not the driver.""" + captured = {} + + def fake_session(**kw): + captured.update(kw) + return MagicMock(session_id="sess-id") + + monkeypatch.setattr(kernel_client._kernel, "Session", fake_session) + c = kernel_client.KernelDatabricksClient( + server_hostname="example.cloud.databricks.com", + http_path="/sql/1.0/warehouses/abc", + auth_provider=AccessTokenAuthProvider("dapi-test"), + ssl_options=None, + port=port, + ) + c.open_session(session_configuration=None, catalog=None, schema=None) + + assert captured["host"] == "example.cloud.databricks.com" + assert captured["port"] == port + + +@pytest.mark.parametrize("port", [None, 443]) +def test_open_session_sends_no_port_kwarg_when_no_port_applies(monkeypatch, port): + """Unset (``None``) and the default 443 send no ``port`` kwarg, so the default path + is unchanged for wheels that predate the kwarg.""" + captured = {} + + def fake_session(**kw): + captured.update(kw) + return MagicMock(session_id="sess-id") + + monkeypatch.setattr(kernel_client._kernel, "Session", fake_session) + c = kernel_client.KernelDatabricksClient( + server_hostname="example.cloud.databricks.com", + http_path="/sql/1.0/warehouses/abc", + auth_provider=AccessTokenAuthProvider("dapi-test"), + ssl_options=None, + port=port, + ) + c.open_session(session_configuration=None, catalog=None, schema=None) + + assert "port" not in captured + assert captured["host"] == "example.cloud.databricks.com" + + +def test_port_kwargs_are_empty_without_a_port(): + assert kernel_client._kernel_port_kwargs(None) == {} + + +def test_port_requires_kernel_wheel_that_accepts_port(monkeypatch): + """A wheel whose fixed ``Session`` signature has no ``port`` raises instead of + connecting to the default port. The real signature introspection decides.""" + calls = [] + + def fake_session_without_port( + host, + http_path, + *, + catalog=None, + schema=None, + session_conf=None, + complex_types_as_json=False, + intervals_as_string=False, + request_timeout_secs=None, + auth_type=None, + access_token=None, + enable_geospatial_support=False, + ): + calls.append(host) + sess = MagicMock() + sess.session_id = "sess-id" + return sess + + monkeypatch.setattr(kernel_client._kernel, "Session", fake_session_without_port) + c = kernel_client.KernelDatabricksClient( + server_hostname="example.cloud.databricks.com", + http_path="/sql/1.0/warehouses/abc", + auth_provider=AccessTokenAuthProvider("dapi-test"), + ssl_options=None, + port=8443, + ) + + with pytest.raises(NotSupportedError, match="_port requires a newer"): + c.open_session(session_configuration=None, catalog=None, schema=None) + assert calls == [] + + def test_open_session_passes_phase_7_telemetry_kwargs_to_kernel(monkeypatch): """Kernel telemetry phase 7 added binding/runtime identity and telemetry config kwargs to ``databricks_sql_kernel.Session``.""" diff --git a/tests/unit/test_session.py b/tests/unit/test_session.py index fb889d856..b88ebe305 100644 --- a/tests/unit/test_session.py +++ b/tests/unit/test_session.py @@ -2,6 +2,12 @@ from unittest.mock import patch, MagicMock, Mock, PropertyMock from contextlib import contextmanager import gc +import importlib.metadata as ilm +import jwt +import socket +import sys +import threading +import types from databricks.sql.thrift_api.TCLIService.ttypes import ( TOpenSessionResp, @@ -10,15 +16,17 @@ ) from databricks.sql.backend.types import SessionId, BackendType from databricks.sql.common.agent import KNOWN_AGENTS +from databricks.sql.session import _kernel_endpoint, _check_oauth_origin + +import databricks.sql from databricks.sql.exc import ( ReydenThriftUnsupportedError, DatabaseError, + NotSupportedError, OperationalError, ) from databricks.sql.session import Session -import databricks.sql - class TestSession: """ @@ -1184,3 +1192,599 @@ def test_pat_recovery_does_not_inject_auth_type(self, mock_thrift): assert kwargs["auth_options"].get("auth_type") is None finally: conn.close() + + +# ---- kernel _port / _connection_uri resolution (use_kernel=True) ---- +# The kernel applies _port (host:port folding, IPv6 brackets, embedded-port rules, and +# credential/path/query checks), so these tests cover only what the driver resolves: +# the host, the port and the path that reach the kernel. + +_P = "/sql/1.0/warehouses/abc" + + +@pytest.mark.parametrize( + "server, kwargs, expected_port", + [ + # A non-default _port is passed as port=; server_hostname is passed unchanged. + ("h.io", {"_port": 8443}, 8443), + ("h.io", {"_port": "8443"}, 8443), + ("h.io", {"_port": 1}, 1), + ("h.io", {"_port": 65535}, 65535), + ("[::1]", {"_port": 8443}, 8443), + ("h.io:8443", {"_port": 8443}, 8443), + ("h.io/x", {"_port": 8443}, 8443), + ("", {"_port": 8443}, 8443), + # Unset, falsy and the default 443 pass no port, so the host is untouched. + ("h.io", {}, None), + ("h.io", {"_port": None}, None), + ("h.io", {"_port": ""}, None), + ("h.io", {"_port": " "}, None), + ("h.io", {"_port": False}, None), + ("h.io", {"_port": 0}, None), + ("h.io", {"_port": "0"}, None), + ("h.io", {"_port": 443}, None), + ("h.io", {"_port": "443"}, None), + ("h.io:0", {}, None), + ], +) +def test_kernel_endpoint_passes_host_unchanged_and_port_separately( + server, kwargs, expected_port +): + assert _kernel_endpoint(server, _P, kwargs) == (server, _P, expected_port) + + +@pytest.mark.parametrize( + "kwargs, expected", + [ + # _connection_uri gives the host (with any port), the path and the query. It wins + # over _port, which is not passed. + ( + {"_connection_uri": "https://d.io:8443/sql/1.0/warehouses/xyz"}, + ("https://d.io:8443", "/sql/1.0/warehouses/xyz", None), + ), + ( + {"_connection_uri": "https://h.io/sql/x?o=123"}, + ("https://h.io", "/sql/x?o=123", None), + ), + ( + {"_connection_uri": "http://h.io:8080/sql/x"}, + ("http://h.io:8080", "/sql/x", None), + ), + ( + {"_connection_uri": "https://d.io:9999/p", "_port": 8443}, + ("https://d.io:9999", "/p", None), + ), + ], +) +def test_connection_uri_resolves_host_and_path_and_passes_no_port(kwargs, expected): + assert _kernel_endpoint("h.io", _P, kwargs) == expected + + +def test_connection_uri_only_resolves_host_and_path(): + assert _kernel_endpoint("", "", {"_connection_uri": "https://h.io/sql/x"}) == ( + "https://h.io", + "/sql/x", + None, + ) + + +@pytest.mark.parametrize( + "kwargs, message", + [ + # The driver parses _port as an int in 1..65535 (falsy means the default). + ({"_port": -1}, "Invalid _port"), + ({"_port": 65536}, "Invalid _port"), + ({"_port": "abc"}, "Invalid _port"), + ({"_port": True}, "Invalid _port"), + ({"_port": 8443.5}, "Invalid _port"), + # _connection_uri must be http(s) with a host and a warehouse path, no credentials. + ({"_connection_uri": "d.io/sql/x"}, "Invalid _connection_uri"), + ({"_connection_uri": "ftp://h.io/sql/x"}, "Invalid _connection_uri"), + ({"_connection_uri": "https://h.io:8443"}, "Invalid _connection_uri"), + ({"_connection_uri": "https://h.io:8443/"}, "Invalid _connection_uri"), + ({"_connection_uri": "https://h.io:notaport/sql/x"}, "Invalid _connection_uri"), + ({"_connection_uri": "https://h.io:0/sql/x"}, "Invalid _connection_uri"), + ({"_connection_uri": "https://h.io:/sql/x"}, "Invalid _connection_uri"), + ({"_connection_uri": "https://[::1]:/sql/x"}, "Invalid _connection_uri"), + ({"_connection_uri": "https://u:p@h.io/sql/x"}, "Invalid _connection_uri"), + ({"_connection_uri": "https:///sql/x"}, "Invalid _connection_uri"), + ], +) +def test_kernel_endpoint_rejects_driver_owned_inputs(kwargs, message): + with pytest.raises(ValueError, match=message): + _kernel_endpoint("h", _P, kwargs) + + +@pytest.mark.parametrize( + "server, port", + [ + ("h.io:8443", 443), + ("h.io", 8443), + ("h.io/x", 8443), + ("h.io", ""), + ], +) +@patch("databricks.sql.session.ThriftDatabricksClient") +def test_thrift_receives_host_and_port_unchanged(mock_client_class, server, port): + # Thrift is unchanged: the host and _port reach ThriftDatabricksClient verbatim, and + # ThriftDatabricksClient applies its own `port or 443` to the URL. The kernel-only + # port handling above does not apply here. + connection = databricks.sql.connect( + server_hostname=server, + http_path=_P, + access_token="tok", + enable_telemetry=False, + _port=port, + ) + call_kwargs = mock_client_class.call_args.kwargs + assert call_kwargs["server_hostname"] == server + assert call_kwargs["port"] == port + connection.close() + + +@pytest.mark.parametrize( + "server, kwargs, uri, should_raise", + [ + # AC-P4: with OAuth, the _connection_uri origin must equal https://server_hostname. + ( + "h.io", + {"oauth_client_id": "c", "oauth_client_secret": "s"}, + "https://evil.io/sql/x", + True, + ), + ("h.io", {"auth_type": "azure-sp-m2m"}, "https://evil.io/sql/x", True), + ("h.io", {"oauth_jwt_key_file": "/k.pem"}, "https://evil.io/sql/x", True), + ("h.io", {"auth_type": "databricks-oauth"}, "http://h.io/sql/x", True), + ("h.io", {"auth_type": "databricks-oauth"}, "https://h.io:8443/sql/x", True), + ("h.io", {"auth_type": "databricks-oauth"}, "https://H.io/sql/x", False), + ( + "h.io:8443", + {"auth_type": "databricks-oauth"}, + "https://h.io:8443/sql/x", + False, + ), + ("[::1]", {"auth_type": "databricks-oauth"}, "https://[::1]/sql/x", False), + ( + "h.io", + {"access_token": "dapi"}, + "https://evil.io/sql/x", + False, + ), # PAT is not guarded + # The auth bridge routes access_token with no M2M/JWT credentials to PAT, + # even when auth_type is databricks-oauth; azure-sp-m2m and M2M/JWT stay guarded. + ( + "h.io", + {"auth_type": "databricks-oauth", "access_token": "dapi"}, + "https://evil.io/sql/x", + False, + ), + ( + "h.io", + {"auth_type": "azure-sp-m2m", "access_token": "dapi"}, + "https://evil.io/sql/x", + True, + ), + # The kernel auth bridge rejects a custom credentials_provider with NotSupportedError, + # so the origin guard does not classify it as OAuth. + ( + "h.io", + {"credentials_provider": object()}, + "https://evil.io/sql/x", + False, + ), + ( + "h.io", + {"oauth_jwt_key_file": "/k.pem", "access_token": "dapi"}, + "https://evil.io/sql/x", + True, + ), + ( + "h.io", + { + "oauth_client_id": "c", + "oauth_client_secret": "s", + "access_token": "dapi", + }, + "https://evil.io/sql/x", + True, + ), + ( + "", + {"auth_type": "databricks-oauth"}, + "https://h.io/sql/x", + False, + ), # URI-only + ( + "h.io", + {"auth_type": "databricks-oauth", "_port": 8443}, + None, + False, + ), # documented, not guarded + # A server_hostname with no comparable origin is an origin mismatch, not a + # "malformed host" error. + ("::1", {"auth_type": "databricks-oauth"}, "https://h.io/sql/x", True), + ("h.io:", {"auth_type": "databricks-oauth"}, "https://h.io/sql/x", True), + ( + "user:pass@h.io", + {"auth_type": "databricks-oauth"}, + "https://h.io/sql/x", + True, + ), + ], +) +def test_oauth_origin_guard(server, kwargs, uri, should_raise): + kwargs = dict(kwargs) + if uri is not None: + kwargs["_connection_uri"] = uri + kernel_host = _kernel_endpoint(server, _P, kwargs)[0] + if should_raise: + with pytest.raises(ValueError, match="requires the _connection_uri origin"): + _check_oauth_origin(server, kernel_host, kwargs) + else: + _check_oauth_origin(server, kernel_host, kwargs) + + +def _jwt(issuer): + # Unverified on purpose: the guard only reads the iss claim, so the key is a placeholder. + return jwt.encode({"iss": issuer, "sub": "user"}, "k" * 32, algorithm="HS256") + + +@pytest.mark.parametrize( + "server, uri, token, should_raise", + [ + # A foreign-issuer JWT is exchanged at the kernel's connection host, so a + # mismatched _connection_uri origin must fail before any request. + ( + "h.io", + "https://evil.io/sql/x", + _jwt("https://login.microsoftonline.com/tenant/v2.0"), + True, + ), + # The same foreign JWT is fine when the _connection_uri origin matches. + ( + "h.io", + "https://h.io/sql/x", + _jwt("https://login.microsoftonline.com/tenant/v2.0"), + False, + ), + # An issuer on the server host is not exchanged (Thrift parity), so it passes. + ("h.io", "https://h.io/sql/x", _jwt("https://h.io/oidc"), False), + # The same issuer is foreign to a different _connection_uri host, where the kernel + # exchanges it, so the mismatched origin fails. + ("h.io", "https://other.io/sql/x", _jwt("https://h.io/oidc"), True), + # A PAT is not a JWT and is not guarded. + ("h.io", "https://evil.io/sql/x", "dapi-xyz", False), + ], +) +def test_foreign_issuer_access_token_origin_guard(server, uri, token, should_raise): + kwargs = {"access_token": token, "_connection_uri": uri} + kernel_host = _kernel_endpoint(server, _P, kwargs)[0] + if should_raise: + with pytest.raises(ValueError, match="requires the _connection_uri origin"): + _check_oauth_origin(server, kernel_host, kwargs) + else: + _check_oauth_origin(server, kernel_host, kwargs) + + +@pytest.mark.parametrize( + "uri, should_raise", + [ + # identity_federation_client_id makes the kernel exchange the token at the + # connection host, so a mismatched origin must fail even for an opaque token. + ("https://evil.io/sql/x", True), + ("https://h.io/sql/x", False), + ], +) +def test_federation_client_id_access_token_origin_guard(uri, should_raise): + kwargs = { + "access_token": "dapi-xyz", + "identity_federation_client_id": "sp-client", + "_connection_uri": uri, + } + kernel_host = _kernel_endpoint("h.io", _P, kwargs)[0] + if should_raise: + with pytest.raises(ValueError, match="requires the _connection_uri origin"): + _check_oauth_origin("h.io", kernel_host, kwargs) + else: + _check_oauth_origin("h.io", kernel_host, kwargs) + + +def test_foreign_issuer_access_token_without_connection_uri_is_unaffected(): + # No _connection_uri: the kernel host is the server_hostname, so there is no origin to check. + kwargs = {"access_token": _jwt("https://login.microsoftonline.com/tenant/v2.0")} + _check_oauth_origin("h.io", "h.io", kwargs) + + +@pytest.mark.parametrize( + "uri, secret", + [ + ("https://user:secret@h.io/sql/x", "secret"), + ("https://h.io:8443?token=secret", "secret"), + # "@" after the host with no path: the URI is rejected, and the "@" must not leak. + ("https://h.io?x=a@secret", "secret"), + # Percent-encoded "@" hides the userinfo marker from a literal "@" check. + ("https://user%3Asecret%40h.io", "secret"), + # A "/" or "?" inside the password must not cut the authority short. + ("https://user:sec/ret@h.io/sql/x", "sec/ret"), + ("https://user:sec?ret@h.io/sql/x", "sec?ret"), + # A "/" inside the password, with "@" after it in the path: netloc stops at "/". + ("https://user:secret/foo@h.io/sql/x", "secret"), + # A fullwidth solidus makes urlsplit's NFKC check raise with the raw netloc in its text. + ("https://user:secret@h.io/sql/x", "secret"), + # Scheme-less, with "://" inside the query: the text before it is not a scheme. + ("h.io/sql/x?token=secret&redirect=https://example.com", "secret"), + # A non-http(s) prefix before "://" is not shown either. + ("token=secret://h.io/sql/x", "secret"), + ], +) +def test_invalid_connection_uri_message_omits_credentials(uri, secret): + with pytest.raises(ValueError, match="Invalid _connection_uri") as exc: + _kernel_endpoint("h", _P, {"_connection_uri": uri}) + assert secret not in str(exc.value) + # The secret must not survive in a chained cause or context either. + assert exc.value.__cause__ is None + assert exc.value.__context__ is None or secret not in str(exc.value.__context__) + + +def test_oauth_origin_message_omits_uri_query(): + kwargs = { + "auth_type": "databricks-oauth", + "_connection_uri": "https://evil.io/sql/x?token=secret", + } + kernel_host = _kernel_endpoint("h.io", _P, kwargs)[0] + with pytest.raises(ValueError, match="requires the _connection_uri origin") as exc: + _check_oauth_origin("h.io", kernel_host, kwargs) + assert "secret" not in str(exc.value) + assert "https://evil.io" in str(exc.value) + + +@pytest.mark.parametrize( + "conn_kwargs, expected_host, expected_path, expected_port", + [ + # _port reaches the kernel client as port=; server_hostname is unchanged. + ( + {"server_hostname": "h.io", "http_path": _P, "_port": 8443}, + "h.io", + _P, + 8443, + ), + ( + {"server_hostname": "h.io", "http_path": _P, "_port": "8443"}, + "h.io", + _P, + 8443, + ), + # Unset, falsy and 443 send no port. + ({"server_hostname": "h.io", "http_path": _P}, "h.io", _P, None), + ({"server_hostname": "h.io", "http_path": _P, "_port": 443}, "h.io", _P, None), + ({"server_hostname": "h.io", "http_path": _P, "_port": 0}, "h.io", _P, None), + # _connection_uri supplies the host (with its port) and the path; no port. + ( + { + "server_hostname": "h.io", + "http_path": _P, + "_connection_uri": f"https://d.io:9999{_P}", + "_port": 8443, + }, + "https://d.io:9999", + _P, + None, + ), + ( + { + "server_hostname": "", + "http_path": "", + "_connection_uri": f"https://d.io:9999{_P}", + }, + "https://d.io:9999", + _P, + None, + ), + ], +) +def test_resolved_kernel_host_and_path_reach_kernel_client( + fake_kernel, conn_kwargs, expected_host, expected_path, expected_port +): + client, _ = fake_kernel + databricks.sql.connect( + use_kernel=True, + access_token="dapi-xyz", + enable_telemetry=False, + **conn_kwargs, + ).close() + kwargs = client.call_args.kwargs + assert kwargs["server_hostname"] == expected_host + assert kwargs["http_path"] == expected_path + assert kwargs["port"] == expected_port + + +@pytest.fixture +def fake_kernel(): + """Fake the kernel wheel and client so connect() runs without a warehouse.""" + pytest.importorskip( + "pyarrow", reason="kernel client module imports pyarrow at load" + ) + fake = types.ModuleType("databricks_sql_kernel") + fake.KernelError = type("KernelError", (Exception,), {}) + fake.Session = MagicMock() + with patch.dict(sys.modules, {"databricks_sql_kernel": fake}), patch( + "databricks.sql.backend.kernel.client.KernelDatabricksClient" + ) as client, patch("databricks.sql.session.get_python_sql_connector_auth_provider"): + client.return_value.open_session.return_value = SessionId( + BackendType.SEA, "sess-id", None + ) + yield client, fake + + +def test_oauth_guard_refuses_before_kernel_client_is_built(fake_kernel): + client, fake = fake_kernel + with pytest.raises(ValueError, match="requires the _connection_uri origin"): + databricks.sql.connect( + server_hostname="h.io", + http_path=_P, + use_kernel=True, + enable_telemetry=False, + oauth_client_id="c", + oauth_client_secret="s", + _connection_uri="https://evil.io/sql/x", + ) + client.assert_not_called() + fake.Session.assert_not_called() + + +@pytest.mark.parametrize( + "hp, uri, expected_org", + [ + ("/sql/1.0/warehouses/abc?o=111", "https://d.io/sql/x?o=222", "222"), + ("/sql/1.0/warehouses/abc?o=111", "https://d.io/sql/x", None), + ("/sql/1.0/warehouses/abc", "https://d.io/sql/x?o=222", "222"), + ("/sql/1.0/warehouses/abc?o=111", None, "111"), + ], +) +def test_spog_org_id_follows_resolved_path(fake_kernel, hp, uri, expected_org): + client, _ = fake_kernel + extra = {"_connection_uri": uri} if uri else {} + databricks.sql.connect( + server_hostname="h.io", + http_path=hp, + access_token="dapi", + use_kernel=True, + enable_telemetry=False, + **extra, + ).close() + assert ( + dict(client.call_args.kwargs["http_headers"]).get("x-databricks-org-id") + == expected_org + ) + + +def _require_real_kernel_wheel(port_kwarg): + """Skip unless the kernel wheel is installed and, when ``port_kwarg`` is set, its + ``Session`` takes ``port``. An older wheel raises NotSupportedError for a non-default + ``_port``, which a loopback test would otherwise report as a listener timeout.""" + try: + ilm.version("databricks-sql-kernel") + except ilm.PackageNotFoundError: + pytest.skip("databricks-sql-kernel wheel not installed") + if port_kwarg: + from databricks.sql.backend.kernel import client as kernel_client + + if not kernel_client._kernel_session_accepts_kwarg("port"): + pytest.skip("installed databricks-sql-kernel wheel has no port kwarg") + + +@pytest.mark.realkernel +@pytest.mark.parametrize( + "build, port_kwarg", + [ + ( + lambda p: {"server_hostname": "127.0.0.1", "http_path": _P, "_port": p}, + True, + ), + ( + lambda p: { + "server_hostname": "", + "http_path": "", + "_connection_uri": f"https://127.0.0.1:{p}{_P}", + }, + False, + ), + ], + ids=["port", "uri-only"], +) +def test_kernel_dials_over_tls(build, port_kwarg): + """Loopback dial on the real kernel wheel: a TCP listener on 127.0.0.1 must receive the + kernel's TLS handshake (first byte 0x16) at the requested port. Nothing completes the + handshake, so connect() is expected to fail; only the dial is asserted.""" + _require_real_kernel_wheel(port_kwarg) + listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + listener.bind(("127.0.0.1", 0)) + listener.listen(1) + listener.settimeout(60) + port = listener.getsockname()[1] + received = {} + + def accept_one(): + try: + sock, _ = listener.accept() + sock.settimeout(10) + received["first_byte"] = sock.recv(1) + sock.close() + except OSError as exc: + received["error"] = repr(exc) + finally: + listener.close() + + thread = threading.Thread(target=accept_one, daemon=True) + thread.start() + try: + databricks.sql.connect( + use_kernel=True, + access_token="dapi-xyz", + enable_telemetry=False, + _retry_stop_after_attempts_count=1, + **build(port), + ).close() + except NotSupportedError: + raise + except Exception: + pass # expected: nothing behind the listener completes TLS + thread.join(timeout=70) + assert "error" not in received, received + assert received.get("first_byte") == b"\x16", received + + +@pytest.mark.realkernel +def test_kernel_embedded_port_wins_over_explicit_port(): + """Loopback on the real kernel wheel: server_hostname 'h:P1' with an explicit _port P2 + dials P1 (TLS first byte 0x16) and never P2.""" + _require_real_kernel_wheel(port_kwarg=True) + + def listen(): + sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + sock.bind(("127.0.0.1", 0)) + sock.listen(1) + sock.settimeout(15) + return sock + + embedded, explicit = listen(), listen() + embedded_port = embedded.getsockname()[1] + explicit_port = explicit.getsockname()[1] + received = {} + + def accept_one(name, sock): + try: + conn, _ = sock.accept() + conn.settimeout(10) + received[name] = conn.recv(1) + conn.close() + except OSError as exc: + received[name + "_error"] = repr(exc) + finally: + sock.close() + + threads = [ + threading.Thread(target=accept_one, args=("embedded", embedded), daemon=True), + threading.Thread(target=accept_one, args=("explicit", explicit), daemon=True), + ] + for thread in threads: + thread.start() + try: + databricks.sql.connect( + server_hostname=f"127.0.0.1:{embedded_port}", + http_path=_P, + use_kernel=True, + access_token="dapi-xyz", + enable_telemetry=False, + _retry_stop_after_attempts_count=1, + _port=explicit_port, + ).close() + except NotSupportedError: + raise + except Exception: + pass # expected: nothing behind the listener completes TLS + for thread in threads: + thread.join(timeout=70) + assert received.get("embedded") == b"\x16", received + assert "explicit" not in received, received + assert "explicit_error" in received, received