Skip to content
Open
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
Expand Up @@ -5,6 +5,7 @@
### Driver changes

- Lower the minimum supported Go version from 1.27.3 to 1.26.11. Go 1.27 users need 1.27.4 or newer for the emSign certificate distrust and November security fixes. The `go.mod` minimum accepts every Go 1.27 patch, including 1.27.0 through 1.27.3.
- Support custom authenticators and token providers (`WithAuthenticator`, `WithTokenProvider`, `WithExternalToken`, `WithStaticToken`, `WithFederatedTokenProvider*`) on the kernel backend, called on every request as on Thrift. Federated tokens now refresh instead of being read once at connect.
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
- Read buffered kernel result batches without a runtime hop, falling back to a blocking fetch when needed.
- Honor `WithPort` and the DSN port on the kernel backend, including after automatic Reyden recovery, instead of rejecting a non-default port. IPv6 hosts need brackets, and a port the kernel rejects returns an error wrapping both `ErrInvalidKernelConfig` and `ErrNotSupportedByKernel`.
- **Behavior change:** Nested `DATE` and `TIMESTAMP_NTZ` text changes in every session time zone, UTC included, with no option to restore the old text. This covers `ARRAY` elements, `MAP` values and keys, and `STRUCT` fields (databricks/databricks-sql-go#604).
Expand Down
26 changes: 18 additions & 8 deletions CONNECTION_PARAMETERS.md
Original file line number Diff line number Diff line change
Expand Up @@ -54,18 +54,28 @@ wire. They are listed under [Kernel client-result confs](#kernel-client-result-c
| Personal access token (PAT) | `token:<t>@…`, or `accessToken=` / `authType=Pat` | `WithAccessToken` | ✅ | ✅ |
| OAuth machine-to-machine (M2M) | `clientID=` (or `clientId=`) + `clientSecret=` / `authType=OauthM2M` | `WithClientCredentials` | ✅ | ✅ |
| OAuth user-to-machine (U2M) | `authType=OauthU2M` | `WithAuthenticator` (u2m) | ✅ | ✅ |
| Custom / external / static token provider | — | `WithTokenProvider`, `WithExternalToken`, `WithStaticToken` | ✅ | ❌ |
| Custom authenticator | — | `WithAuthenticator(custom)` | ✅ | ❌ |
| Custom / external / static token provider | — | `WithTokenProvider`, `WithExternalToken`, `WithStaticToken` | ✅ | ✅ |
| Custom authenticator | — | `WithAuthenticator(custom)` | ✅ | ✅ |
| Federated token provider | — | `WithFederatedTokenProvider`, `WithFederatedTokenProviderAndClientID` | ✅ | ✅ |

Notes for the SEA/kernel backend:

- The kernel snapshots one federated-provider token during setup;
`WithFederatedTokenProviderAndClientID` also forwards the SP-wide client ID. Expired
tokens require a new connection.
- `WithAuthenticator` is kernel-compatible only when its concrete authenticator is
one of the supported PAT, M2M, or U2M implementations. An arbitrary custom
`auth.Authenticator` is supported on Thrift and rejected on the kernel path.
- A custom authenticator, token provider or federated token provider runs on every
kernel HTTP request, as on Thrift: `Authenticate` gets a fresh `POST` request for the
Thrift endpoint URL, not the kernel request's own method and path (the same request a
Thrift authenticator sees), and the `Authorization` and extra headers it sets are sent.
`User-Agent`, `Content-Type`, `Content-Length`, `Host`, `Transfer-Encoding`,
`Connection`, `Accept-Encoding`, `x-databricks-org-id`,
`x-databricks-metadata-operation-type`, `x-databricks-sea-can-run-fully-sync` and
`x-databricks-require-thrift-native-metadata` are ignored. A value with CR, LF or NUL
fails the request. The request context is `context.Background()`, so caller cancellation and
context values do not reach the provider ([kernel issue #537](https://github.com/databricks/databricks-sql-kernel/issues/537)).
- Token federation is done by the driver's own wrapper, as on Thrift (an exchange per
request, no cache); the kernel's own federation exchange does not run for these modes.
- An authenticator error fails the request at once; Thrift retries it under `WithRetries`.
The kernel preserves the error identity when its message matches exactly, but a concurrent
or earlier failure with the same text can be mistaken for it. The connection and its session
stay usable. The kernel also calls the authenticator once before its first request at connect.
- **U2M** is interactive: on a cache miss, connecting launches the browser to complete the
login. Use PAT or M2M for headless connects (they need no browser).
- On the kernel path U2M always uses the in-house `databricks-sql-connector` OAuth app and
Expand Down
2 changes: 1 addition & 1 deletion KERNEL_REV
Original file line number Diff line number Diff line change
@@ -1 +1 @@
a29235cbea9532efa5572ebff010045583a19cbe
6d6c1e4eb70e3d5bebea75b76c5b19c459d9a467
Comment thread
cathleeny marked this conversation as resolved.
Resolved
9 changes: 4 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -297,7 +297,8 @@ groups. Telemetry parameters are covered under [Telemetry](#telemetry).
| Personal access token (PAT) | `token:<t>@…`, or `accessToken=` / `authType=Pat` | `WithAccessToken` | Both |
| OAuth machine-to-machine (M2M) | `clientID=`+`clientSecret=` / `authType=OauthM2M` | `WithClientCredentials` | Both |
| OAuth user-to-machine (U2M) | `authType=OauthU2M` | `WithAuthenticator` (u2m) | Both |
| Custom / external / static token provider | — | `WithTokenProvider`, `WithExternalToken`, `WithStaticToken` | Thrift only |
| Custom / external / static token provider | — | `WithTokenProvider`, `WithExternalToken`, `WithStaticToken` | Both |
| Custom authenticator | — | `WithAuthenticator(custom)` | Both |
| Federated token provider | — | `WithFederatedTokenProvider*` | Both |

**PAT** (default): supply `token:<pat>@…` in the DSN, or `WithAccessToken`.
Expand All @@ -322,13 +323,11 @@ M2M requests the `all-apis` scope by default. For a secret limited to other scop

Notes for the SEA/kernel backend:

- The kernel snapshots one `WithFederatedTokenProvider*` token during setup;
`AndClientID` also forwards the SP-wide client ID. Expired tokens require a new connection.
- Custom authenticators and token providers, federated ones included, run on every
kernel request, as on Thrift; see [CONNECTION_PARAMETERS.md](CONNECTION_PARAMETERS.md#authentication).
- **U2M** is interactive: on a cache miss, connecting launches the browser and a
connect-context **deadline is not honored** during the login window. U2M scopes are at
parity with Thrift. Use PAT or M2M for headless/deadline-bound connects.
- Custom token-provider / external / static authenticators are **Thrift
only**.
- OAuth token caching/refresh is owned by the kernel on the kernel path (no driver
config).

Expand Down
18 changes: 2 additions & 16 deletions connector.go
Original file line number Diff line number Diff line change
Expand Up @@ -56,13 +56,6 @@ func shouldSkipDriverTelemetry(be backend.Backend) bool {
return !isThrift
}

// federatedTokenAuthenticator preserves the base provider for the kernel.
type federatedTokenAuthenticator struct {
auth.Authenticator
provider tokenprovider.TokenProvider
clientID string
}

// Connect returns a connection to the Databricks database from a connection pool.
func (c *connector) Connect(ctx context.Context) (driver.Conn, error) {
defer debuglog.Track(ctx, "connector.Connect", "host=%s", c.cfg.Host)()
Expand Down Expand Up @@ -636,10 +629,7 @@ func WithFederatedTokenProvider(baseProvider tokenprovider.TokenProvider) ConnOp
if baseProvider != nil {
// Wrap with federation provider that auto-detects need for token exchange
federationProvider := tokenprovider.NewFederationProvider(baseProvider, c.Host)
c.Authenticator = &federatedTokenAuthenticator{
Authenticator: tokenprovider.NewAuthenticator(federationProvider),
provider: baseProvider,
}
c.Authenticator = tokenprovider.NewAuthenticator(federationProvider)
}
}
}
Expand All @@ -650,11 +640,7 @@ func WithFederatedTokenProviderAndClientID(baseProvider tokenprovider.TokenProvi
if baseProvider != nil {
// Wrap with federation provider for SP-wide federation
federationProvider := tokenprovider.NewFederationProviderWithClientID(baseProvider, c.Host, clientID)
c.Authenticator = &federatedTokenAuthenticator{
Authenticator: tokenprovider.NewAuthenticator(federationProvider),
provider: baseProvider,
clientID: clientID,
}
c.Authenticator = tokenprovider.NewAuthenticator(federationProvider)
}
}
}
Expand Down
10 changes: 6 additions & 4 deletions doc.go
Original file line number Diff line number Diff line change
Expand Up @@ -220,16 +220,18 @@ RUST_LOG. Filter on the target databricks::sql::kernel (note the colons):
DBSQL_KERNEL_DEBUG=1 RUST_LOG=debug ./your_app

Supported on the kernel backend: PAT and OAuth (M2M via WithClientCredentials, U2M
via the authType=oauthU2M DSN param); reading scalar, nested, and complex-typed
via the authType=oauthU2M DSN param); custom authenticators and token providers
(WithAuthenticator, WithTokenProvider, WithExternalToken, WithStaticToken,
WithFederatedTokenProvider*), whose Authenticate runs on every kernel request with a
POST to the Thrift endpoint URL (not the kernel request's own method and path); reading scalar, nested, and complex-typed
results (CloudFetch is transparent); bound query parameters (positional and named);
context cancellation during execute; the initial namespace (WithInitialNamespace,
applied post-connect via USE CATALOG / USE SCHEMA); metric-view metadata
(WithEnableMetricViewMetadata); the retry / backoff policy (WithRetries:
RetryWaitMin / RetryWaitMax / RetryMax, including the disable form, forwarded to the
kernel's HTTP retry config); and the TLS, proxy, and session-conf (query tags,
statement timeout, time zone) options. Federated token providers use one token snapshot
during setup. Nothing is silently ignored: WithTimeout and token-provider / external /
static authenticators are rejected at connect; staging (PUT/GET/REMOVE on a
statement timeout, time zone) options. Nothing is silently ignored: WithTimeout is
rejected at connect; staging (PUT/GET/REMOVE on a
Unity Catalog volume) is rejected at execute. WithMaxRows is accepted but inert (the
kernel manages fetching below the C ABI).

Expand Down
42 changes: 39 additions & 3 deletions internal/backend/kernel/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,22 @@ package kernel
// resolves an Auth from the config; OpenSession (tagged) maps it to the kernel's
// set_auth_* C setters.

import (
"fmt"
"net/http"
"strings"

"github.com/databricks/databricks-sql-go/v2/auth"
)

// AuthMode selects which kernel auth form OpenSession applies.
type AuthMode int

const (
AuthPAT AuthMode = iota // personal access token
AuthM2M // OAuth client-credentials (client id + secret)
AuthU2M // OAuth user-to-machine (browser/PKCE; kernel-owned flow)
AuthPAT AuthMode = iota // personal access token
AuthM2M // OAuth client-credentials (client id + secret)
AuthU2M // OAuth user-to-machine (browser/PKCE; kernel-owned flow)
AuthExternal // driver authenticator, called on every kernel request
)

// Auth is the resolved auth descriptor for a kernel connection. Only the fields
Expand All @@ -36,6 +45,33 @@ type Auth struct {
ClientSecret string // M2M
Scopes []string // M2M — the authenticator's scopes; U2M — fixed offline_access + sql (cloud-agnostic); nil → kernel default
RedirectPort uint16 // U2M — no user option today; 0 → kernel default port (8030)
// External: the authenticator and the URL of the throwaway request it
// authenticates once per kernel request (the C callback carries no URL).
Authenticator auth.Authenticator
RequestURL string
}

// externalHeaders runs authr on a throwaway POST to url, as the Thrift transport
// does for each HTTP request, and returns every header it set. A NUL byte is
// rejected here because C strings would silently truncate at it.
func externalHeaders(authr auth.Authenticator, url string) ([][2]string, error) {
req, err := http.NewRequest(http.MethodPost, url, nil)
Comment thread
cathleeny marked this conversation as resolved.
Resolved
if err != nil {
return nil, err
}
if err := authr.Authenticate(req); err != nil {
return nil, err
}
var headers [][2]string
for name, values := range req.Header {
for _, value := range values {
if strings.ContainsRune(name, 0) || strings.ContainsRune(value, 0) {
return nil, fmt.Errorf("databricks: the authenticator set header %q with a NUL byte", name)
}
headers = append(headers, [2]string{name, value})
}
}
return headers, nil
}

// M2MCredentialsProvider is implemented by the OAuth M2M authenticator to expose
Expand Down
123 changes: 123 additions & 0 deletions internal/backend/kernel/auth_callback.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
//go:build cgo && databricks_kernel

package kernel

/*
#include <stdint.h>
#include <stdlib.h>
#include "databricks_kernel.h"

// Adapters with the exact KernelAuthHeadersCallback / KernelAuthReleaseCallback
// signatures that forward to the Go exports below, so no function-pointer cast
// is needed (same pattern as the log callback).
int32_t kernelAuthHeadersTrampoline(void* user_data, KernelAuthHeaders* headers);
void kernelAuthReleaseTrampoline(void* user_data);
static int32_t kernelAuthHeadersAdapter(void* user_data, KernelAuthHeaders* headers) {
return kernelAuthHeadersTrampoline(user_data, headers);
}
static void kernelAuthReleaseAdapter(void* user_data) { kernelAuthReleaseTrampoline(user_data); }
static KernelAuthHeadersCallback kernel_auth_headers_cb(void) { return kernelAuthHeadersAdapter; }
static KernelAuthReleaseCallback kernel_auth_release_cb(void) { return kernelAuthReleaseAdapter; }
*/
import "C"

import (
"fmt"
"net/http"
"runtime/cgo"
"sync/atomic"
"unsafe"

"github.com/databricks/databricks-sql-go/v2/auth"
)

// externalAuth is what the kernel's per-request auth callback reaches through
// its user_data: the driver authenticator and the URL of the throwaway request.
type externalAuth struct {
authr auth.Authenticator
url string
lastErr atomic.Pointer[authError]
}

type authError struct{ err error }

// Authenticate records only failures from the authenticator, not header validation
// failures. Callbacks for a statement and a detached cancel can run concurrently.
func (e *externalAuth) Authenticate(req *http.Request) error {
err := e.authr.Authenticate(req)
if err != nil {
e.lastErr.Store(&authError{err: err})
}
return err
}

func (e *externalAuth) wrapProviderFailure(err error) error {
if e == nil {
return err
}
if last := e.lastErr.Load(); last != nil {
return wrapProviderFailure(err, last.err)
}
return err
}

// setAuthExternal registers ext as the session's credentials callback. The
// cgo.Handle lives in C memory (never in a C pointer slot itself); the kernel's
// release callback deletes it and frees that memory exactly once, after the
// session is closed or the config is freed. If the setter fails, the kernel
// does not call release, so this function cleans up instead.
func setAuthExternal(cfg *C.KernelSessionConfig, ext *externalAuth) error {
h := cgo.NewHandle(ext)
slot := (*C.uintptr_t)(C.malloc(C.size_t(unsafe.Sizeof(C.uintptr_t(0)))))
*slot = C.uintptr_t(h)
err := call(func() C.KernelStatusCode {
return C.kernel_session_config_set_auth_external(
cfg, C.kernel_auth_headers_cb(), C.kernel_auth_release_cb(), unsafe.Pointer(slot))
Comment thread
cathleeny marked this conversation as resolved.
Resolved
Comment thread
cathleeny marked this conversation as resolved.
Resolved
})
if err != nil {
h.Delete()
C.free(unsafe.Pointer(slot))
}
return err
}

//export kernelAuthHeadersTrampoline
func kernelAuthHeadersTrampoline(userData unsafe.Pointer, headers *C.KernelAuthHeaders) (status C.int32_t) {
// A panic must never cross the C ABI: fail this request instead.
defer func() {
if r := recover(); r != nil {
setAuthHeadersError(headers, "databricks: the authenticator panicked")
status = 1
}
}()
ext := cgo.Handle(*(*C.uintptr_t)(userData)).Value().(*externalAuth)
pairs, err := externalHeaders(ext, ext.url)
if err != nil {
setAuthHeadersError(headers, err.Error())
Comment thread
cathleeny marked this conversation as resolved.
Resolved
return 1
}
for _, p := range pairs {
name, value := newCStr(p[0]), newCStr(p[1])
st := C.kernel_auth_headers_add(headers, name.c, value.c)
name.free()
value.free()
if st != C.KernelStatusCode_Success {
setAuthHeadersError(headers, fmt.Sprintf("databricks: the kernel rejected header %q", p[0]))
return 1
}
}
return 0
}

//export kernelAuthReleaseTrampoline
func kernelAuthReleaseTrampoline(userData unsafe.Pointer) {
defer func() { _ = recover() }()
cgo.Handle(*(*C.uintptr_t)(userData)).Delete()
C.free(userData)
}

func setAuthHeadersError(headers *C.KernelAuthHeaders, msg string) {
m := newCStr(msg)
defer m.free()
C.kernel_auth_headers_set_error(headers, m.c)
}
Loading
Loading