Skip to content

Commit db9a0fe

Browse files
cathleenyIsaac
andcommitted
feat(kernel): honor _port and _connection_uri on use_kernel connections
The kernel backend (use_kernel=True) ignored the Thrift-style _port and _connection_uri overrides. Resolve both connector-side onto the kernel's single host and http_path, with the Thrift rules: - _port (1..65535; 0 or None mean the default) folds into server_hostname as host:port. The default 443 adds nothing, IPv6 literals are bracketed, and an embedded port equal to _port is accepted. An empty server_hostname with _port raises ValueError. - _connection_uri (http(s)://host[:port]/path?query) replaces host, port, path and query, and wins over _port. Scheme-less, non-http(s), path-less and credential-bearing URIs raise ValueError. URI-only use works. - With OAuth (U2M, Azure service principal, JWT key file, or M2M client id and secret), a _connection_uri whose origin differs from https://server_hostname raises before a kernel session opens. PAT is not affected. A non-default _port with OAuth is not guarded: the token exchange goes to the same host:port, which is documented. - The SPOG x-databricks-org-id header follows the resolved path. Tests cover the resolver tables, the OAuth origin guard, the SPOG re-derivation, and a real-wheel loopback dial proving the kernel reaches the requested port over TLS for _port and for _connection_uri. Co-authored-by: Isaac <no-reply@databricks.com> Signed-off-by: Cathleen Yan <58714163+cathleeny@users.noreply.github.com>
1 parent b099dd6 commit db9a0fe

4 files changed

Lines changed: 419 additions & 2 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
# Release History
22

