Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
db9a0fe
feat(kernel): honor _port and _connection_uri on use_kernel connections
cathleeny Nov 19, 2026
d98ca45
fix(kernel): type _kernel_host_and_path http_path as str
cathleeny Nov 19, 2026
5bb846e
fix(kernel): match main for default host resolution and PAT OAuth guard
cathleeny Nov 19, 2026
6a78cef
fix(kernel): black formatting and OAuth guard follows the auth bridge
cathleeny Nov 19, 2026
8f96c0b
fix(kernel): keep credentials and resolved host details out of error …
cathleeny Nov 19, 2026
6250c28
fix(kernel): sanitize connection-URI parse errors and wrap long messages
cathleeny Nov 19, 2026
f27c165
fix(kernel): drop the whole authority from errors when credentials ma…
cathleeny Nov 19, 2026
c90459f
Embedded host port wins over a differing _port on the kernel path
cathleeny Nov 19, 2026
bc7c09e
Reject a path, query or fragment host combined with _port; document k…
cathleeny Nov 19, 2026
bdeef64
kernel: parse host:port with urllib and check the JWT issuer origin
cathleeny Nov 20, 2026
f242c0f
kernel: skip ip_address for host names on the host:port path
cathleeny Nov 20, 2026
5082c7e
kernel: drop bare IPv6 support on the host:port path
cathleeny Nov 20, 2026
0de7c86
fix(kernel): narrow access_token before the foreign-JWT check
cathleeny Nov 20, 2026
a6936af
fix(kernel): don't echo a non-http(s) prefix in _connection_uri errors
cathleeny Nov 20, 2026
973b4e2
fix(kernel): guard the URI origin when identity_federation_client_id …
cathleeny Nov 20, 2026
81c1cff
fix(kernel): pass the host through unchanged for _port=443
cathleeny Nov 23, 2026
233f2b5
fix(kernel): report an uncomparable server_hostname as an OAuth origi…
cathleeny Nov 23, 2026
12ed5dc
refactor(kernel): let the kernel apply _port
cathleeny Nov 25, 2026
6272ae0
Merge origin/main (4.10.0) into feat/kernel-honor-port-uri-parity
cathleeny Nov 25, 2026
01999fa
fix(kernel): guard a JWT that is foreign to the _connection_uri host
cathleeny Nov 25, 2026
1453b26
fix(kernel): reject a _connection_uri with an empty port
cathleeny Nov 25, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -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)
Expand Down
7 changes: 3 additions & 4 deletions CONNECTION_PARAMETERS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.) |

Expand Down Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion KERNEL_REV
Original file line number Diff line number Diff line change
@@ -1 +1 @@
5c3a909771f749174567af074bfe18c24a335f5c
22ae6ec250837b38d0e3dc720310d4dcfb81fa98
26 changes: 23 additions & 3 deletions src/databricks/sql/backend/kernel/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"):

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Low — The dependency floor is still ^1.5.0, so a released install without the port kwarg raises NotSupportedError for a non-default _port. The failure is explicit, not silent. Once the kernel release with #505 is published, raise the floor and update the lockfile.

🔀 Found by GPT-6.1 Sol · confirmed by the judge

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.
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -488,6 +506,7 @@ def open_session(
geospatial_kwargs = _kernel_geospatial_kwargs(
self._enable_geospatial_support
)
port_kwargs = _kernel_port_kwargs(self._port)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟠 High — The dependency floor stays at ^1.5.0 although the feature needs a kernel release containing kernel#505. The driver raises a clear NotSupportedError on older wheels, but the published-wheel realkernel CI tier cannot pass until the floor and lockfile move. Bump the floor and lockfile once that kernel is released.

🔀 Found by GPT-6.1 Sol · confirmed by the judge

max_connections_kwargs: Dict[str, Any] = {}
if _kernel_session_accepts_kwarg("max_connections"):
max_connections_kwargs["max_connections"] = self._max_connections
Expand Down Expand Up @@ -536,6 +555,7 @@ def open_session(
**retry_kwargs,
**telemetry_kwargs,
**geospatial_kwargs,
**port_kwargs,
**max_connections_kwargs,
**http_headers_kwargs,
)
Expand Down
9 changes: 9 additions & 0 deletions src/databricks/sql/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
205 changes: 203 additions & 2 deletions src/databricks/sql/session.py
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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("://")
Comment thread
cathleeny marked this conversation as resolved.
Resolved
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 = "<redacted>"
# 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}<redacted>"
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}<redacted>"
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:
Comment thread
cathleeny marked this conversation as resolved.
Resolved
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
Comment thread
oss-reviewer-bot[bot] marked this conversation as resolved.
Resolved
Comment thread
oss-reviewer-bot[bot] marked this conversation as resolved.
Resolved
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 = (
Comment thread
cathleeny marked this conversation as resolved.
Resolved
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,
Expand Down Expand Up @@ -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,
Comment thread
oss-reviewer-bot[bot] marked this conversation as resolved.
Resolved
http_path=kernel_http_path,
port=kernel_port,
http_headers=all_headers,
auth_provider=auth_provider,
ssl_options=self.ssl_options,
Expand Down
Loading
Loading