Skip to content

Commit 97277bd

Browse files
cathleenyIsaac
andcommitted
Merge origin/main into the Negotiate proxy branch
Brings in credentials_provider on kernel connections and the SOCKS docs. The only conflict was tests/unit/test_kernel_client.py, where both sides added tests at the same place; both are kept. KERNEL_REV follows main. Signed-off-by: Cathleen Yan <58714163+cathleeny@users.noreply.github.com> Co-authored-by: Isaac <no-reply@databricks.com>
2 parents 03d95a5 + 31b3ba4 commit 97277bd

10 files changed

Lines changed: 409 additions & 75 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+
- Support `credentials_provider` on kernel connections (`use_kernel=True`), with the same header refresh and token federation as Thrift.
45
- 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.
56
- 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.
67
- 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.

‎CONNECTION_PARAMETERS.md‎

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -93,7 +93,7 @@ to change without notice.
9393
| `oauth_jwt_algorithm` (OAuth M2M, JWT private key) | `str` | ❌ | ✅ | `RS256` | **Kernel-only.** JWT signing algorithm (`RS256`/`384`/`512`, `PS256`/`384`/`512`, `ES256`, `ES384`). |
9494
| `token_url` (OAuth M2M) | `str` | ❌ | ✅ | `None` ⇒ OIDC discovery | **Kernel-only.** OAuth IdP token endpoint override. Required for JWT M2M against an external-IdP-backed workspace (e.g. Entra ID for Azure Databricks), since Databricks-native OIDC does not advertise the `private_key_jwt` method. Applies to shared-secret M2M too. |
9595
| `oauth_scopes` | `List[str]` | ❌ | ✅ | `["sql","offline_access"]` for U2M | **Thrift ignores custom scopes** — it always uses the built-in scope set. Kernel honors custom scopes for U2M and M2M; an omitted M2M value uses the kernel's own default. |
96-
| `credentials_provider` | `CredentialsProvider`| ✅ | ❌ | `None` | Custom external credentials provider. **Rejected on the kernel path** (`NotSupportedError`) — it is an opaque token source, so the kernel cannot own the token lifecycle; use `oauth_client_id` + `oauth_client_secret` for M2M, or the Thrift backend. |
96+
| `credentials_provider` | `CredentialsProvider`| ✅ | ✅ | `None` | Custom external credentials provider. Takes precedence over `access_token` and `auth_type` on both backends. On Kernel the connector's provider chain (header caching, token federation with `identity_federation_client_id`, exchange fallback) runs as on Thrift and supplies the headers for every kernel request; combining it with `oauth_client_secret` or `oauth_jwt_key_file` raises `NotSupportedError`. |
9797
| `identity_federation_client_id` | `str` | ✅ | ✅ | `None` | Workload identity / token-federation client id (kernel support added in #910). |
9898
| `experimental_oauth_persistence` | `OAuthPersistence` | ✅ | ❌ | `None` | **Thrift-only.** The kernel owns its own token lifecycle and does not accept a persistence store. |
9999
| `oauth_token_cache_enabled` | `bool \| None` | ❌ | ✅ | `None` | **Kernel-only, U2M-only.** Controls whether the kernel persists OAuth U2M refresh tokens to disk (AES-256 encrypted, in the OS config dir — `~/Library/Application Support/databricks-sql-kernel/oauth/` on macOS, `~/.config/databricks-sql-kernel/oauth/` on Linux; requires databricks-sql-kernel PR #283). **Disabled by default:** when unset (None) or False, the connector disables on-disk persistence (tokens in-memory only, matching Thrift); True enables the cache. Omitting it does **not** inherit the kernel's enabled-by-default. Distinct from `experimental_oauth_persistence` — this toggles the kernel's built-in encrypted storage, not a pluggable callback. |
@@ -128,6 +128,26 @@ to change without notice.
128128
| `_retry_max_redirects` | `int` | ✅ | ❌ | `None` | Max HTTP redirects to follow (must be ≤ `_retry_stop_after_attempts_count`). Thrift-only. |
129129
| `_enable_v3_retries` | `bool` | ✅ | ❌ | `True` | Use the urllib3-based v3 retry policy; `False` selects the deprecated legacy policy. Thrift-only. |
130130

131+
### SOCKS proxies from environment variables
132+
133+
The connector has no proxy URL parameter; both backends read proxies from the
134+
environment. The backends differ for SOCKS proxies:
135+
136+
- **Kernel** (with a `databricks-sql-kernel` release that supports SOCKS) supports
137+
only the `socks4://`, `socks4a://`, `socks5://` and `socks5h://` SOCKS schemes, in
138+
`HTTPS_PROXY`, or in `ALL_PROXY` when `HTTPS_PROXY` is unset, for all kernel
139+
traffic: queries, CloudFetch downloads and OAuth. `NO_PROXY` hosts connect
140+
directly. `http://` and `https://` proxy URLs work as before. A value with an
141+
unsupported scheme, such as bare `socks://`, is ignored: the kernel then uses
142+
`ALL_PROXY` or connects directly. `socks5` and `socks4` resolve
143+
the target host locally; `socks5h` and `socks4a` let the proxy resolve it. SOCKS5
144+
credentials go in the URL userinfo (`socks5h://user:password@proxy:1080`;
145+
percent-encode reserved characters). SOCKS4 has no password, and the user ID is
146+
not sent. If a proxy with a supported scheme is unreachable or rejects the
147+
credentials, the connection fails; it never falls back to a direct connection.
148+
- **Thrift** has no SOCKS support. A SOCKS `HTTPS_PROXY` fails with urllib3's
149+
`ProxySchemeUnknown`, and `ALL_PROXY` is ignored, so Thrift connects directly.
150+
131151
## TLS / SSL
132152

133153
> TLS options are assembled into a single `SSLOptions` object in `session.py`
@@ -223,6 +243,8 @@ are forwarded when supported by the installed kernel binding.
223243
2. Custom `oauth_scopes`.
224244
3. Kernel U2M encrypted token storage (`oauth_token_cache_enabled`).
225245
4. Telemetry flush interval (`telemetry_flush_interval_ms`).
246+
5. SOCKS proxies from `HTTPS_PROXY` / `ALL_PROXY` (see
247+
[SOCKS proxies from environment variables](#socks-proxies-from-environment-variables)).
226248

227249
### Behavioral divergences to watch
228250

‎KERNEL_REV‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
3b691d2a2c235ef847d61b308c31604979830994
1+
6d6c1e4eb70e3d5bebea75b76c5b19c459d9a467

‎src/databricks/sql/backend/kernel/auth_bridge.py‎

Lines changed: 80 additions & 51 deletions
Original file line numberDiff line numberDiff line change
@@ -51,13 +51,20 @@
5151
wins resolution. It selects mandatory SP-wide workload-identity token
5252
exchange in the kernel; omitting it preserves BYOT / account-wide behavior.
5353
54-
A user-supplied custom ``credentials_provider`` is **rejected** on the
55-
kernel path with ``NotSupportedError``: it's an opaque token source
56-
with no extractable raw credentials, so the kernel can't own the
57-
lifecycle. Such callers should pass ``oauth_client_id`` /
58-
``oauth_client_secret`` (M2M) instead. Anything else non-PAT also
59-
raises ``NotSupportedError`` so the failure surfaces at session-open
60-
with a clear message rather than deep inside the kernel.
54+
- **Custom ``credentials_provider``** — takes precedence over
55+
``access_token`` and ``auth_type``, as on Thrift. The connector builds
56+
the same provider chain Thrift uses
57+
(``TokenFederationProvider(ExternalAuthProvider)``) and passes it to
58+
the kernel's ``auth_type='external'`` as a
59+
``header_provider`` callable, which the kernel calls on every
60+
authenticated request. Header caching, token federation (including
61+
``identity_federation_client_id``) and exchange fallback therefore run
62+
in the connector exactly as on Thrift; the kernel does not federate
63+
``external`` itself.
64+
65+
Anything else non-PAT raises ``NotSupportedError`` so the failure
66+
surfaces at session-open with a clear message rather than deep inside
67+
the kernel.
6168
6269
The M2M / U2M decisions are driven by the *raw* connect() kwargs
6370
(``auth_options``), not a built ``AuthProvider``. On the kernel path
@@ -72,7 +79,8 @@
7279

7380
import logging
7481
import re
75-
from typing import Any, Dict, Optional
82+
import threading
83+
from typing import Any, Callable, Dict, Optional
7684

7785
from databricks.sql.auth.auth import (
7886
PYSQL_OAUTH_CLIENT_ID,
@@ -152,6 +160,25 @@ def _extract_bearer_token(auth_provider: Optional[AuthProvider]) -> Optional[str
152160
return token
153161

154162

163+
def _header_provider(auth_provider: AuthProvider) -> Callable[[], Dict[str, str]]:
164+
"""Wrap a connector ``AuthProvider`` as the kernel's ``header_provider``.
165+
166+
The kernel calls it on every authenticated request, possibly from
167+
several kernel threads at once, so calls are serialized: the
168+
provider's own cache then decides when the user's header factory
169+
(and any federation exchange) runs, as it does on Thrift.
170+
"""
171+
lock = threading.Lock()
172+
173+
def header_provider() -> Dict[str, str]:
174+
headers: Dict[str, str] = {}
175+
with lock:
176+
auth_provider.add_headers(headers)
177+
return headers
178+
179+
return header_provider
180+
181+
155182
def kernel_auth_kwargs(
156183
auth_provider: Optional[AuthProvider],
157184
auth_options: Optional[Dict[str, Any]] = None,
@@ -198,8 +225,11 @@ def kernel_auth_kwargs(
198225
(PECOBLR-4039/4040). ``azure-oauth`` resolves identically: the kernel's
199226
workspace-federated flow serves Azure workspaces too (PECOBLR-4120).
200227
Unlike the Thrift path, a caller-supplied ``oauth_scopes`` is honored here.
201-
5. **Custom credentials_provider** → ``NotSupportedError`` (opaque
202-
token source; no raw creds for the kernel to own).
228+
5. **Custom credentials_provider** → ``auth_type='external'``. Checked
229+
first, before the Azure branch and steps 1-4, so it wins over
230+
``access_token`` and ``auth_type`` as on Thrift
231+
(``auth.get_auth_provider``); only the M2M ambiguity guards above
232+
take priority over it.
203233
6. Anything else → ``NotSupportedError``.
204234
205235
M2M is checked before PAT so that a workload passing both an
@@ -222,6 +252,35 @@ def kernel_auth_kwargs(
222252
# rather than sending a client secret.
223253
has_jwt_m2m = bool(jwt_key_file)
224254

255+
# Custom credentials_provider wins over access_token and every auth_type
256+
# (azure-sp-m2m included), as on Thrift (auth.get_auth_provider checks it
257+
# first). Paired with the kernel-only M2M kwargs it is ambiguous; that is
258+
# rejected here, before any flow (Azure included) is chosen.
259+
if opts.get("credentials_provider"):
260+
if client_secret:
261+
raise NotSupportedError(
262+
"Ambiguous auth on use_kernel=True: both a custom "
263+
"credentials_provider and oauth_client_secret were provided. "
264+
"Pass exactly one — oauth_client_id + oauth_client_secret for "
265+
"kernel-managed M2M, or credentials_provider alone."
266+
)
267+
if has_jwt_m2m:
268+
raise NotSupportedError(
269+
"Ambiguous auth on use_kernel=True: both a custom "
270+
"credentials_provider and oauth_jwt_key_file were provided. "
271+
"Pass exactly one — oauth_client_id + oauth_jwt_key_file for "
272+
"kernel-managed JWT private-key M2M, or credentials_provider alone."
273+
)
274+
if auth_provider is None:
275+
raise ProgrammingError(
276+
"credentials_provider was set but no auth provider was built "
277+
"for it; cannot route through the kernel's external auth path"
278+
)
279+
return {
280+
"auth_type": "external",
281+
"header_provider": _header_provider(auth_provider),
282+
}
283+
225284
# Azure Entra (Azure AD) auth types route to the kernel's GENERIC OAuth
226285
# flows with Azure values supplied as overrides — the kernel needs no
227286
# Azure-specific code. Handled up front, keyed on the explicit auth_type,
@@ -256,12 +315,13 @@ def kernel_auth_kwargs(
256315
#
257316
# This branch returns BEFORE the ambiguity guards below, so an
258317
# azure-sp-m2m selector paired with a conflicting OAuth signal
259-
# (oauth_client_secret / oauth_jwt_key_file / credentials_provider) does not
260-
# fail loudly the way the other flows do. That is intentional: azure-sp-m2m
261-
# carries its credentials in the azure_* namespace, so there is no routing
262-
# collision, and an explicit azure-sp-m2m selector is unambiguous intent to
263-
# use the Azure SP flow. Any oauth_*/credentials_provider values are simply
264-
# ignored here rather than treated as ambiguous.
318+
# (oauth_client_secret / oauth_jwt_key_file) does not fail loudly the way
319+
# the other flows do. That is intentional: azure-sp-m2m carries its
320+
# credentials in the azure_* namespace, so there is no routing collision,
321+
# and an explicit azure-sp-m2m selector is unambiguous intent to use the
322+
# Azure SP flow. Any oauth_* values are simply ignored here rather than
323+
# treated as ambiguous. (A credentials_provider never reaches this branch:
324+
# it is resolved above and wins, as on Thrift.)
265325
if auth_type == "azure-sp-m2m":
266326
azure_client_id = opts.get("azure_client_id")
267327
azure_client_secret = opts.get("azure_client_secret")
@@ -274,14 +334,13 @@ def kernel_auth_kwargs(
274334
# conflicting OAuth signal is not a routing collision and does not fail
275335
# loudly the way the other flows do (see the routing note above). Still,
276336
# leave a breadcrumb: a caller who paired azure-sp-m2m with an
277-
# oauth_*/credentials_provider value likely misunderstood the routing,
278-
# and those values are silently ignored here.
337+
# oauth_* value likely misunderstood the routing, and those values are
338+
# silently ignored here.
279339
ignored_signals = [
280340
name
281341
for name in (
282342
"oauth_client_secret",
283343
"oauth_jwt_key_file",
284-
"credentials_provider",
285344
)
286345
if opts.get(name) is not None
287346
]
@@ -313,14 +372,6 @@ def kernel_auth_kwargs(
313372
return kwargs
314373

315374
# 0. Ambiguity guards — fail before any flow is chosen.
316-
if client_secret and opts.get("credentials_provider") is not None:
317-
raise NotSupportedError(
318-
"Ambiguous auth on use_kernel=True: both a custom "
319-
"credentials_provider and oauth_client_secret were provided. "
320-
"Pass exactly one — oauth_client_id + oauth_client_secret for "
321-
"kernel-managed M2M, or use the Thrift backend (default) for "
322-
"credentials_provider."
323-
)
324375
if client_secret and auth_type in ("databricks-oauth", "azure-oauth"):
325376
raise NotSupportedError(
326377
f"Ambiguous auth on use_kernel=True: auth_type={auth_type!r} selects "
@@ -335,14 +386,6 @@ def kernel_auth_kwargs(
335386
"M2M) were provided. Pass exactly one — a private key for "
336387
"JWT client-assertion M2M, or a client secret for shared-secret M2M."
337388
)
338-
if has_jwt_m2m and opts.get("credentials_provider") is not None:
339-
raise NotSupportedError(
340-
"Ambiguous auth on use_kernel=True: both a custom "
341-
"credentials_provider and oauth_jwt_key_file were provided. "
342-
"Pass exactly one — oauth_client_id + oauth_jwt_key_file for "
343-
"kernel-managed JWT private-key M2M, or use the Thrift backend "
344-
"(default) for credentials_provider."
345-
)
346389
if has_jwt_m2m and auth_type in ("databricks-oauth", "azure-oauth"):
347390
raise NotSupportedError(
348391
f"Ambiguous auth on use_kernel=True: auth_type={auth_type!r} selects "
@@ -473,20 +516,6 @@ def kernel_auth_kwargs(
473516
kwargs["identity_federation_client_id"] = federation_client_id
474517
return kwargs
475518

476-
# 5. Custom credentials_provider — the connector's primary M2M path
477-
# on Thrift/SEA, but unusable on the kernel: it's an opaque token
478-
# source with no extractable client_id/secret, so the kernel
479-
# can't own the token lifecycle. Point the caller at the raw
480-
# M2M kwargs instead.
481-
if opts.get("credentials_provider") is not None:
482-
raise NotSupportedError(
483-
"use_kernel=True does not support a custom credentials_provider. "
484-
"For OAuth machine-to-machine auth, pass oauth_client_id and "
485-
"oauth_client_secret so the kernel can manage the token lifecycle "
486-
"directly; or use the Thrift backend (default) with "
487-
"credentials_provider."
488-
)
489-
490519
# 6. Everything else (including no usable credentials at all —
491520
# ``auth_provider`` is None on the kernel path when no access
492521
# token was supplied and no OAuth kwargs resolved above).
@@ -497,8 +526,8 @@ def kernel_auth_kwargs(
497526
f"use_kernel=True requires PAT (access_token), OAuth M2M "
498527
f"(oauth_client_id + oauth_client_secret), OAuth M2M JWT "
499528
f"(oauth_client_id + oauth_jwt_key_file + oauth_jwt_kid), OAuth U2M "
500-
f"(auth_type='databricks-oauth' or 'azure-oauth'), or Azure SP M2M "
501-
f"(auth_type='azure-sp-m2m'), but got "
529+
f"(auth_type='databricks-oauth' or 'azure-oauth'), Azure SP M2M "
530+
f"(auth_type='azure-sp-m2m'), or credentials_provider, but got "
502531
f"{provider_desc} with auth_type={auth_type!r}. Use the Thrift "
503532
"backend (default) for other auth flows."
504533
)

‎src/databricks/sql/backend/kernel/client.py‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -523,6 +523,13 @@ def open_session(
523523
self._auth_provider,
524524
self._auth_options,
525525
)
526+
if "header_provider" in auth_kwargs and not (
527+
_kernel_session_accepts_kwarg("header_provider")
528+
):
529+
raise NotSupportedError(
530+
"credentials_provider requires a newer databricks-sql-kernel "
531+
"wheel that accepts a header provider."
532+
)
526533
# Translate the connector's SSLOptions into the kernel's
527534
# ``tls_*`` Session kwargs. Empty when TLS is at defaults.
528535
tls_kwargs = _kernel_tls_kwargs(self._ssl_options)

‎src/databricks/sql/client.py‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -427,10 +427,12 @@ def read(self) -> Optional[OAuthToken]:
427427
)
428428

429429
client_context = build_client_context(server_hostname, __version__, **kwargs)
430-
# The kernel owns its HTTP transport.
430+
# The kernel owns its HTTP transport. A credentials_provider still needs
431+
# the connector's client for its token-federation exchange, as on Thrift.
431432
self.http_client: Optional[UnifiedHttpClient] = (
432433
None
433434
if kwargs.get("use_kernel", False)
435+
and not kwargs.get("credentials_provider")
434436
else UnifiedHttpClient(client_context)
435437
)
436438

‎src/databricks/sql/session.py‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -165,8 +165,16 @@ def __init__(
165165
# provider when an ``access_token`` is present, and ``None``
166166
# otherwise (OAuth M2M/U2M resolve purely from the raw kwargs
167167
# the bridge reads). The Thrift / SEA backends are unchanged.
168+
#
169+
# A custom ``credentials_provider`` is the exception: it runs no
170+
# OAuth flow, so the kernel gets the same provider chain Thrift
171+
# builds (federation wrapper included) and calls it per request.
168172
self.use_kernel = kwargs.get("use_kernel", False)
169-
if self.use_kernel:
173+
if self.use_kernel and kwargs.get("credentials_provider"):
174+
self.auth_provider = get_python_sql_connector_auth_provider(
175+
server_hostname, http_client=self.http_client, **kwargs
176+
)
177+
elif self.use_kernel:
170178
access_token = kwargs.get("access_token")
171179
self.auth_provider = (
172180
AccessTokenAuthProvider(access_token) if access_token else None

0 commit comments

Comments
 (0)