From d3d5db6609574158472a451983f05a4326f56968 Mon Sep 17 00:00:00 2001 From: Cathleen Yan <58714163+cathleeny@users.noreply.github.com> Date: Tue, 1 Dec 2026 23:56:45 +0000 Subject: [PATCH 1/5] 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 --- CHANGELOG.md | 1 + CONNECTION_PARAMETERS.md | 2 +- KERNEL_REV | 2 +- .../sql/backend/kernel/auth_bridge.py | 131 ++++++++----- src/databricks/sql/backend/kernel/client.py | 7 + src/databricks/sql/client.py | 4 +- src/databricks/sql/session.py | 10 +- tests/unit/test_kernel_auth_bridge.py | 180 ++++++++++++++++-- tests/unit/test_kernel_client.py | 58 ++++++ tests/unit/test_session.py | 13 ++ 10 files changed, 333 insertions(+), 75 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c31d6927f..ecedc7c4a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,7 @@ # Release History # Unreleased +- Support `credentials_provider` on kernel connections (`use_kernel=True`), with the same header refresh and token federation as Thrift. Requires a databricks-sql-kernel release with external header-provider auth. - 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. - 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. diff --git a/CONNECTION_PARAMETERS.md b/CONNECTION_PARAMETERS.md index 6d4f336fd..d240698ed 100644 --- a/CONNECTION_PARAMETERS.md +++ b/CONNECTION_PARAMETERS.md @@ -93,7 +93,7 @@ to change without notice. | `oauth_jwt_algorithm` (OAuth M2M, JWT private key) | `str` | ❌ | ✅ | `RS256` | **Kernel-only.** JWT signing algorithm (`RS256`/`384`/`512`, `PS256`/`384`/`512`, `ES256`, `ES384`). | | `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. | | `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. | -| `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. | +| `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`. | | `identity_federation_client_id` | `str` | ✅ | ✅ | `None` | Workload identity / token-federation client id (kernel support added in #910). | | `experimental_oauth_persistence` | `OAuthPersistence` | ✅ | ❌ | `None` | **Thrift-only.** The kernel owns its own token lifecycle and does not accept a persistence store. | | `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. | diff --git a/KERNEL_REV b/KERNEL_REV index 101d21c5a..c03982892 100644 --- a/KERNEL_REV +++ b/KERNEL_REV @@ -1 +1 @@ -3b691d2a2c235ef847d61b308c31604979830994 +fb18a18215fc11fd58e40a5451b2ce073de0abbb diff --git a/src/databricks/sql/backend/kernel/auth_bridge.py b/src/databricks/sql/backend/kernel/auth_bridge.py index 3477caf6b..7d4cbd189 100644 --- a/src/databricks/sql/backend/kernel/auth_bridge.py +++ b/src/databricks/sql/backend/kernel/auth_bridge.py @@ -51,13 +51,20 @@ wins resolution. It selects mandatory SP-wide workload-identity token exchange in the kernel; omitting it preserves BYOT / account-wide behavior. -A user-supplied custom ``credentials_provider`` is **rejected** on the -kernel path with ``NotSupportedError``: it's an opaque token source -with no extractable raw credentials, so the kernel can't own the -lifecycle. Such callers should pass ``oauth_client_id`` / -``oauth_client_secret`` (M2M) instead. Anything else non-PAT also -raises ``NotSupportedError`` so the failure surfaces at session-open -with a clear message rather than deep inside the kernel. +- **Custom ``credentials_provider``** — takes precedence over + ``access_token`` and ``auth_type``, as on Thrift. The connector builds + the same provider chain Thrift uses + (``TokenFederationProvider(ExternalAuthProvider)``) and passes it to + the kernel's ``auth_type='external'`` as a + ``header_provider`` callable, which the kernel calls on every + authenticated request. Header caching, token federation (including + ``identity_federation_client_id``) and exchange fallback therefore run + in the connector exactly as on Thrift; the kernel does not federate + ``external`` itself. + +Anything else non-PAT raises ``NotSupportedError`` so the failure +surfaces at session-open with a clear message rather than deep inside +the kernel. The M2M / U2M decisions are driven by the *raw* connect() kwargs (``auth_options``), not a built ``AuthProvider``. On the kernel path @@ -72,7 +79,8 @@ import logging import re -from typing import Any, Dict, Optional +import threading +from typing import Any, Callable, Dict, Optional from databricks.sql.auth.auth import ( PYSQL_OAUTH_CLIENT_ID, @@ -152,6 +160,25 @@ def _extract_bearer_token(auth_provider: Optional[AuthProvider]) -> Optional[str return token +def _header_provider(auth_provider: AuthProvider) -> Callable[[], Dict[str, str]]: + """Wrap a connector ``AuthProvider`` as the kernel's ``header_provider``. + + The kernel calls it on every authenticated request, possibly from + several kernel threads at once, so calls are serialized: the + provider's own cache then decides when the user's header factory + (and any federation exchange) runs, as it does on Thrift. + """ + lock = threading.Lock() + + def header_provider() -> Dict[str, str]: + headers: Dict[str, str] = {} + with lock: + auth_provider.add_headers(headers) + return headers + + return header_provider + + def kernel_auth_kwargs( auth_provider: Optional[AuthProvider], auth_options: Optional[Dict[str, Any]] = None, @@ -198,8 +225,11 @@ def kernel_auth_kwargs( (PECOBLR-4039/4040). ``azure-oauth`` resolves identically: the kernel's workspace-federated flow serves Azure workspaces too (PECOBLR-4120). Unlike the Thrift path, a caller-supplied ``oauth_scopes`` is honored here. - 5. **Custom credentials_provider** → ``NotSupportedError`` (opaque - token source; no raw creds for the kernel to own). + 5. **Custom credentials_provider** → ``auth_type='external'``. Checked + first, before the Azure branch and steps 1-4, so it wins over + ``access_token`` and ``auth_type`` as on Thrift + (``auth.get_auth_provider``); only the M2M ambiguity guards above + take priority over it. 6. Anything else → ``NotSupportedError``. M2M is checked before PAT so that a workload passing both an @@ -222,6 +252,35 @@ def kernel_auth_kwargs( # rather than sending a client secret. has_jwt_m2m = bool(jwt_key_file) + # Custom credentials_provider wins over access_token and every auth_type + # (azure-sp-m2m included), as on Thrift (auth.get_auth_provider checks it + # first). Paired with the kernel-only M2M kwargs it is ambiguous; that is + # rejected here, before any flow (Azure included) is chosen. + if opts.get("credentials_provider"): + if client_secret: + raise NotSupportedError( + "Ambiguous auth on use_kernel=True: both a custom " + "credentials_provider and oauth_client_secret were provided. " + "Pass exactly one — oauth_client_id + oauth_client_secret for " + "kernel-managed M2M, or credentials_provider alone." + ) + if has_jwt_m2m: + raise NotSupportedError( + "Ambiguous auth on use_kernel=True: both a custom " + "credentials_provider and oauth_jwt_key_file were provided. " + "Pass exactly one — oauth_client_id + oauth_jwt_key_file for " + "kernel-managed JWT private-key M2M, or credentials_provider alone." + ) + if auth_provider is None: + raise ProgrammingError( + "credentials_provider was set but no auth provider was built " + "for it; cannot route through the kernel's external auth path" + ) + return { + "auth_type": "external", + "header_provider": _header_provider(auth_provider), + } + # Azure Entra (Azure AD) auth types route to the kernel's GENERIC OAuth # flows with Azure values supplied as overrides — the kernel needs no # Azure-specific code. Handled up front, keyed on the explicit auth_type, @@ -256,12 +315,13 @@ def kernel_auth_kwargs( # # This branch returns BEFORE the ambiguity guards below, so an # azure-sp-m2m selector paired with a conflicting OAuth signal - # (oauth_client_secret / oauth_jwt_key_file / credentials_provider) does not - # fail loudly the way the other flows do. That is intentional: azure-sp-m2m - # carries its credentials in the azure_* namespace, so there is no routing - # collision, and an explicit azure-sp-m2m selector is unambiguous intent to - # use the Azure SP flow. Any oauth_*/credentials_provider values are simply - # ignored here rather than treated as ambiguous. + # (oauth_client_secret / oauth_jwt_key_file) does not fail loudly the way + # the other flows do. That is intentional: azure-sp-m2m carries its + # credentials in the azure_* namespace, so there is no routing collision, + # and an explicit azure-sp-m2m selector is unambiguous intent to use the + # Azure SP flow. Any oauth_* values are simply ignored here rather than + # treated as ambiguous. (A credentials_provider never reaches this branch: + # it is resolved above and wins, as on Thrift.) if auth_type == "azure-sp-m2m": azure_client_id = opts.get("azure_client_id") azure_client_secret = opts.get("azure_client_secret") @@ -274,14 +334,13 @@ def kernel_auth_kwargs( # conflicting OAuth signal is not a routing collision and does not fail # loudly the way the other flows do (see the routing note above). Still, # leave a breadcrumb: a caller who paired azure-sp-m2m with an - # oauth_*/credentials_provider value likely misunderstood the routing, - # and those values are silently ignored here. + # oauth_* value likely misunderstood the routing, and those values are + # silently ignored here. ignored_signals = [ name for name in ( "oauth_client_secret", "oauth_jwt_key_file", - "credentials_provider", ) if opts.get(name) is not None ] @@ -313,14 +372,6 @@ def kernel_auth_kwargs( return kwargs # 0. Ambiguity guards — fail before any flow is chosen. - if client_secret and opts.get("credentials_provider") is not None: - raise NotSupportedError( - "Ambiguous auth on use_kernel=True: both a custom " - "credentials_provider and oauth_client_secret were provided. " - "Pass exactly one — oauth_client_id + oauth_client_secret for " - "kernel-managed M2M, or use the Thrift backend (default) for " - "credentials_provider." - ) if client_secret and auth_type in ("databricks-oauth", "azure-oauth"): raise NotSupportedError( f"Ambiguous auth on use_kernel=True: auth_type={auth_type!r} selects " @@ -335,14 +386,6 @@ def kernel_auth_kwargs( "M2M) were provided. Pass exactly one — a private key for " "JWT client-assertion M2M, or a client secret for shared-secret M2M." ) - if has_jwt_m2m and opts.get("credentials_provider") is not None: - raise NotSupportedError( - "Ambiguous auth on use_kernel=True: both a custom " - "credentials_provider and oauth_jwt_key_file were provided. " - "Pass exactly one — oauth_client_id + oauth_jwt_key_file for " - "kernel-managed JWT private-key M2M, or use the Thrift backend " - "(default) for credentials_provider." - ) if has_jwt_m2m and auth_type in ("databricks-oauth", "azure-oauth"): raise NotSupportedError( f"Ambiguous auth on use_kernel=True: auth_type={auth_type!r} selects " @@ -473,20 +516,6 @@ def kernel_auth_kwargs( kwargs["identity_federation_client_id"] = federation_client_id return kwargs - # 5. Custom credentials_provider — the connector's primary M2M path - # on Thrift/SEA, but unusable on the kernel: it's an opaque token - # source with no extractable client_id/secret, so the kernel - # can't own the token lifecycle. Point the caller at the raw - # M2M kwargs instead. - if opts.get("credentials_provider") is not None: - raise NotSupportedError( - "use_kernel=True does not support a custom credentials_provider. " - "For OAuth machine-to-machine auth, pass oauth_client_id and " - "oauth_client_secret so the kernel can manage the token lifecycle " - "directly; or use the Thrift backend (default) with " - "credentials_provider." - ) - # 6. Everything else (including no usable credentials at all — # ``auth_provider`` is None on the kernel path when no access # token was supplied and no OAuth kwargs resolved above). @@ -497,8 +526,8 @@ def kernel_auth_kwargs( f"use_kernel=True requires PAT (access_token), OAuth M2M " f"(oauth_client_id + oauth_client_secret), OAuth M2M JWT " f"(oauth_client_id + oauth_jwt_key_file + oauth_jwt_kid), OAuth U2M " - f"(auth_type='databricks-oauth' or 'azure-oauth'), or Azure SP M2M " - f"(auth_type='azure-sp-m2m'), but got " + f"(auth_type='databricks-oauth' or 'azure-oauth'), Azure SP M2M " + f"(auth_type='azure-sp-m2m'), or credentials_provider, but got " f"{provider_desc} with auth_type={auth_type!r}. Use the Thrift " "backend (default) for other auth flows." ) diff --git a/src/databricks/sql/backend/kernel/client.py b/src/databricks/sql/backend/kernel/client.py index a0e77bbc7..87fcea919 100644 --- a/src/databricks/sql/backend/kernel/client.py +++ b/src/databricks/sql/backend/kernel/client.py @@ -480,6 +480,13 @@ def open_session( self._auth_provider, self._auth_options, ) + if "header_provider" in auth_kwargs and not ( + _kernel_session_accepts_kwarg("header_provider") + ): + raise NotSupportedError( + "credentials_provider requires a newer databricks-sql-kernel " + "wheel that accepts a header provider." + ) # Translate the connector's SSLOptions into the kernel's # ``tls_*`` Session kwargs. Empty when TLS is at defaults. tls_kwargs = _kernel_tls_kwargs(self._ssl_options) diff --git a/src/databricks/sql/client.py b/src/databricks/sql/client.py index 15db8f8f9..cfb8f0ae4 100755 --- a/src/databricks/sql/client.py +++ b/src/databricks/sql/client.py @@ -427,10 +427,12 @@ def read(self) -> Optional[OAuthToken]: ) client_context = build_client_context(server_hostname, __version__, **kwargs) - # The kernel owns its HTTP transport. + # The kernel owns its HTTP transport. A credentials_provider still needs + # the connector's client for its token-federation exchange, as on Thrift. self.http_client: Optional[UnifiedHttpClient] = ( None if kwargs.get("use_kernel", False) + and not kwargs.get("credentials_provider") else UnifiedHttpClient(client_context) ) diff --git a/src/databricks/sql/session.py b/src/databricks/sql/session.py index 1f98cc674..3cee629c3 100644 --- a/src/databricks/sql/session.py +++ b/src/databricks/sql/session.py @@ -165,8 +165,16 @@ def __init__( # provider when an ``access_token`` is present, and ``None`` # otherwise (OAuth M2M/U2M resolve purely from the raw kwargs # the bridge reads). The Thrift / SEA backends are unchanged. + # + # A custom ``credentials_provider`` is the exception: it runs no + # OAuth flow, so the kernel gets the same provider chain Thrift + # builds (federation wrapper included) and calls it per request. self.use_kernel = kwargs.get("use_kernel", False) - if self.use_kernel: + if self.use_kernel and kwargs.get("credentials_provider"): + self.auth_provider = get_python_sql_connector_auth_provider( + server_hostname, http_client=self.http_client, **kwargs + ) + elif self.use_kernel: access_token = kwargs.get("access_token") self.auth_provider = ( AccessTokenAuthProvider(access_token) if access_token else None diff --git a/tests/unit/test_kernel_auth_bridge.py b/tests/unit/test_kernel_auth_bridge.py index 000515915..3ced7f332 100644 --- a/tests/unit/test_kernel_auth_bridge.py +++ b/tests/unit/test_kernel_auth_bridge.py @@ -12,8 +12,11 @@ routes through ``auth_type='oauth-u2m'``; on the kernel path ``azure-oauth`` is an alias for ``databricks-oauth`` (the in-house workspace-federated flow serves Azure workspaces too) (PECOBLR-4120). - - A custom ``credentials_provider`` and any other non-PAT shape raise - ``NotSupportedError`` with a clear, actionable message. + - A custom ``credentials_provider`` routes through ``auth_type='external'`` + with the connector's provider chain as the ``header_provider``, and wins + over ``access_token`` / ``auth_type`` as on Thrift. + - Any other non-PAT shape raises ``NotSupportedError`` with a clear, + actionable message. """ from __future__ import annotations @@ -167,22 +170,6 @@ def test_generic_oauth_provider_raises_not_supported(self): with pytest.raises(NotSupportedError, match="Use the Thrift backend"): kernel_auth_kwargs(_FakeOAuthProvider()) - def test_external_credentials_provider_raises_not_supported(self): - """A user-supplied ``credentials_provider`` is the connector's - primary M2M path on Thrift/SEA, but it's an opaque token source - with no extractable raw creds — the kernel can't own the token - lifecycle, so the bridge rejects it and points at the - ``oauth_client_id`` / ``oauth_client_secret`` M2M kwargs.""" - - def _creds_provider(): - return lambda: {"Authorization": "Bearer noop"} - - with pytest.raises(NotSupportedError, match="oauth_client_secret"): - kernel_auth_kwargs( - _FakeOAuthProvider(), - {"credentials_provider": _creds_provider}, - ) - def test_silent_non_pat_provider_also_raises_not_supported(self): """Even if a non-PAT provider produces no header, the bridge rejects the type itself — we don't try to extract a token @@ -838,14 +825,13 @@ def test_azure_sp_m2m_forwards_federation_client_id(self): [ {"oauth_client_secret": "oauth-secret"}, {"oauth_jwt_key_file": "/tmp/key.pem"}, - {"credentials_provider": object()}, ], ) def test_azure_sp_m2m_ignores_conflicting_oauth_signal(self, conflicting_signal): # Intentional asymmetry: every OTHER flow treats a conflicting credential # signal as a hard "Ambiguous auth" error, but an explicit azure-sp-m2m # selector carries its creds in the azure_* namespace, so a stray - # oauth_*/credentials_provider value is NOT a routing collision — it is + # oauth_* value is NOT a routing collision — it is # silently ignored (logger.warning breadcrumb only) and the Azure SP flow # still wins. This guards against a refactor accidentally promoting the # ignored signal to an error (see the routing note in auth_bridge.py). @@ -860,6 +846,160 @@ def test_azure_sp_m2m_ignores_conflicting_oauth_signal(self, conflicting_signal) } +def _thrift_chain(header_factory): + """The provider chain Thrift builds for ``credentials_provider``.""" + from databricks.sql.auth.authenticators import ExternalAuthProvider + from databricks.sql.auth.token_federation import TokenFederationProvider + + return TokenFederationProvider( + hostname="https://example.cloud.databricks.com", + external_provider=ExternalAuthProvider(lambda: header_factory), + http_client=Mock(), + ) + + +class TestKernelCredentialsProvider: + """A custom ``credentials_provider`` maps to the kernel's + ``auth_type='external'``: the connector's own provider chain becomes the + per-request ``header_provider``, so caching, header handling and token + federation stay identical to Thrift.""" + + @pytest.mark.parametrize( + "extra_options", + [ + pytest.param({}, id="alone"), + pytest.param({"access_token": "pat#1"}, id="with-access-token"), + pytest.param({"auth_type": "databricks-oauth"}, id="with-u2m"), + pytest.param({"auth_type": "azure-oauth"}, id="with-azure-u2m"), + pytest.param( + { + "auth_type": "azure-sp-m2m", + "azure_client_id": "azure-sp", + "azure_client_secret": "azure-secret", + }, + id="with-azure-sp-m2m", + ), + pytest.param({"oauth_client_id": "id"}, id="with-client-id-only"), + pytest.param( + {"identity_federation_client_id": "fed-client"}, + id="with-federation-client-id", + ), + ], + ) + def test_provider_takes_precedence_and_routes_to_external(self, extra_options): + chain = _thrift_chain(lambda: {"Authorization": "Bearer prov#1"}) + opts = dict(extra_options, credentials_provider=object()) + + kwargs = kernel_auth_kwargs(chain, opts) + + # Federation runs in the connector's chain, so nothing else is + # forwarded (no PAT snapshot, no kernel-side federation client id). + assert set(kwargs) == {"auth_type", "header_provider"} + assert kwargs["auth_type"] == "external" + assert kwargs["header_provider"]() == {"Authorization": "Bearer prov#1"} + + _AZURE_SP = { + "auth_type": "azure-sp-m2m", + "azure_client_id": "azure-sp", + "azure_client_secret": "azure-secret", + } + + @pytest.mark.parametrize( + "extra_options", + [ + pytest.param({"oauth_client_secret": "s"}, id="with-secret"), + pytest.param({"oauth_jwt_key_file": "/tmp/key.pem"}, id="with-jwt"), + pytest.param( + dict(_AZURE_SP, oauth_client_secret="s"), id="azure-sp-with-secret" + ), + pytest.param( + dict(_AZURE_SP, oauth_jwt_key_file="/tmp/key.pem"), + id="azure-sp-with-jwt", + ), + ], + ) + def test_provider_with_kernel_m2m_kwargs_fails_loudly(self, extra_options): + # A provider is never silently dropped for another principal: paired + # with kernel-managed M2M kwargs it is rejected before any flow (the + # Azure SP one included) is chosen. + opts = dict(extra_options, credentials_provider=object()) + with pytest.raises(NotSupportedError, match="credentials_provider"): + kernel_auth_kwargs(_thrift_chain(lambda: {}), opts) + + @pytest.mark.parametrize( + "factory_headers, expected, factory_calls", + [ + # Thrift parity: with Authorization present the federation wrapper + # forwards only Authorization and caches it (1 factory call). + pytest.param( + {"Authorization": "Bearer prov#1", "X-Ddf-Probe": "1"}, + {"Authorization": "Bearer prov#1"}, + 1, + id="auth-and-extra", + ), + # Without Authorization the headers pass through, uncached. + pytest.param( + {"X-Custom-Auth": "c#1"}, {"X-Custom-Auth": "c#1"}, 3, id="extra-only" + ), + ], + ) + def test_header_provider_matches_thrift_chain( + self, factory_headers, expected, factory_calls + ): + calls = [] + + def factory(): + calls.append(1) + return dict(factory_headers) + + header_provider = kernel_auth_kwargs( + _thrift_chain(factory), {"credentials_provider": object()} + )["header_provider"] + + assert [header_provider() for _ in range(3)] == [expected] * 3 + assert len(calls) == factory_calls + + def test_header_factory_error_propagates(self): + def factory(): + raise RuntimeError("ddf header factory failure") + + header_provider = kernel_auth_kwargs( + _thrift_chain(factory), {"credentials_provider": object()} + )["header_provider"] + + with pytest.raises(RuntimeError, match="ddf header factory failure"): + header_provider() + + def test_header_provider_calls_are_serialized(self): + import threading + import time + + state = {"active": 0, "max": 0} + + class _SlowProvider(AuthProvider): + def add_headers(self, request_headers): + state["active"] += 1 + state["max"] = max(state["max"], state["active"]) + time.sleep(0.01) + state["active"] -= 1 + request_headers["Authorization"] = "Bearer prov#1" + + header_provider = kernel_auth_kwargs( + _SlowProvider(), {"credentials_provider": object()} + )["header_provider"] + threads = [threading.Thread(target=header_provider) for _ in range(4)] + for t in threads: + t.start() + for t in threads: + t.join() + + assert state["max"] == 1 + + def test_provider_without_built_auth_provider_raises(self): + with pytest.raises(ProgrammingError, match="credentials_provider"): + kernel_auth_kwargs(None, {"credentials_provider": object()}) + + class TestKernelScopesNormalization: def test_unknown_scope_type_raises(self): # A non-str/list/tuple oauth_scopes is a caller error; fail loudly diff --git a/tests/unit/test_kernel_client.py b/tests/unit/test_kernel_client.py index ded4a3362..0103ca6a9 100644 --- a/tests/unit/test_kernel_client.py +++ b/tests/unit/test_kernel_client.py @@ -605,6 +605,64 @@ def fake_session_without_port(host, http_path, *, enable_geospatial_support=Fals c.open_session(session_configuration=None, catalog=None, schema=None) +class _CountingProvider(AccessTokenAuthProvider): + def __init__(self): + super().__init__("unused") + self.calls = 0 + + def add_headers(self, request_headers): + self.calls += 1 + request_headers["Authorization"] = f"Bearer prov#{self.calls}" + + +def _provider_client(provider): + return kernel_client.KernelDatabricksClient( + server_hostname="example.cloud.databricks.com", + http_path="/sql/1.0/warehouses/abc", + auth_provider=provider, + ssl_options=None, + auth_options={"credentials_provider": object(), "access_token": "pat#1"}, + ) + + +def test_open_session_passes_credentials_provider_as_header_provider(monkeypatch): + """The kernel gets the connector's provider as a callable, not a token snapshot.""" + captured = {} + + def fake_session(**kw): + captured.update(kw) + return MagicMock(session_id="sess-id") + + monkeypatch.setattr(kernel_client._kernel, "Session", fake_session) + provider = _CountingProvider() + _provider_client(provider).open_session( + session_configuration=None, catalog=None, schema=None + ) + + assert captured["auth_type"] == "external" + assert "access_token" not in captured + assert provider.calls == 0 + assert captured["header_provider"]() == {"Authorization": "Bearer prov#1"} + assert captured["header_provider"]() == {"Authorization": "Bearer prov#2"} + + +def test_open_session_credentials_provider_on_an_old_kernel_raises_not_supported( + monkeypatch, +): + def fake_session_without_header_provider( + host, http_path, *, auth_type=None, access_token=None + ): + raise AssertionError("must not construct a session") + + monkeypatch.setattr( + kernel_client._kernel, "Session", fake_session_without_header_provider + ) + with pytest.raises(NotSupportedError, match="newer databricks-sql-kernel"): + _provider_client(_CountingProvider()).open_session( + session_configuration=None, catalog=None, schema=None + ) + + def test_open_session_passes_phase_7_telemetry_kwargs_to_kernel(monkeypatch): """Kernel telemetry phase 7 added binding/runtime identity and telemetry config kwargs to ``databricks_sql_kernel.Session``.""" diff --git a/tests/unit/test_session.py b/tests/unit/test_session.py index 976c9a7c1..92444007b 100644 --- a/tests/unit/test_session.py +++ b/tests/unit/test_session.py @@ -487,6 +487,19 @@ def test_use_kernel_pat_builds_minimal_access_token_provider( assert sess.feature_flags is None session_feature_flags.get_instance.assert_not_called() + def test_use_kernel_credentials_provider_builds_thrift_provider_chain( + self, session_feature_flags + ): + # A credentials_provider runs no OAuth flow, so the kernel path builds + # the same federation-wrapped chain as Thrift and hands it to the bridge. + provider = MagicMock() + sess, mock_get_provider = self._build_session( + credentials_provider=provider, access_token="dapi-xyz" + ) + mock_get_provider.assert_called_once() + assert mock_get_provider.call_args.kwargs["credentials_provider"] is provider + assert sess.auth_provider is mock_get_provider.return_value + class TestKernelTransportOptionsThreading: """The connector's retry and socket timeout kwargs must be forwarded From 1b2093205ca3a8c94aab00bb053282cb908d3e24 Mon Sep 17 00:00:00 2001 From: Cathleen Yan <58714163+cathleeny@users.noreply.github.com> Date: Thu, 3 Dec 2026 02:11:31 +0000 Subject: [PATCH 2/5] 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 Signed-off-by: Cathleen Yan <58714163+cathleeny@users.noreply.github.com> --- tests/unit/test_kernel_client.py | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/tests/unit/test_kernel_client.py b/tests/unit/test_kernel_client.py index 0103ca6a9..8cd6b6b6d 100644 --- a/tests/unit/test_kernel_client.py +++ b/tests/unit/test_kernel_client.py @@ -650,14 +650,22 @@ def test_open_session_credentials_provider_on_an_old_kernel_raises_not_supported monkeypatch, ): def fake_session_without_header_provider( - host, http_path, *, auth_type=None, access_token=None + host, + http_path, + *, + auth_type=None, + access_token=None, + enable_geospatial_support=False, ): raise AssertionError("must not construct a session") monkeypatch.setattr( kernel_client._kernel, "Session", fake_session_without_header_provider ) - with pytest.raises(NotSupportedError, match="newer databricks-sql-kernel"): + with pytest.raises( + NotSupportedError, + match="credentials_provider requires a newer databricks-sql-kernel", + ): _provider_client(_CountingProvider()).open_session( session_configuration=None, catalog=None, schema=None ) From 84d527bd3ce78e3aa1bc08910943fbbb0413744f Mon Sep 17 00:00:00 2001 From: Cathleen Yan <58714163+cathleeny@users.noreply.github.com> Date: Thu, 3 Dec 2026 21:28:34 +0000 Subject: [PATCH 3/5] test(kernel): make header_provider serialization test deterministic MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 Signed-off-by: Cathleen Yan <58714163+cathleeny@users.noreply.github.com> --- tests/unit/test_kernel_auth_bridge.py | 45 ++++++++++++++++++--------- 1 file changed, 31 insertions(+), 14 deletions(-) diff --git a/tests/unit/test_kernel_auth_bridge.py b/tests/unit/test_kernel_auth_bridge.py index 3ced7f332..449bbe143 100644 --- a/tests/unit/test_kernel_auth_bridge.py +++ b/tests/unit/test_kernel_auth_bridge.py @@ -971,29 +971,46 @@ def factory(): header_provider() def test_header_provider_calls_are_serialized(self): + # Event-driven (per review): nothing here depends on thread + # scheduling. The first call blocks inside add_headers until + # released, so the second call provably cannot enter add_headers + # while the first is still in it — the test fails deterministically + # if the serialization lock is removed. import threading - import time - state = {"active": 0, "max": 0} + first_entered = threading.Event() + release = threading.Event() + second_entered = threading.Event() + calls = [] - class _SlowProvider(AuthProvider): + class _BlockingProvider(AuthProvider): def add_headers(self, request_headers): - state["active"] += 1 - state["max"] = max(state["max"], state["active"]) - time.sleep(0.01) - state["active"] -= 1 + if not calls: + calls.append(1) + first_entered.set() + release.wait(5) + else: + second_entered.set() request_headers["Authorization"] = "Bearer prov#1" header_provider = kernel_auth_kwargs( - _SlowProvider(), {"credentials_provider": object()} + _BlockingProvider(), {"credentials_provider": object()} )["header_provider"] - threads = [threading.Thread(target=header_provider) for _ in range(4)] - for t in threads: - t.start() - for t in threads: - t.join() - assert state["max"] == 1 + t1 = threading.Thread(target=header_provider) + t1.start() + assert first_entered.wait(5) + t2 = threading.Thread(target=header_provider) + t2.start() + # While the first call is blocked inside add_headers, the second + # call must still be held by the lock. + assert not second_entered.wait(0.3) + release.set() + t1.join(5) + t2.join(5) + assert not t1.is_alive() + assert not t2.is_alive() + assert second_entered.is_set() def test_provider_without_built_auth_provider_raises(self): with pytest.raises(ProgrammingError, match="credentials_provider"): From 41eb42ddc107cc28e785dec45c42d0a3eacd6049 Mon Sep 17 00:00:00 2001 From: Cathleen Yan <58714163+cathleeny@users.noreply.github.com> Date: Thu, 3 Dec 2026 21:50:26 +0000 Subject: [PATCH 4/5] 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 Signed-off-by: Cathleen Yan <58714163+cathleeny@users.noreply.github.com> --- tests/unit/test_session.py | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/tests/unit/test_session.py b/tests/unit/test_session.py index 92444007b..bf0d7942f 100644 --- a/tests/unit/test_session.py +++ b/tests/unit/test_session.py @@ -1020,6 +1020,37 @@ def test_kernel_http_client_lifecycle(self, mock_thrift, route): 1 if route == "recovery" else 0 ) + @patch("%s.session.ThriftDatabricksClient" % PACKAGE) + def test_kernel_credentials_provider_keeps_python_http_client(self, mock_thrift): + # use_kernel=True WITH a credentials_provider: unlike a plain kernel + # connection, the connector still builds its own UnifiedHttpClient — + # the provider chain's token-federation exchange needs it, exactly + # as on Thrift (TokenFederationProvider raises on a missing client, + # so a regression here breaks federation at runtime). The client must + # flow to the session, the federation-wrapped chain and the kernel. + # The control case — use_kernel=True without a provider builds no + # client — is covered by test_kernel_http_client_lifecycle[explicit]. + from databricks.sql.auth.token_federation import TokenFederationProvider + + def provider(): + return {"Authorization": "Bearer prov#1"} + + with self._fake_kernel() as kernel, patch( + f"{self.PACKAGE}.client.UnifiedHttpClient" + ) as http_client: + conn = self._connect(use_kernel=True, credentials_provider=provider) + try: + assert conn.session.use_kernel is True + http_client.assert_called_once() + assert conn.http_client is http_client.return_value + assert conn.session.http_client is conn.http_client + assert kernel.call_args.kwargs["http_client"] is conn.http_client + # Same federation-wrapped chain as Thrift, carrying that client. + assert isinstance(conn.session.auth_provider, TokenFederationProvider) + assert conn.session.auth_provider.http_client is conn.http_client + finally: + conn.close() + @pytest.mark.parametrize("failure_stage", ["backend", "open"]) def test_explicit_kernel_failure_preserves_error_and_telemetry(self, failure_stage): with self._fake_kernel() as kernel, patch( From d2fe5c67e14559d2ef83a631d486874be3ffb1ab Mon Sep 17 00:00:00 2001 From: Cathleen Yan <58714163+cathleeny@users.noreply.github.com> Date: Thu, 3 Dec 2026 23:37:37 +0000 Subject: [PATCH 5/5] 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 Signed-off-by: Cathleen Yan <58714163+cathleeny@users.noreply.github.com> --- CHANGELOG.md | 2 +- KERNEL_REV | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ecedc7c4a..ec4719355 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,7 +1,7 @@ # Release History # Unreleased -- Support `credentials_provider` on kernel connections (`use_kernel=True`), with the same header refresh and token federation as Thrift. Requires a databricks-sql-kernel release with external header-provider auth. +- Support `credentials_provider` on kernel connections (`use_kernel=True`), with the same header refresh and token federation as Thrift. - 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. - 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. diff --git a/KERNEL_REV b/KERNEL_REV index f2e9a9eb8..bf66d751f 100644 --- a/KERNEL_REV +++ b/KERNEL_REV @@ -1 +1 @@ -159a2ff0b69dd74e1b9bd98a4e03d6db47b142c8 +6d6c1e4eb70e3d5bebea75b76c5b19c459d9a467