33
# Unreleased
4+
- Honor `_port` and `_connection_uri` on kernel connections (`use_kernel=True`), as Thrift does. `_port` sends the connection to that port (default 443 adds nothing); `_connection_uri` (`http(s)://host[:port]/path?query`) sets host, port, path and query and wins over `_port`; URI-only connections work. Invalid ports, conflicting ports, an empty `server_hostname` with `_port`, and URIs without a scheme or path 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).
45
- Honor `max_download_threads` on kernel connections, with a default download window of 16 and explicit chunk-setting overrides. Invalid values raise `ValueError` when connecting with `use_kernel=True`.
56
- Fix the kernel backend ignoring `use_cloud_fetch=False`, so complete results can be fetched without cloud-storage downloads.
67
- Fix inline parameters (`use_inline_params=True`) so a sequence directly after `IN` renders as a list again: `x IN %(ids)s` renders as `x IN (1,2,3)` instead of `x IN ARRAY(1,2,3)`, which Spark rejects. Inside the list, tuples render as rows for a multi-column `IN`, and a `set` or `frozenset` is accepted again. Sequences anywhere else still render as `ARRAY(...)` ([#629](https://github.com/databricks/databricks-sql-python/issues/629))

‎src/databricks/sql/client.py‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -193,6 +193,13 @@ def __init__(
193193
decision. This is an intentional divergence from the
194194
Thrift/SEA paths, where an explicit ``True`` can still
195195
be suppressed by the feature flag.
196+
197+
Kernel overrides: _port sends the connection to that port
198+
(the default 443 adds nothing). _connection_uri (https://host[:port]/path?query)
199+
sets host, port, path and query, as on Thrift, and wins over _port.
200+
With OAuth, _connection_uri must have the same origin as
201+
server_hostname. With OAuth and a non-default _port, the token
202+
exchange goes to the same host:port, unlike Thrift.
196203
:param enable_geospatial_support: `bool`, optional (default is False)
197204
Kernel backend only. Controls the public representation of
198205
``GEOMETRY`` and ``GEOGRAPHY`` result values. ``True`` returns

‎src/databricks/sql/session.py‎

Lines changed: 137 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import logging
22
import re
33
from functools import cached_property
4+
from urllib.parse import urlsplit
45
from typing import Dict, Tuple, List, Optional, Any, Type, TYPE_CHECKING
56

67
from databricks.sql.types import SSLOptions
@@ -47,6 +48,126 @@ def __getattr__(name: str) -> Any:
4748
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
4849

4950

51+
_OAUTH_AUTH_TYPES = ("databricks-oauth", "azure-oauth", "azure-sp-m2m")
52+
_HOSTPORT_RE = re.compile(r"(\[[^\]]*\]|(?!\[)[^:]*)(?::([0-9]+))?")
53+
54+
55+
def _port_or_none(value: Any) -> Optional[int]:
56+
"""Validate ``_port``. ``None`` and ``0`` mean the default (Thrift: ``port or 443``)."""
57+
if value is None:
58+
return None
59+
text = (
60+
str(value).strip()
61+
if isinstance(value, (int, str)) and not isinstance(value, bool)
62+
else ""
63+
)
64+
if not re.fullmatch(r"[0-9]+", text) or not int(text) <= 65535:
65+
raise ValueError(
66+
f"Invalid _port {value!r}: expected an integer between 1 and 65535"
67+
)
68+
return int(text) or None
69+
70+
71+
def _split_host(host: str) -> Tuple[str, str, Optional[int]]:
72+
"""Split ``[scheme://]name[:port]`` into ``(prefix, name, port)``; ``name`` keeps IPv6 brackets."""
73+
prefix, sep, text = host.rstrip("/").rpartition("://")
74+
prefix += sep
75+
match = _HOSTPORT_RE.fullmatch(text)
76+
if match is None:
77+
if text.startswith("[") or text.count(":") == 1:
78+
raise ValueError(
79+
f"Invalid server_hostname {host!r}: malformed IPv6 literal or port"
80+
)
81+
return prefix, text, None # an unbracketed IPv6 literal such as ::1 has no port
82+
name, port_text = match.group(1), match.group(2)
83+
if port_text is None:
84+
return prefix, name, None
85+
if not 1 <= int(port_text) <= 65535:
86+
raise ValueError(
87+
f"Invalid server_hostname {host!r}: port {port_text} is out of range"
88+
)
89+
return prefix, name, int(port_text)
90+
91+
92+
def _uri_host_and_path(uri: str) -> Tuple[str, str]:
93+
"""Split a ``_connection_uri`` into the kernel host (scheme and authority) and path (with query)."""
94+
parts = urlsplit(uri)
95+
try:
96+
port = parts.port
97+
except ValueError:
98+
port = 0
99+
if (
100+
parts.scheme not in ("http", "https")
101+
or not parts.hostname
102+
or "@" in parts.netloc
103+
or port == 0
104+
or parts.path in ("", "/")
105+
):
106+
raise ValueError(
107+
f"Invalid _connection_uri {uri!r}: expected http(s)://host[:port]/path with a "
108+
"warehouse path and no credentials"
109+
)
110+
return f"{parts.scheme}://{parts.netloc}", parts.path + (
111+
f"?{parts.query}" if parts.query else ""
112+
)
113+
114+
115+
def _kernel_host_and_path(
116+
server_hostname: str, http_path: Optional[str], kwargs: dict
117+
) -> Tuple[str, Optional[str]]:
118+
"""Resolve the kernel ``(host, http_path)``. ``_connection_uri`` replaces both and wins over
119+
``_port``; ``_port`` folds into the host as ``host:port`` (default 443 adds nothing).
120+
"""
121+
if kwargs.get("_connection_uri"):
122+
return _uri_host_and_path(kwargs["_connection_uri"])
123+
port = _port_or_none(kwargs.get("_port"))
124+
prefix, name, embedded = _split_host(server_hostname)
125+
if port is None:
126+
return server_hostname, http_path
127+
if not server_hostname:
128+
raise ValueError(
129+
"server_hostname is required on use_kernel=True when _port is set "
130+
"(or pass _connection_uri, which carries its own host)"
131+
)
132+
if embedded is not None:
133+
if embedded != port:
134+
raise ValueError(
135+
f"Conflicting ports: server_hostname {server_hostname!r} carries {embedded} but _port={port}"
136+
)
137+
return server_hostname, http_path
138+
if port == 443:
139+
return server_hostname, http_path
140+
if ":" in name and not name.startswith("["):
141+
name = f"[{name}]"
142+
return f"{prefix}{name}:{port}", http_path
143+
144+
145+
def _check_oauth_origin(server_hostname: str, kernel_host: str, kwargs: dict) -> None:
146+
"""AC-P4: with OAuth, a ``_connection_uri`` origin must equal ``https://server_hostname``.
147+
Thrift keeps OAuth on server_hostname; the kernel uses one host for API and token calls.
148+
URI-only use (empty server_hostname) has no server origin to compare and is not checked.
149+
"""
150+
oauth = (
151+
kwargs.get("auth_type") in _OAUTH_AUTH_TYPES
152+
or kwargs.get("oauth_jwt_key_file")
153+
or (kwargs.get("oauth_client_id") and kwargs.get("oauth_client_secret"))
154+
or kwargs.get("credentials_provider") is not None
155+
)
156+
if not (kwargs.get("_connection_uri") and server_hostname and oauth):
157+
return
158+
_, name, port = _split_host(server_hostname)
159+
uri = urlsplit(kernel_host)
160+
if (uri.scheme, uri.hostname or "", uri.port or 443) != (
161+
"https",
162+
name.strip("[]").lower(),
163+
port or 443,
164+
):
165+
raise ValueError(
166+
f"OAuth requires the _connection_uri origin to match https://{server_hostname}; "
167+
f"the kernel would send the credentials to {kernel_host}. Use a PAT or match the origin."
168+
)
169+
170+
50171
class Session:
51172
def __init__(
52173
self,
@@ -323,9 +444,23 @@ def _create_backend(
323444
"_telemetry_circuit_breaker_enabled"
324445
),
325446
}
447+
kernel_host, kernel_http_path = _kernel_host_and_path(
448+
server_hostname, http_path, kwargs
449+
)
450+
_check_oauth_origin(server_hostname, kernel_host, kwargs)
451+
if kernel_http_path != http_path:
452+
# A _connection_uri can point at another workspace: re-derive the
453+
# SPOG org-id header from the resolved path (a caller header still wins).
454+
base_headers = [
455+
h for h in all_headers if h not in self._spog_headers.items()
456+
]
457+
self._spog_headers = self._extract_spog_headers(
458+
kernel_http_path, base_headers
459+
)
460+
all_headers = base_headers + list(self._spog_headers.items())
326461
return KernelDatabricksClient(
327-
server_hostname=server_hostname,
328-
http_path=http_path,
462+
server_hostname=kernel_host,
463+
http_path=kernel_http_path,
329464
http_headers=all_headers,
330465
auth_provider=auth_provider,
331466
ssl_options=self.ssl_options,

0 commit comments

Comments
 (0)