Skip to content

Commit b0e2329

Browse files
cathleenyIsaac
andcommitted
refactor(kernel): drop the OAuth origin guard and trim _connection_uri handling
Remove the OAuth origin check for `_connection_uri` (and its JWT issuer, server-origin and redaction helpers). `_connection_uri` now only splits into host and path, rejecting a non-http(s) scheme, a missing host, or credentials in the URI; the kernel validates the rest. The related tests go too. KERNEL_REV moves to the kernel PR head (7e76a60). Signed-off-by: Cathleen Yan <58714163+cathleeny@users.noreply.github.com> Co-authored-by: Isaac <no-reply@databricks.com>
1 parent bad2b25 commit b0e2329

6 files changed

Lines changed: 20 additions & 409 deletions

File tree

‎CHANGELOG.md‎

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

33
# Unreleased
4-
- Honor `_port` and `_connection_uri` on kernel connections (`use_kernel=True`), as Thrift does; with OAuth, a `_connection_uri` on a different host than `server_hostname` raises `ValueError`. Requires a databricks-sql-kernel release that includes databricks/databricks-sql-kernel#505.
4+
- 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.
55
- 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.
66

77
# 4.10.0 (2026-11-24)

‎CONNECTION_PARAMETERS.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -74,7 +74,7 @@ to change without notice.
7474
| `server_hostname` | `str` | ✅ | ✅ | — (required) | Workspace hostname, e.g. `dbc-12345.cloud.databricks.com`. |
7575
| `http_path` | `str` | ✅ | ✅ | — (required) | Thrift accepts a SQL-warehouse path **or** an all-purpose-cluster path; Kernel requires a warehouse/endpoint path. |
7676
| `_port` | `int` | ✅ | ✅ | `443` | TCP port (advanced). On Kernel it is passed to the kernel as is, which validates and applies it: a port other than 443 makes the connection use `host:port`; `0`, unset and `443` change nothing; a non-default port embedded in `server_hostname` wins over a differing `_port` (with a warning). An IPv6 host needs brackets (`[::1]`). An invalid port raises `ValueError`; a host that can't take the port raises `ProgrammingError`, and the error never repeats the host. Needs a databricks-sql-kernel release that includes databricks-sql-kernel#505. |
77-
| `_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`. |
77+
| `_connection_uri` | `str` | ✅ | ✅ | `None` | Overrides `server_hostname`, `_port` and `http_path` on both, and wins over `_port`. On Kernel, OAuth also uses the URI's host:port (Thrift keeps OAuth on `server_hostname`). Credentials in the URI are rejected. |
7878
| `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. |
7979
| `user_agent_entry`| `str` | ✅ | ✅ | `None` | Custom tag folded into the composed `User-Agent` on both. (`_user_agent_entry` is a deprecated alias that warns.) |
8080

‎KERNEL_REV‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
403ef247a71c3e49297d7cb7fc97211db942d200
1+
7e76a603fd4e3ce74e90e6c578e86bc75ac025eb

‎src/databricks/sql/client.py‎

Lines changed: 3 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -194,14 +194,9 @@ def __init__(
194194
Thrift/SEA paths, where an explicit ``True`` can still
195195
be suppressed by the feature flag.
196196
197-
Kernel overrides: _port sends the connection to that port
198-
(the default 443 adds nothing; a falsy _port means the default). A port
199-
embedded in server_hostname wins over a differing _port, with a warning.
200-
_connection_uri (https://host[:port]/path?query)
201-
sets host, port, path and query, as on Thrift, and wins over _port.
202-
With OAuth, _connection_uri must have the same origin as
203-
server_hostname. With OAuth and a non-default _port, the token
204-
exchange goes to the same host:port, unlike Thrift.
197+
Kernel overrides: _port is passed to the kernel, which applies it to
198+
the host. _connection_uri (https://host[:port]/path?query) sets host,
199+
port, path and query, as on Thrift, and wins over _port.
205200
:param enable_geospatial_support: `bool`, optional (default is False)
206201
Kernel backend only. Controls the public representation of
207202
``GEOMETRY`` and ``GEOGRAPHY`` result values. ``True`` returns

‎src/databricks/sql/session.py‎

Lines changed: 11 additions & 157 deletions
Original file line numberDiff line numberDiff line change
@@ -6,10 +6,8 @@
66

77
from databricks.sql.types import SSLOptions
88
from databricks.sql.auth.auth import get_python_sql_connector_auth_provider
9-
from databricks.sql.auth.auth_utils import decode_token, is_same_host
109
from databricks.sql.auth.authenticators import AccessTokenAuthProvider
1110
from databricks.sql.auth.common import ClientContext
12-
from databricks.sql.common.url_utils import normalize_host_with_protocol
1311
from databricks.sql.exc import SessionAlreadyClosedError, DatabaseError, RequestError
1412
from databricks.sql import __version__
1513
from databricks.sql import USER_AGENT_NAME
@@ -50,167 +48,24 @@ def __getattr__(name: str) -> Any:
5048
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
5149

5250

53-
_OAUTH_AUTH_TYPES = ("databricks-oauth", "azure-oauth", "azure-sp-m2m")
54-
55-
56-
def _redact(value: str) -> str:
57-
"""Keep only scheme and host[:port] of a URI or host string for an error message.
58-
59-
Userinfo, path, query and fragment can carry credentials, so they never reach an
60-
exception text or log line.
61-
"""
62-
scheme, sep, rest = value.partition("://")
63-
if not sep:
64-
scheme, rest = "", value
65-
elif scheme.lower() not in ("http", "https"):
66-
# Not a real scheme: in a scheme-less URI such as "h.io/x?token=t&next=https://e",
67-
# everything before "://" is path and query, so none of it is shown.
68-
scheme = "<redacted>"
69-
# A "/" or "?" can sit inside a password, and "@" can sit in a path, so once any
70-
# userinfo marker is present the whole authority is dropped rather than guessed at.
71-
if "@" in value or "%40" in value.lower():
72-
return f"{scheme}{sep}<redacted>"
73-
try:
74-
host = urlsplit(f"//{rest}").netloc
75-
except ValueError:
76-
# urlsplit refuses some hosts (bad IPv6, NFKC-unsafe text); show none of them.
77-
return f"{scheme}{sep}<redacted>"
78-
return f"{scheme}{sep}{host}"
79-
80-
81-
def _uri_host_and_path(uri: str) -> Tuple[str, str]:
82-
"""Split a ``_connection_uri`` into the kernel host (scheme, authority) and path."""
83-
try:
84-
parts = urlsplit(uri)
85-
except ValueError:
86-
parts = None
87-
if parts is None:
88-
# Raised outside the except block so no chained exception carries urlsplit's netloc.
89-
raise ValueError(
90-
f"Invalid _connection_uri {_redact(uri)!r}: could not be parsed"
91-
)
92-
try:
93-
port = parts.port
94-
except ValueError:
95-
port = 0
96-
if (
97-
parts.scheme not in ("http", "https")
98-
or not parts.hostname
99-
or "@" in parts.netloc
100-
or port == 0
101-
# urlsplit reads "h.io:" as no port; an empty port is malformed.
102-
or parts.netloc.endswith(":")
103-
or parts.path in ("", "/")
104-
):
105-
raise ValueError(
106-
f"Invalid _connection_uri {_redact(uri)!r}: expected http(s)://host[:port]/path with a "
107-
"warehouse path and no credentials"
108-
)
109-
return f"{parts.scheme}://{parts.netloc}", parts.path + (
110-
f"?{parts.query}" if parts.query else ""
111-
)
112-
113-
11451
def _kernel_endpoint(
11552
server_hostname: str, http_path: str, kwargs: dict
11653
) -> Tuple[str, str, Any]:
11754
"""Resolve the kernel ``(host, http_path, port)``. ``_connection_uri`` gives the host
118-
(with any port in it) and the path, and wins over ``_port``, so no port is passed.
119-
Otherwise ``server_hostname``, ``http_path`` and ``_port`` pass through as is: the
120-
kernel validates the port and applies it to the host.
55+
(with any port in it) and the path, and wins over ``_port``. Otherwise the arguments
56+
pass through as is; the kernel validates the port and applies it to the host.
12157
"""
122-
if kwargs.get("_connection_uri"):
123-
host, path = _uri_host_and_path(kwargs["_connection_uri"])
124-
return host, path, None
125-
return server_hostname, http_path, kwargs.get("_port")
126-
127-
128-
def _is_foreign_jwt(access_token: str, server_hostname: str) -> bool:
129-
"""True when ``access_token`` is a JWT whose issuer is not ``server_hostname``. Thrift
130-
token-exchanges such a token at server_hostname (TokenFederationProvider); the kernel
131-
wraps every provider with the connection host, so it exchanges at the connection host.
132-
"""
133-
claims = decode_token(access_token)
134-
if not claims:
135-
return False
136-
issuer = claims.get("iss", "")
137-
return not is_same_host(issuer, normalize_host_with_protocol(server_hostname))
138-
139-
140-
def _server_origin(server_hostname: str) -> Tuple[str, Optional[int]]:
141-
"""Host and port of ``server_hostname`` for the OAuth origin check. A value with no
142-
comparable origin (credentials, a bare IPv6 literal, an empty or out-of-range port)
143-
returns ``("", None)``, so it never matches and is reported as an origin mismatch.
144-
"""
145-
netloc = server_hostname.rstrip("/").rpartition("://")[2]
146-
# urlsplit reads a trailing ':' as an empty port, which has no origin.
147-
if netloc.endswith(":"):
148-
return "", None
149-
try:
150-
parts = urlsplit(f"//{netloc}")
151-
port = parts.port
152-
except ValueError:
153-
return "", None
154-
if port == 0 or ("@" in parts.netloc and parts.password is not None):
155-
return "", None
156-
return parts.hostname or "", port
157-
158-
159-
def _check_oauth_origin(server_hostname: str, kernel_host: str, kwargs: dict) -> None:
160-
"""AC-P4: with OAuth, a ``_connection_uri`` origin must equal ``https://server_hostname``.
161-
Thrift keeps OAuth on server_hostname; the kernel uses one host for API and token calls.
162-
URI-only use (empty server_hostname) has no server origin to compare and is not checked.
163-
"""
164-
if not (kwargs.get("_connection_uri") and server_hostname):
165-
return
166-
access_token = kwargs.get("access_token")
167-
# A JWT from a foreign issuer is exchanged, so it is an OAuth credential even though
168-
# it arrives as access_token. Thrift judges the issuer against server_hostname and the
169-
# kernel against its connection host, so a token foreign to either is exchanged.
170-
foreign_jwt = bool(
171-
access_token
172-
and (
173-
_is_foreign_jwt(access_token, server_hostname)
174-
or _is_foreign_jwt(access_token, kernel_host)
175-
)
176-
)
177-
# identity_federation_client_id makes the kernel exchange the access_token at the
178-
# connection host (mandatory workload-identity exchange), so it is exchanged like a
179-
# foreign JWT, whatever the token's issuer.
180-
federated = bool(access_token and kwargs.get("identity_federation_client_id"))
181-
exchanged = foreign_jwt or federated
182-
oauth = (
183-
kwargs.get("auth_type") in _OAUTH_AUTH_TYPES
184-
or kwargs.get("oauth_jwt_key_file")
185-
or (kwargs.get("oauth_client_id") and kwargs.get("oauth_client_secret"))
186-
or exchanged
187-
)
188-
# The kernel auth bridge routes an access_token with no JWT or client-secret
189-
# M2M credentials to PAT, even for auth_type='databricks-oauth'; azure-sp-m2m
190-
# is resolved before that branch and stays OAuth. A custom credentials_provider
191-
# is rejected by the bridge, so it is not an OAuth origin here.
192-
routed_to_pat = (
193-
bool(access_token)
194-
and not exchanged
195-
and kwargs.get("auth_type") != "azure-sp-m2m"
196-
and not kwargs.get("oauth_jwt_key_file")
197-
and not (kwargs.get("oauth_client_id") and kwargs.get("oauth_client_secret"))
198-
)
199-
if routed_to_pat or not oauth:
200-
return
201-
server_host, port = _server_origin(server_hostname)
202-
uri = urlsplit(kernel_host)
203-
if (uri.scheme, uri.hostname or "", uri.port or 443) != (
204-
"https",
205-
server_host,
206-
port or 443,
207-
):
58+
uri = kwargs.get("_connection_uri")
59+
if not uri:
60+
return server_hostname, http_path, kwargs.get("_port")
61+
parts = urlsplit(uri)
62+
# Credentials in the URI would reach the transport, so they are refused here.
63+
if parts.scheme not in ("http", "https") or not parts.netloc or "@" in parts.netloc:
20864
raise ValueError(
209-
f"OAuth requires the _connection_uri origin to match "
210-
f"https://{_redact(server_hostname)}; "
211-
f"the kernel would send the credentials to {_redact(kernel_host)}. "
212-
"Use a PAT or match the origin."
65+
"Invalid _connection_uri: expected http(s)://host[:port]/path with no credentials"
21366
)
67+
path = parts.path + (f"?{parts.query}" if parts.query else "")
68+
return f"{parts.scheme}://{parts.netloc}", path, None
21469

21570

21671
class Session:
@@ -492,7 +347,6 @@ def _create_backend(
492347
kernel_host, kernel_http_path, kernel_port = _kernel_endpoint(
493348
server_hostname, http_path, kwargs
494349
)
495-
_check_oauth_origin(server_hostname, kernel_host, kwargs)
496350
if kernel_http_path != http_path:
497351
# A _connection_uri can point at another workspace: re-derive the
498352
# SPOG org-id header from the resolved path (a caller header still wins).

0 commit comments

Comments
 (0)