Skip to content

Commit 31b3ba4

Browse files
cathleenyIsaac
andauthored
feat(kernel): support credentials_provider on kernel connections (#1086)
* feat(kernel): support credentials_provider on kernel connections On use_kernel=True the connector now builds the same provider chain as Thrift (TokenFederationProvider wrapping ExternalAuthProvider) and passes it to the kernel's external auth as a per-request header provider, so header caching, token federation with identity_federation_client_id and exchange fallback behave as on Thrift. credentials_provider takes precedence over access_token and every auth_type (azure-sp-m2m included), as on Thrift; paired with oauth_client_secret or oauth_jwt_key_file it is rejected as ambiguous before any flow is chosen. The connector keeps its HTTP client for these connections so the federation exchange works, and an older kernel wheel without header_provider raises NotSupportedError. KERNEL_REV pins the kernel commit that adds the header provider. Signed-off-by: Cathleen Yan <58714163+cathleeny@users.noreply.github.com> Co-authored-by: Isaac <no-reply@databricks.com> * test(kernel): assert the credentials_provider guard by its own message The old-kernel test's fake Session lacked enable_geospatial_support, so the geospatial guard raised a NotSupportedError with the same "newer databricks-sql-kernel" text before the header_provider guard could be checked. Removing the header_provider guard left the test passing. Add the kwarg to the fake and match on the "credentials_provider requires a newer databricks-sql-kernel" message. Co-authored-by: Isaac <no-reply@databricks.com> Signed-off-by: Cathleen Yan <58714163+cathleeny@users.noreply.github.com> * test(kernel): make header_provider serialization test deterministic Replace the sleep-based overlap test with the event-based version from review: the first add_headers call blocks on a release event, so the second call provably cannot enter while the first is in flight — the test now fails deterministically without the serialization lock instead of only almost-always. Co-authored-by: Isaac <no-reply@databricks.com> Signed-off-by: Cathleen Yan <58714163+cathleeny@users.noreply.github.com> * test(kernel): cover the credentials_provider http-client gate Add test_kernel_credentials_provider_keeps_python_http_client: on use_kernel=True with a credentials_provider the connector still builds a UnifiedHttpClient and hands it to the session, the federation- wrapped provider chain and the kernel, as on Thrift. Verified the test fails with the gate removed (TokenFederationProvider raises on http_client=None). The no-provider control case is covered by test_kernel_http_client_lifecycle[explicit]. Co-authored-by: Isaac <no-reply@databricks.com> Signed-off-by: Cathleen Yan <58714163+cathleeny@users.noreply.github.com> * Pin the kernel to merged #527 (6d6c1e4) KERNEL_REV moves from the #527 branch head 159a2ff to the commit merged into kernel main, 6d6c1e4. That picks up the external-auth conflict guard (Session rejects credential/OAuth/JWT/Azure/ federation/token-cache kwargs alongside auth_type="external"), async-only external auth in the kernel core, reserved SEA per-request routing headers, and the Volume and LZ4 config changes that landed on kernel main in between. The connector passes only auth_type="external" plus header_provider on the provider path, so no connector change is needed. Verified against the wheel built from 6d6c1e4: the full unit suite (1465 passed), the real-kernel session (5) and async-reader (6) suites, black and mypy. Also drops the kernel-release sentence from the changelog entry; the kernel floor and lockfile move at the joint kernel and driver release, not here. Co-authored-by: Isaac <no-reply@databricks.com> Signed-off-by: Cathleen Yan <58714163+cathleeny@users.noreply.github.com> --------- Signed-off-by: Cathleen Yan <58714163+cathleeny@users.noreply.github.com> Co-authored-by: Isaac <no-reply@databricks.com>
1 parent 72ac235 commit 31b3ba4

10 files changed

Lines changed: 389 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
- 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.
67

‎CONNECTION_PARAMETERS.md‎

Lines changed: 1 addition & 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. |

‎KERNEL_REV‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
a29235cbea9532efa5572ebff010045583a19cbe
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
@@ -480,6 +480,13 @@ def open_session(
480480
self._auth_provider,
481481
self._auth_options,
482482
)
483+
if "header_provider" in auth_kwargs and not (
484+
_kernel_session_accepts_kwarg("header_provider")
485+
):
486+
raise NotSupportedError(
487+
"credentials_provider requires a newer databricks-sql-kernel "
488+
"wheel that accepts a header provider."
489+
)
483490
# Translate the connector's SSLOptions into the kernel's
484491
# ``tls_*`` Session kwargs. Empty when TLS is at defaults.
485492
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)