Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -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.
Comment thread
cathleeny marked this conversation as resolved.
Resolved
- 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.

Expand Down
2 changes: 1 addition & 1 deletion CONNECTION_PARAMETERS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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. |
Expand Down
2 changes: 1 addition & 1 deletion KERNEL_REV
Original file line number Diff line number Diff line change
@@ -1 +1 @@
a29235cbea9532efa5572ebff010045583a19cbe
6d6c1e4eb70e3d5bebea75b76c5b19c459d9a467
131 changes: 80 additions & 51 deletions src/databricks/sql/backend/kernel/auth_bridge.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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,
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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
Expand All @@ -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,
Expand Down Expand Up @@ -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")
Expand All @@ -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
]
Expand Down Expand Up @@ -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 "
Expand All @@ -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 "
Expand Down Expand Up @@ -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).
Expand All @@ -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."
)
Expand Down
7 changes: 7 additions & 0 deletions src/databricks/sql/backend/kernel/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -480,6 +480,13 @@ def open_session(
self._auth_provider,
self._auth_options,
)
if "header_provider" in auth_kwargs and not (
Comment thread
cathleeny marked this conversation as resolved.
Resolved
Comment thread
cathleeny marked this conversation as resolved.
Resolved
_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)
Expand Down
4 changes: 3 additions & 1 deletion src/databricks/sql/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Comment thread
cathleeny marked this conversation as resolved.
Resolved
Comment thread
cathleeny marked this conversation as resolved.
Resolved
Comment thread
cathleeny marked this conversation as resolved.
Resolved
else UnifiedHttpClient(client_context)
)

Expand Down
10 changes: 9 additions & 1 deletion src/databricks/sql/session.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading
Loading