From 23a9b8d72f5cab548432fbe31593e099bc8cd7e2 Mon Sep 17 00:00:00 2001 From: Cathleen Yan <58714163+cathleeny@users.noreply.github.com> Date: Tue, 1 Dec 2026 23:55:21 +0000 Subject: [PATCH 1/6] feat(kernel): custom authenticators and token providers on the kernel backend Route every authenticator that is not PAT, M2M or U2M through the kernel's new per-request credentials callback (kernel_session_config_set_auth_external) instead of rejecting it. This covers WithAuthenticator(custom), WithTokenProvider, WithExternalToken, WithStaticToken and WithFederatedTokenProvider[AndClientID]. - A cgo.Handle, held in C memory, reaches the authenticator from an exported trampoline. On each kernel request it calls Authenticate on a fresh POST to the Thrift endpoint URL and passes back every header it set. The kernel's release callback deletes the handle once the session or config is gone. - Federated providers are no longer a one-time PAT snapshot taken at connect. The driver's own FederationProvider now runs per request, as on Thrift (an RFC 8693 exchange per request, no cache, fallback on refusal), and the kernel's own federation does not run for this mode. - NUL bytes are rejected in Go before the C boundary. The kernel rejects CR and LF and ignores the headers it manages. - An authenticator error fails the request at once with its message, and the session stays usable (it is local, nothing was sent). Thrift retried it under WithRetries. - PAT, M2M and U2M mappings are unchanged. KERNEL_REV moves to the kernel change that adds the setter (fb18a18215fc11fd58e40a5451b2ce073de0abbb), and its C header is copied. The header also carries kernel main's revocation setter declaration, which the driver does not use. Signed-off-by: Cathleen Yan <58714163+cathleeny@users.noreply.github.com> Co-authored-by: Isaac --- CHANGELOG.md | 1 + CONNECTION_PARAMETERS.md | 22 +- KERNEL_REV | 2 +- README.md | 9 +- connector.go | 18 +- doc.go | 10 +- internal/backend/kernel/auth.go | 42 +- internal/backend/kernel/auth_callback.go | 98 ++++ internal/backend/kernel/auth_callback_test.go | 424 ++++++++++++++++++ internal/backend/kernel/auth_test.go | 88 ++++ internal/backend/kernel/backend.go | 7 +- internal/backend/kernel/errors_classify.go | 16 +- .../backend/kernel/errors_classify_test.go | 23 + .../kernel/include/databricks_kernel.h | 59 ++- kernel_closed_conn_test.go | 60 +++ kernel_config.go | 42 +- kernel_config_test.go | 87 ++-- 17 files changed, 899 insertions(+), 109 deletions(-) create mode 100644 internal/backend/kernel/auth_callback.go create mode 100644 internal/backend/kernel/auth_callback_test.go create mode 100644 internal/backend/kernel/auth_test.go diff --git a/CHANGELOG.md b/CHANGELOG.md index 41c5e722e..b51d8ba99 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,7 @@ ### Driver changes +- 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. - 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). diff --git a/CONNECTION_PARAMETERS.md b/CONNECTION_PARAMETERS.md index 1dd9bb152..bd9db3adf 100644 --- a/CONNECTION_PARAMETERS.md +++ b/CONNECTION_PARAMETERS.md @@ -54,18 +54,24 @@ wire. They are listed under [Kernel client-result confs](#kernel-client-result-c | Personal access token (PAT) | `token:@…`, 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` and `x-databricks-org-id` are ignored, and a value with CR, LF or NUL fails + the request. The request context is `context.Background()`. +- 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 with the error's message; Thrift retries + it under `WithRetries`. 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 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/README.md b/README.md index b4b5536f5..45010666a 100644 --- a/README.md +++ b/README.md @@ -297,7 +297,8 @@ groups. Telemetry parameters are covered under [Telemetry](#telemetry). | Personal access token (PAT) | `token:@…`, 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:@…` in the DSN, or `WithAccessToken`. @@ -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). diff --git a/connector.go b/connector.go index 6828d9f58..4b3c5e044 100644 --- a/connector.go +++ b/connector.go @@ -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)() @@ -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) } } } @@ -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) } } } diff --git a/doc.go b/doc.go index aaf8cb746..bc9eec00f 100644 --- a/doc.go +++ b/doc.go @@ -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). diff --git a/internal/backend/kernel/auth.go b/internal/backend/kernel/auth.go index a3f3ecd7e..705bcdb0d 100644 --- a/internal/backend/kernel/auth.go +++ b/internal/backend/kernel/auth.go @@ -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 @@ -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) + 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 diff --git a/internal/backend/kernel/auth_callback.go b/internal/backend/kernel/auth_callback.go new file mode 100644 index 000000000..56803cbd8 --- /dev/null +++ b/internal/backend/kernel/auth_callback.go @@ -0,0 +1,98 @@ +//go:build cgo && databricks_kernel + +package kernel + +/* +#include +#include +#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" + "runtime/cgo" + "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 +} + +// setAuthExternal registers authr 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, authr auth.Authenticator, url string) error { + h := cgo.NewHandle(&externalAuth{authr: authr, url: url}) + 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)) + }) + 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.authr, ext.url) + if err != nil { + setAuthHeadersError(headers, err.Error()) + 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) +} diff --git a/internal/backend/kernel/auth_callback_test.go b/internal/backend/kernel/auth_callback_test.go new file mode 100644 index 000000000..2e88db895 --- /dev/null +++ b/internal/backend/kernel/auth_callback_test.go @@ -0,0 +1,424 @@ +//go:build cgo && databricks_kernel + +package kernel + +import ( + "context" + "encoding/base64" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "net/http/httptest" + "sort" + "strings" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/databricks/databricks-sql-go/v2/auth/tokenprovider" + "github.com/databricks/databricks-sql-go/v2/internal/backend" + "github.com/stretchr/testify/require" +) + +// authSeen is one request the fake SEA server received. +type authSeen struct{ method, path, authorization, probe, userAgent string } + +// authServer is a minimal SEA endpoint that records the auth headers of every +// request. A statement whose SQL contains SLOW stays RUNNING until cancelled. +type authServer struct { + *httptest.Server + mu sync.Mutex + seen []authSeen + cancelled atomic.Bool +} + +func (s *authServer) requests() []authSeen { + s.mu.Lock() + defer s.mu.Unlock() + return append([]authSeen(nil), s.seen...) +} + +func newAuthServer(t *testing.T) *authServer { + t.Helper() + payload := batchTestIPC(t, 1) + s := &authServer{} + s.Server = httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + body, _ := io.ReadAll(r.Body) + s.mu.Lock() + s.seen = append(s.seen, authSeen{r.Method, r.URL.Path, r.Header.Get("Authorization"), r.Header.Get("X-Ddf-Probe"), r.Header.Get("User-Agent")}) + s.mu.Unlock() + w.Header().Set("Content-Type", "application/json") + switch { + case r.Method == http.MethodPost && strings.HasSuffix(r.URL.Path, "/sessions"): + _, _ = io.WriteString(w, `{"session_id":"auth-session"}`) + case r.Method == http.MethodPost && strings.HasSuffix(r.URL.Path, "/statements") && strings.Contains(string(body), "SLOW"): + _, _ = io.WriteString(w, `{"statement_id":"slow","status":{"state":"RUNNING"}}`) + case r.Method == http.MethodPost && strings.HasSuffix(r.URL.Path, "/statements"): + _ = json.NewEncoder(w).Encode(map[string]any{ + "statement_id": "fast", "status": map[string]any{"state": "SUCCEEDED"}, + "manifest": map[string]any{ + "format": "ARROW_STREAM", "total_chunk_count": 1, "total_row_count": 3, + "schema": map[string]any{"column_count": 3, "columns": []map[string]any{ + {"name": "boolean", "type_name": "BOOLEAN", "type_text": "BOOLEAN", "position": 0}, + {"name": "float", "type_name": "FLOAT", "type_text": "FLOAT", "position": 1}, + {"name": "double", "type_name": "DOUBLE", "type_text": "DOUBLE", "position": 2}, + }}, + }, + "result": map[string]any{"chunk_index": 0, "row_offset": 0, "row_count": 3, "attachment": base64.StdEncoding.EncodeToString(payload)}, + }) + case r.Method == http.MethodPost && strings.HasSuffix(r.URL.Path, "/statements/slow/cancel"): + s.cancelled.Store(true) + _, _ = io.WriteString(w, `{}`) + case r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/statements/slow"): + state := "RUNNING" + if s.cancelled.Load() { + state = "CANCELED" + } + _, _ = fmt.Fprintf(w, `{"statement_id":"slow","status":{"state":%q}}`, state) + default: + _, _ = io.WriteString(w, `{}`) + } + })) + t.Cleanup(s.Close) + return s +} + +func (s *authServer) backend(authr authenticatorFunc) *KernelBackend { + enabled := false + return New(Config{ + Host: s.URL, HTTPPath: "/sql/1.0/warehouses/auth", + Auth: Auth{Mode: AuthExternal, Authenticator: authr, RequestURL: s.URL + "/sql/1.0/warehouses/auth"}, + UserAgent: "ddf-driver-ua", + TLSSkipVerify: true, RequestTimeout: 5 * time.Second, + Retry: &RetryConfig{MinWait: time.Millisecond, MaxWait: time.Millisecond, MaxRetries: 0}, + Telemetry: &TelemetryConfig{Enabled: &enabled}, + }) +} + +// waitForCloses waits until n statement-close DELETEs arrived: the kernel sends +// them fire-and-forget, so they can otherwise race the assertions. +func (s *authServer) waitForCloses(t *testing.T, n int) { + t.Helper() + require.Eventually(t, func() bool { + got := 0 + for _, r := range s.requests() { + if r.method == http.MethodDelete && strings.HasSuffix(r.path, "/statements/fast") { + got++ + } + } + return got >= n + }, 5*time.Second, 5*time.Millisecond) +} + +func runStatement(t *testing.T, k *KernelBackend, ctx context.Context, sql string) error { + t.Helper() + op, err := k.Execute(ctx, backend.ExecRequest{Query: sql}) + if err != nil { + return err + } + _, closeErr := op.Close(context.Background()) + return closeErr +} + +// AC-2 / AC-3: the authenticator runs on every kernel request with a fresh value, +// extra headers reach the wire, and driver-managed headers cannot be overridden. +// With DriverSystemConfiguration set, as kernel_config.go does in production, the +// kernel's feature-flag GET (cold cache) is the first authenticated request. +func TestExternalAuthPerRequestHeaders(t *testing.T) { + for _, tc := range []struct { + name string + dsc *DriverSystemConfiguration + firstPath string + want int + }{ + {name: "no driver system configuration", firstPath: "/sessions", want: 8}, + { + name: "feature-flag GET consumes the pre-flight value", + dsc: &DriverSystemConfiguration{DriverName: "databricks-sql-go", DriverVersion: "ddf-auth-ff"}, + firstPath: "/connector-service/feature-flags/GOLANG/ddf-auth-ff", + want: 9, + }, + } { + t.Run(tc.name, func(t *testing.T) { + s := newAuthServer(t) + var calls atomic.Int32 + k := s.backend(func(r *http.Request) error { + n := calls.Add(1) + r.Header.Set("Authorization", fmt.Sprintf("Bearer tok-%d", n)) + r.Header.Set("X-Ddf-Probe", "probe") + r.Header.Set("User-Agent", "provider-override") + return nil + }) + k.cfg.DriverSystemConfiguration = tc.dsc + // A per-test org id keeps the kernel's process-wide flag cache cold. + k.cfg.HTTPPath += fmt.Sprintf("?o=%d", time.Now().UnixNano()) + require.NoError(t, k.OpenSession(context.Background())) + for i := 0; i < 3; i++ { + require.NoError(t, runStatement(t, k, context.Background(), "SELECT 1")) + } + s.waitForCloses(t, 3) + require.NoError(t, k.CloseSession(context.Background())) + + // The kernel's pre-flight at open (session.rs) calls the authenticator + // once and hands that value to the first request, so there is exactly + // one call per request: the first request (the feature-flag GET when + // configured, else session open) carries tok-1 and every request a + // distinct value. + seen := s.requests() + require.Len(t, seen, tc.want, "[feature-flag GET,] session, 3x (statement + close), session close") + require.Equal(t, int(calls.Load()), len(seen), "one authenticator call per request, no kernel cache") + require.True(t, strings.HasSuffix(seen[0].path, tc.firstPath), "first request %s %s", seen[0].method, seen[0].path) + require.Equal(t, "Bearer tok-1", seen[0].authorization, "the first request reuses the pre-flight value") + tokens := map[string]bool{} + for i, r := range seen { + require.False(t, tokens[r.authorization], "request %d reused %s", i, r.authorization) + tokens[r.authorization] = true + require.Equal(t, "probe", r.probe) + require.Contains(t, r.userAgent, "ddf-driver-ua", "provider must not override User-Agent") + } + }) + } +} + +// AC-P1: the bridge adds no requests: the same workload sends exactly the +// requests the kernel PAT path sends. +func TestExternalAuthNoExtraRequests(t *testing.T) { + workload := func(s *authServer, k *KernelBackend) []string { + require.NoError(t, k.OpenSession(context.Background())) + for i := 0; i < 3; i++ { + require.NoError(t, runStatement(t, k, context.Background(), "SELECT 1")) + } + s.waitForCloses(t, 3) + require.NoError(t, k.CloseSession(context.Background())) + var out []string + for _, r := range s.requests() { + out = append(out, r.method+" "+r.path) + } + sort.Strings(out) // statement closes are fire-and-forget, so order varies + return out + } + patServer := newAuthServer(t) + pat := patServer.backend(nil) + pat.cfg.Auth = Auth{Mode: AuthPAT, Token: "dapi-ddf"} + external := newAuthServer(t) + got := workload(external, external.backend(func(r *http.Request) error { + r.Header.Set("Authorization", "Bearer dapi-ddf") + return nil + })) + require.Equal(t, workload(patServer, pat), got) +} + +// AC-4: an authenticator error fails open fast with its message and nothing is sent. +func TestExternalAuthErrorAtOpen(t *testing.T) { + s := newAuthServer(t) + var calls atomic.Int32 + k := s.backend(func(*http.Request) error { + calls.Add(1) + return errors.New("ddf-authenticator-broken") + }) + k.cfg.Retry = nil // the kernel's default retry policy: a provider error is still not retried + err := k.OpenSession(context.Background()) + require.ErrorContains(t, err, "ddf-authenticator-broken") + require.Equal(t, int32(1), calls.Load(), "fail fast: one call, no retry (Thrift retried 3x)") + require.Empty(t, s.requests(), "nothing sent without a credential") +} + +// AC-4: a failure after a successful open fails only that operation, without a +// retry of the authenticator. The session stays valid (conn.IsValid, so +// database/sql keeps the pooled conn) and the next operation reuses it. +func TestExternalAuthErrorMidSession(t *testing.T) { + s := newAuthServer(t) + var calls atomic.Int32 + var fail atomic.Bool + k := s.backend(func(r *http.Request) error { + calls.Add(1) + if fail.Load() { + return errors.New("ddf-mid-session-failure") + } + r.Header.Set("Authorization", "Bearer ok") + return nil + }) + k.cfg.Retry = nil // the kernel's default retry policy: a provider error is still not retried + require.NoError(t, k.OpenSession(context.Background())) + require.NoError(t, runStatement(t, k, context.Background(), "SELECT 1")) + s.waitForCloses(t, 1) + fail.Store(true) + before, sent := calls.Load(), len(s.requests()) + err := runStatement(t, k, context.Background(), "SELECT 1") + require.ErrorContains(t, err, "ddf-mid-session-failure") + require.Equal(t, before+1, calls.Load(), "fail fast: one call, no retry loop") + require.Equal(t, sent, len(s.requests()), "nothing sent with a missing credential") + require.True(t, k.SessionValid(), "a local provider failure must not evict the session") + fail.Store(false) + require.NoError(t, runStatement(t, k, context.Background(), "SELECT 1")) + s.waitForCloses(t, 2) + require.NoError(t, k.CloseSession(context.Background())) + opens := 0 + for _, r := range s.requests() { + if r.method == http.MethodPost && strings.HasSuffix(r.path, "/sessions") { + opens++ + } + } + require.Equal(t, 1, opens, "recovery reuses the same server session") +} + +// AC-3: header values the kernel cannot send fail the request and are never echoed. +func TestExternalAuthRejectsInvalidValues(t *testing.T) { + for _, value := range []string{"Bearer secret\r\nX-Evil: 1", "Bearer secret\x00tail"} { + t.Run(fmt.Sprintf("%q", value[len(value)-5:]), func(t *testing.T) { + s := newAuthServer(t) + k := s.backend(func(r *http.Request) error { + r.Header["Authorization"] = []string{value} + return nil + }) + err := k.OpenSession(context.Background()) + require.Error(t, err) + require.NotContains(t, err.Error(), "secret") + for _, r := range s.requests() { + require.NotContains(t, r.authorization, "secret") + } + }) + } +} + +// AC-6: the driver's own federation wrapper runs inside the bridge: an RFC 8693 +// exchange per request (Go's Thrift cadence), the exchanged token on the wire, +// client_id forwarded, fallback to the original token on refusal, and no second +// exchange by the kernel. +func TestExternalAuthFederation(t *testing.T) { + for _, tc := range []struct { + name string + refuse bool + clientID string + }{ + {name: "exchange success"}, + {name: "exchange success with client id", clientID: "ddf-client"}, + {name: "refused exchange falls back", refuse: true}, + } { + t.Run(tc.name, func(t *testing.T) { + var exchanges atomic.Int32 + var badExchange atomic.Value + oidc := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + n := exchanges.Add(1) + _ = r.ParseForm() + if r.URL.Path != "/oidc/v1/token" || r.Form.Get("grant_type") != "urn:ietf:params:oauth:grant-type:token-exchange" || + !strings.HasPrefix(r.Form.Get("subject_token"), "eyJ") || r.Form.Get("client_id") != tc.clientID { + badExchange.Store(fmt.Sprintf("%s grant=%s client_id=%q", r.URL.Path, r.Form.Get("grant_type"), r.Form.Get("client_id"))) + } + if tc.refuse { + http.Error(w, `{"error":"invalid_grant"}`, http.StatusBadRequest) + return + } + _, _ = fmt.Fprintf(w, `{"access_token":"exchanged-%d","token_type":"Bearer","expires_in":3600}`, n) + })) + defer oidc.Close() + + var subjects atomic.Int32 + base := tokenprovider.NewExternalTokenProvider(func() (string, error) { + return foreignJWT(int(subjects.Add(1))), nil + }) + var provider tokenprovider.TokenProvider = tokenprovider.NewFederationProvider(base, oidc.URL) + if tc.clientID != "" { + provider = tokenprovider.NewFederationProviderWithClientID(base, oidc.URL, tc.clientID) + } + authr := tokenprovider.NewAuthenticator(provider) + + s := newAuthServer(t) + k := s.backend(authr.Authenticate) + require.NoError(t, k.OpenSession(context.Background())) + require.NoError(t, runStatement(t, k, context.Background(), "SELECT 1")) + s.waitForCloses(t, 1) + require.NoError(t, k.CloseSession(context.Background())) + + // The pre-flight value serves session open (see + // TestExternalAuthPerRequestHeaders), so one exchange per request. + require.Nil(t, badExchange.Load(), "unexpected exchange request") + seen := s.requests() + require.Len(t, seen, 4, "session, statement, statement close, session close") + require.Equal(t, int(exchanges.Load()), len(seen), "one driver exchange per request, none by the kernel") + require.Equal(t, int(subjects.Load()), len(seen), "base token fetched per request (no cache, as on Thrift)") + want := map[string]bool{} + for n := 1; n <= len(seen); n++ { + if tc.refuse { + want["Bearer "+foreignJWT(n)] = true + } else { + want[fmt.Sprintf("Bearer exchanged-%d", n)] = true + } + } + for i, r := range seen { + require.True(t, want[r.authorization], "request %d %s carried %.40s", i, r.path, r.authorization) + delete(want, r.authorization) + } + }) + } +} + +// foreignJWT is an unsigned JWT from an issuer other than the workspace, which +// the federation wrapper exchanges. n makes each token distinct. +func foreignJWT(n int) string { + enc := base64.RawURLEncoding.EncodeToString + return enc([]byte(`{"alg":"none","typ":"JWT"}`)) + "." + + enc([]byte(fmt.Sprintf(`{"iss":"https://idp.example","sub":"ddf-subject","jti":"%d","exp":4102444800}`, n))) + "." +} + +// AC-8: parallel connections share one authenticator through cgo handles without +// deadlock, and cancelling a running statement sends a cancel that carries the +// provider credential. +func TestExternalAuthConcurrencyAndCancel(t *testing.T) { + s := newAuthServer(t) + var calls atomic.Int32 + authr := authenticatorFunc(func(r *http.Request) error { + r.Header.Set("Authorization", fmt.Sprintf("Bearer tok-%d", calls.Add(1))) + return nil + }) + var wg sync.WaitGroup + errs := make(chan error, 8) + for i := 0; i < 4; i++ { + wg.Add(1) + go func() { + defer wg.Done() + k := s.backend(authr) + if err := k.OpenSession(context.Background()); err != nil { + errs <- err + return + } + errs <- runStatement(t, k, context.Background(), "SELECT 1") + errs <- k.CloseSession(context.Background()) + }() + } + done := make(chan struct{}) + go func() { wg.Wait(); close(done) }() + select { + case <-done: + case <-time.After(30 * time.Second): + t.Fatal("parallel connections deadlocked") + } + close(errs) + for err := range errs { + require.NoError(t, err) + } + + k := s.backend(authr) + require.NoError(t, k.OpenSession(context.Background())) + ctx, cancel := context.WithTimeout(context.Background(), 500*time.Millisecond) + defer cancel() + require.Error(t, runStatement(t, k, ctx, "SELECT SLOW")) + require.NoError(t, k.CloseSession(context.Background())) + var cancelAuth string + for _, r := range s.requests() { + if strings.HasSuffix(r.path, "/statements/slow/cancel") { + cancelAuth = r.authorization + } + } + require.True(t, strings.HasPrefix(cancelAuth, "Bearer tok-"), "cancel request carries the provider credential, got %q", cancelAuth) +} + +// The production setter on an unopened config: freeing the config runs the +// kernel's release callback, which deletes the handle. +func TestSetAuthExternal(t *testing.T) { + authr := authenticatorFunc(func(*http.Request) error { return nil }) + require.NoError(t, trySetAuth(Auth{Mode: AuthExternal, Authenticator: authr, RequestURL: "https://h.example:443/p"})) +} diff --git a/internal/backend/kernel/auth_test.go b/internal/backend/kernel/auth_test.go new file mode 100644 index 000000000..9a53ead00 --- /dev/null +++ b/internal/backend/kernel/auth_test.go @@ -0,0 +1,88 @@ +package kernel + +import ( + "errors" + "net/http" + "sort" + "testing" + + "github.com/stretchr/testify/require" +) + +type authenticatorFunc func(*http.Request) error + +func (f authenticatorFunc) Authenticate(r *http.Request) error { return f(r) } + +func TestExternalHeaders(t *testing.T) { + const url = "https://h.example:443/sql/1.0/warehouses/abc" + providerErr := errors.New("provider failed") + cases := []struct { + name string + set func(*http.Request) error + want [][2]string + wantErr string + is error + }{ + { + name: "authorization and extra headers", + set: func(r *http.Request) error { + r.Header.Set("Authorization", "Bearer tok-1") + r.Header.Set("X-Ddf-Probe", "probe") + r.Header.Add("X-Multi", "a") + r.Header.Add("X-Multi", "b") + return nil + }, + want: [][2]string{{"Authorization", "Bearer tok-1"}, {"X-Ddf-Probe", "probe"}, {"X-Multi", "a"}, {"X-Multi", "b"}}, + }, + {name: "no headers", set: func(*http.Request) error { return nil }}, + {name: "authenticator error is returned unchanged", set: func(*http.Request) error { return providerErr }, is: providerErr}, + { + name: "NUL in a value is rejected without echoing it", + set: func(r *http.Request) error { r.Header["Authorization"] = []string{"Bearer secret\x00tail"}; return nil }, + wantErr: `header "Authorization" with a NUL byte`, + }, + { + name: "NUL in a name is rejected", + set: func(r *http.Request) error { r.Header["X-Bad\x00"] = []string{"v"}; return nil }, + wantErr: "with a NUL byte", + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + var seen *http.Request + got, err := externalHeaders(authenticatorFunc(func(r *http.Request) error { + seen = r + return tc.set(r) + }), url) + require.NotNil(t, seen, "authenticator must be called") + require.Equal(t, http.MethodPost, seen.Method) + require.Equal(t, url, seen.URL.String()) + switch { + case tc.is != nil: + require.ErrorIs(t, err, tc.is) + case tc.wantErr != "": + require.ErrorContains(t, err, tc.wantErr) + require.NotContains(t, err.Error(), "secret") + default: + require.NoError(t, err) + sort.Slice(got, func(i, j int) bool { return got[i][0] < got[j][0] }) + require.Equal(t, tc.want, got) + } + }) + } +} + +func TestExternalHeadersFreshRequestPerCall(t *testing.T) { + calls := 0 + authr := authenticatorFunc(func(r *http.Request) error { + calls++ + require.Empty(t, r.Header, "each call starts from a fresh request") + r.Header.Set("Authorization", "Bearer tok") + return nil + }) + for i := 0; i < 3; i++ { + _, err := externalHeaders(authr, "https://h.example:443/p") + require.NoError(t, err) + } + require.Equal(t, 3, calls) +} diff --git a/internal/backend/kernel/backend.go b/internal/backend/kernel/backend.go index 47bb2800c..bfb68a017 100644 --- a/internal/backend/kernel/backend.go +++ b/internal/backend/kernel/backend.go @@ -624,7 +624,8 @@ func describeRetry(r *RetryConfig) string { // kernel_session_config_set_auth_* call (M2M scopes go through set_oauth_scopes). // PAT and M2M are plain value setters; U2M records the client id / redirect port / // scopes and the kernel owns the browser (PKCE) flow, started when the session -// opens. Empty string args are passed as NULL so the kernel applies its own +// opens; External registers the driver authenticator as a per-request callback +// (see setAuthExternal). Empty string args are passed as NULL so the kernel applies its own // defaults (e.g. U2M's public client / default port). func (k *KernelBackend) setAuth(cfg *C.KernelSessionConfig) error { switch k.cfg.Auth.Mode { @@ -671,6 +672,10 @@ func (k *KernelBackend) setAuth(cfg *C.KernelSessionConfig) error { }); err != nil { return fmt.Errorf("kernel: set_u2m_token_cache_config: %w", toConnError(err)) } + case AuthExternal: + if err := setAuthExternal(cfg, k.cfg.Auth.Authenticator, k.cfg.Auth.RequestURL); err != nil { + return fmt.Errorf("kernel: set_auth_external: %w", toConnError(err)) + } default: // AuthPAT tok := newCStr(k.cfg.Auth.Token) defer tok.free() diff --git a/internal/backend/kernel/errors_classify.go b/internal/backend/kernel/errors_classify.go index 8eb605bab..690ae0dda 100644 --- a/internal/backend/kernel/errors_classify.go +++ b/internal/backend/kernel/errors_classify.go @@ -133,10 +133,14 @@ func isBadConnection(code int) bool { // isSessionFatal reports whether the connection must be evicted. Missing or // invalid session handles are fatal; other missing resources or invalid -// arguments leave the session usable. +// arguments leave the session usable. A custom credentials provider failure is +// not fatal: it is raised locally before the request is sent, so the server +// session is intact and only that operation fails, as on Thrift. func isSessionFatal(ke *KernelError) bool { switch ke.Code { - case statusUnauthenticated, statusUnavailable, statusNetworkError: + case statusUnauthenticated: + return !isLocalProviderFailure(ke) + case statusUnavailable, statusNetworkError: return true case statusNotFound: return strings.Contains(strings.ToLower(ke.Message), "session does not exist") @@ -147,6 +151,14 @@ func isSessionFatal(ke *KernelError) bool { } } +// isLocalProviderFailure reports whether an Unauthenticated error came from the +// kernel's custom credentials provider bridge (the callback failed or returned +// headers the kernel rejects) rather than from the server: the kernel names the +// provider in the message, and no HTTP response was received. +func isLocalProviderFailure(ke *KernelError) bool { + return ke.HTTPStatus == 0 && strings.Contains(strings.ToLower(ke.Message), "custom credentials provider") +} + // isUserFault reports whether a status code is a user/query fault (a bad SQL // statement or a bad argument) rather than an infrastructure problem. Used to // pick the log level for a kernel-call failure: user faults are routine — a diff --git a/internal/backend/kernel/errors_classify_test.go b/internal/backend/kernel/errors_classify_test.go index 3c132dff1..abcd7e4d8 100644 --- a/internal/backend/kernel/errors_classify_test.go +++ b/internal/backend/kernel/errors_classify_test.go @@ -89,6 +89,29 @@ func TestIsSessionFatalInvalidSessionHandle(t *testing.T) { } } +// A custom credentials provider failure is local (nothing was sent), so the +// session survives; a server-side 401 still evicts. +func TestIsSessionFatalCustomProviderFailure(t *testing.T) { + cases := []struct { + name string + err *KernelError + want bool + }{ + {"provider failed", &KernelError{Code: statusUnauthenticated, Message: "Custom credentials provider failed: ddf-broken"}, false}, + {"provider returned invalid value", &KernelError{Code: statusUnauthenticated, Message: "Custom credentials provider returned an invalid value for header \"Authorization\""}, false}, + {"server 401", &KernelError{Code: statusUnauthenticated, Message: "HTTP 401: Credential was not sent", HTTPStatus: 401}, true}, + {"server echoes provider text", &KernelError{Code: statusUnauthenticated, Message: "HTTP 401: custom credentials provider token expired", HTTPStatus: 401}, true}, + {"provider text on another code", &KernelError{Code: statusNetworkError, Message: "Custom credentials provider failed"}, true}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + if got := isSessionFatal(tc.err); got != tc.want { + t.Errorf("isSessionFatal(%v) = %v, want %v", tc.err, got, tc.want) + } + }) + } +} + func TestIsSessionFatalNotFound(t *testing.T) { cases := []struct { name string diff --git a/internal/backend/kernel/include/databricks_kernel.h b/internal/backend/kernel/include/databricks_kernel.h index c73dbfbd2..01fd49195 100644 --- a/internal/backend/kernel/include/databricks_kernel.h +++ b/internal/backend/kernel/include/databricks_kernel.h @@ -231,8 +231,8 @@ typedef struct kernel_result_stream_canceller_t kernel_result_stream_canceller_t * * Build a config, set exactly one connection form and exactly one auth * form, then hand it to `kernel_session_open` (which consumes it). Only - * PAT, OAuth M2M, and OAuth U2M (interactive browser flow) auth are - * exposed over the C ABI. + * PAT, OAuth M2M, OAuth U2M (interactive browser flow) and a host + * credentials callback are exposed over the C ABI. */ KernelStatusCode kernel_session_config_new(KernelSessionConfig** out); void kernel_session_config_free(KernelSessionConfig* config); @@ -313,6 +313,35 @@ KernelStatusCode kernel_session_config_set_auth_azure_sp(KernelSessionConfig* co const char* azure_tenant_id, const char* azure_workspace_resource_id); +/* Host credentials callback. The kernel calls `callback` once per + * authenticated request (retries included, no kernel cache). The callback adds + * headers with kernel_auth_headers_add (usually `Authorization` plus any extra + * headers), which replace custom headers of the same name, and returns 0. Any + * other return fails that request with + * KernelStatusCode_Unauthenticated and no retry; call + * kernel_auth_headers_set_error first to give the reason (no credentials). The + * kernel copies every string before the callback returns. Values with CR, LF or + * NUL fail the request; User-Agent, Content-Type, Content-Length, Host, + * Transfer-Encoding, Connection and x-databricks-org-id are ignored. The + * kernel's token-federation exchange does not run for this mode, and + * set_identity_federation_client_id does not apply to it. + * + * The callback runs on kernel threads, possibly concurrently, and must not call + * kernel entry points other than kernel_auth_headers_*. `release` (may be NULL) + * is called exactly once with `user_data` when the kernel no longer needs it: + * after the session is closed and dropped, when the config is freed without + * opening, or when a later set_auth_* call replaces this one. */ +typedef struct KernelAuthHeaders KernelAuthHeaders; +typedef int32_t (*KernelAuthHeadersCallback)(void* user_data, KernelAuthHeaders* headers); +typedef void (*KernelAuthReleaseCallback)(void* user_data); +KernelStatusCode kernel_session_config_set_auth_external(KernelSessionConfig* config, + KernelAuthHeadersCallback callback, + KernelAuthReleaseCallback release, + void* user_data); +KernelStatusCode kernel_auth_headers_add(KernelAuthHeaders* headers, const char* name, + const char* value); +KernelStatusCode kernel_auth_headers_set_error(KernelAuthHeaders* headers, const char* message); + /* Optional SP-wide Workload Identity Federation client id used by mandatory * token exchange. Unset selects BYOT / account-wide WIF. */ KernelStatusCode @@ -487,6 +516,32 @@ KernelStatusCode kernel_session_config_set_tls_client_certificate( KernelSessionConfig* config, const uint8_t* cert_pem, size_t cert_len, const uint8_t* key_pem, size_t key_len); +/* Enable or disable TLS certificate-revocation checking (default: off). + * + * Supported only on Windows with the tls-rustls backend, where Windows CryptoAPI + * checks the revocation of the chain it builds for the server certificate, after + * webpki has verified the chain. A revoked certificate is always rejected. + * `accept_undetermined` governs a status that cannot be determined (a fetch + * failure or timeout, an offline status, a partial chain): false rejects it + * (strict), true accepts it. `check_revocation` false disables the check whatever + * `accept_undetermined` says. Revocation is also skipped when the self-signed + * setter is set. + * + * CRL and OCSP retrieval uses Windows networking and proxy settings, not the + * kernel's proxy configuration, and Windows caches the results. The check is + * synchronous: it blocks the calling thread's TLS handshake until CryptoAPI + * returns, so a connect or operation timeout can be exceeded by up to the + * revocation budget (about 10 s for CRL and OCSP retrieval in total, shared by a + * handshake's one or two chain builds; AIA and other chain-building fetches are + * bounded per URL, not in total). Session + * resumption is disabled while checking is on. + * + * Requesting it on any other platform, or on tls-native, makes opening a session + * fail with InvalidArgument, and the error names the unsupported platform or + * backend. So does requesting it for a host that is not https. */ +KernelStatusCode kernel_session_config_set_tls_certificate_revocation( + KernelSessionConfig* config, bool check_revocation, bool accept_undetermined); + /* Configure the HTTP retry / backoff policy. `min_wait_ms` / `max_wait_ms` * are the backoff-wait bounds between attempts (the wait is exponential * with jitter, clamped to this range); `max_retries` is the number of diff --git a/kernel_closed_conn_test.go b/kernel_closed_conn_test.go index efadf5d7d..133b8e18c 100644 --- a/kernel_closed_conn_test.go +++ b/kernel_closed_conn_test.go @@ -7,6 +7,7 @@ import ( "crypto/tls" "database/sql" "database/sql/driver" + "errors" "io" "net" "net/http" @@ -15,6 +16,7 @@ import ( "sync/atomic" "testing" + "github.com/databricks/databricks-sql-go/v2/auth/tokenprovider" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -93,6 +95,64 @@ func TestKernelClosedConnRejectsStatementsWithoutRequests(t *testing.T) { assert.Equal(t, int32(0), statements.Load()) } +// AC-4: a transient custom-provider failure fails only that statement. The pooled +// conn stays valid, so the next statement reuses it and its server session. +func TestKernelCustomProviderFailureKeepsPooledSession(t *testing.T) { + ca, caKey, caPEM := makeMTLSTestCA(t) + serverCert := makeMTLSTestLeaf(t, ca, caKey, "127.0.0.1", net.ParseIP("127.0.0.1")) + var creates, statements atomic.Int32 + srv := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + path := strings.TrimSuffix(r.URL.Path, "/") + w.Header().Set("Content-Type", "application/json") + switch { + case r.Method == http.MethodPost && strings.HasSuffix(path, "/sessions"): + creates.Add(1) + _, _ = io.WriteString(w, `{"session_id":"provider-session"}`) + case r.Method == http.MethodPost && strings.HasSuffix(path, "/statements"): + statements.Add(1) + _, _ = io.WriteString(w, `{"statement_id":"s","status":{"state":"SUCCEEDED"},"manifest":{"format":"ARROW_STREAM","total_chunk_count":0,"total_row_count":0,"schema":{"column_count":1,"columns":[{"name":"x","type_name":"INT","type_text":"INT","position":0}]}}}`) + case r.Method == http.MethodDelete: + _, _ = io.WriteString(w, `{}`) + default: // feature flags + http.NotFound(w, r) + } + })) + srv.TLS = &tls.Config{Certificates: []tls.Certificate{serverCert.tlsCert}, MinVersion: tls.VersionTLS12} + srv.StartTLS() + t.Cleanup(srv.Close) + + var fail atomic.Bool + connector, err := NewConnector( + WithServerHostname(srv.Listener.Addr().String()), + WithHTTPPath("/sql/1.0/warehouses/hermetic"), + WithAuthenticator(tokenprovider.NewAuthenticator(tokenprovider.NewExternalTokenProvider(func() (string, error) { + if fail.Load() { + return "", errors.New("ddf-transient-provider-failure") + } + return "dapi-hermetic-placeholder", nil + }))), + WithUseKernel(true), + WithRetries(-1, 0, 0), + WithKernelTrustedCerts(caPEM), + ) + require.NoError(t, err) + db := sql.OpenDB(connector) + t.Cleanup(func() { _ = db.Close() }) + db.SetMaxOpenConns(1) + ctx := context.Background() + + _, err = db.ExecContext(ctx, "SELECT 1") + require.NoError(t, err) + fail.Store(true) + _, err = db.ExecContext(ctx, "SELECT 1") + require.ErrorContains(t, err, "ddf-transient-provider-failure") + fail.Store(false) + _, err = db.ExecContext(ctx, "SELECT 1") + require.NoError(t, err) + assert.Equal(t, int32(1), creates.Load(), "the pooled conn and its session survive the provider failure") + assert.Equal(t, int32(2), statements.Load(), "nothing sent for the failed statement") +} + func TestKernelDeadSessionRejectsPinnedConnWithoutRequests(t *testing.T) { cases := []struct { name string diff --git a/kernel_config.go b/kernel_config.go index a7c9eabfb..f1e685327 100644 --- a/kernel_config.go +++ b/kernel_config.go @@ -88,10 +88,8 @@ func validateKernelConfigContext(ctx context.Context, cfg *config.Config) (kerne return kernel.Auth{}, fmt.Errorf("databricks: a custom WithTransport (RoundTripper) is %w "+ "(the kernel uses its own HTTP stack); use the default (Thrift) backend", dbsqlerr.ErrNotSupportedByKernel) } - // Auth: resolve the kernel auth form (PAT / OAuth M2M / U2M) off cfg.Authenticator, - // the single source of truth. resolveKernelAuth rejects unsupported authenticators - // loudly so the failure names the cause instead of surfacing as an opaque - // Unauthenticated. + // Auth: resolve the kernel auth form (PAT / OAuth M2M / U2M / External) off + // cfg.Authenticator, the single source of truth. kauth, err := resolveKernelAuthContext(ctx, cfg) if err != nil { return kernel.Auth{}, err @@ -399,22 +397,13 @@ func resolveKernelProxy(cfg *config.Config, kc *kernel.Config) { // satisfy structurally: // - implements M2MCredentialsProvider → M2M (client id + secret) // - implements U2MCredentialsProvider → U2M (browser/PKCE; kernel-owned flow) -// - federated token provider → PAT resolved once from the provider // - PAT / nil / noop → PAT (from AccessToken or a *pat.PATAuth) -// - anything else → rejected loudly (token-provider / external -// / static), so the failure names the cause instead of surfacing as -// an opaque Unauthenticated. -func resolveKernelAuthContext(ctx context.Context, cfg *config.Config) (kernel.Auth, error) { +// - anything else (custom authenticator, token-provider / external / static / +// federated token provider) → External: the kernel calls Authenticate on a +// throwaway request for every HTTP request, as the Thrift transport does, so +// the authenticator's own caching, refresh and federation exchange apply. +func resolveKernelAuthContext(_ context.Context, cfg *config.Config) (kernel.Auth, error) { switch a := cfg.Authenticator.(type) { - case *federatedTokenAuthenticator: - token, err := a.provider.GetToken(ctx) - if err != nil { - return kernel.Auth{}, fmt.Errorf("databricks: failed to get a federated token for the kernel backend: %w", err) - } - if token == nil || token.AccessToken == "" { - return kernel.Auth{}, errors.New("databricks: the federated token provider returned an empty token") - } - return kernel.Auth{Mode: kernel.AuthPAT, Token: token.AccessToken, ClientID: a.clientID}, nil case kernel.M2MCredentialsProvider: clientID, clientSecret := a.M2MCredentials() return kernel.Auth{Mode: kernel.AuthM2M, ClientID: clientID, ClientSecret: clientSecret, Scopes: a.M2MScopes()}, nil @@ -461,16 +450,11 @@ func resolveKernelAuthContext(ctx context.Context, cfg *config.Config) (kernel.A } return kernel.Auth{Mode: kernel.AuthPAT, Token: token}, nil default: - // Unsupported authenticator: wrap ErrNotSupportedByKernel so a caller can - // detect the "kernel can't honor this auth" case with errors.Is and fall back - // to the default backend, rather than substring-matching this message. This is - // the same contract every other unsupported kernel option in this file follows - // and that doc.go advertises. (The empty-PAT case above is intentionally NOT - // wrapped — a missing token is misconfiguration to fix, not a feature the - // kernel can't honor.) - return kernel.Auth{}, fmt.Errorf("databricks: this authenticator is %w; "+ - "PAT (WithAccessToken) and OAuth M2M/U2M (WithClientCredentials / authType) are supported, but "+ - "custom token-provider and external/static authenticators are not — "+ - "use PAT/OAuth or the default (Thrift) backend", dbsqlerr.ErrNotSupportedByKernel) + // The kernel always connects over https; the URL matches the Thrift endpoint. + return kernel.Auth{ + Mode: kernel.AuthExternal, + Authenticator: a, + RequestURL: fmt.Sprintf("https://%s:%d%s", cfg.Host, cfg.Port, cfg.HTTPPath), + }, nil } } diff --git a/kernel_config_test.go b/kernel_config_test.go index 8421b8473..1f0e7d1aa 100644 --- a/kernel_config_test.go +++ b/kernel_config_test.go @@ -18,8 +18,8 @@ import ( ) // nonPATAuth stands in for any non-PAT, non-OAuth authenticator (token-provider / -// external / static) — the kernel backend must reject it. It implements neither -// kernel.M2MCredentialsProvider nor kernel.U2MCredentialsProvider. +// external / static) — the kernel backend routes it through the External bridge. It +// implements neither kernel.M2MCredentialsProvider nor kernel.U2MCredentialsProvider. type nonPATAuth struct{} func (nonPATAuth) Authenticate(*http.Request) error { return nil } @@ -203,45 +203,59 @@ func TestValidateKernelConfig(t *testing.T) { } }) - t.Run("federated provider supplies PAT auth", func(t *testing.T) { - providerErr := errors.New("provider failure") + t.Run("provider APIs resolve to the per-request External bridge", func(t *testing.T) { + // Each provider API routes its authenticator to the kernel unchanged; nothing + // is resolved at connect (no one-time token snapshot), so the provider is only + // called by the kernel, once per request. for _, tc := range []struct { - name, token, clientID string - providerErr error + name string + apply func(c *config.Config, getToken func() (string, error)) }{ - {"account-wide", "subject-token", "", nil}, - {"SP-wide", "subject-token", "federation-client", nil}, - {"provider error", "", "", providerErr}, - {"empty token", "", "", nil}, + {"WithAuthenticator(custom)", func(c *config.Config, getToken func() (string, error)) { + WithAuthenticator(tokenprovider.NewAuthenticator(tokenprovider.NewExternalTokenProvider(getToken)))(c) + }}, + {"WithTokenProvider", func(c *config.Config, getToken func() (string, error)) { + WithTokenProvider(tokenprovider.NewExternalTokenProvider(getToken))(c) + }}, + {"WithExternalToken", func(c *config.Config, getToken func() (string, error)) { WithExternalToken(getToken)(c) }}, + {"WithFederatedTokenProvider", func(c *config.Config, getToken func() (string, error)) { + WithFederatedTokenProvider(tokenprovider.NewExternalTokenProvider(getToken))(c) + }}, + {"WithFederatedTokenProviderAndClientID", func(c *config.Config, getToken func() (string, error)) { + WithFederatedTokenProviderAndClientID(tokenprovider.NewExternalTokenProvider(getToken), "federation-client")(c) + }}, } { t.Run(tc.name, func(t *testing.T) { c := baseKernelConfig() c.AccessToken = "" calls := 0 - provider := tokenprovider.NewExternalTokenProvider(func() (string, error) { + tc.apply(c, func() (string, error) { calls++ - return tc.token, tc.providerErr + return fmt.Sprintf("tok-%d", calls), nil }) - if tc.clientID == "" { - WithFederatedTokenProvider(provider)(c) - } else { - WithFederatedTokenProviderAndClientID(provider, tc.clientID)(c) - } a, err := validateKernelConfig(c) - if tc.token == "" { - if err == nil || tc.providerErr != nil && !errors.Is(err, tc.providerErr) { - t.Fatalf("error = %v, want provider error %v", err, tc.providerErr) - } - return - } if err != nil { - t.Fatalf("federated provider should validate, got %v", err) + t.Fatalf("provider API should validate on the kernel path, got %v", err) + } + if a.Mode != kernel.AuthExternal || a.Authenticator != c.Authenticator { + t.Fatalf("auth = %+v, want External carrying cfg.Authenticator", a) + } + if want := "https://h.databricks.com:443/sql/1.0/warehouses/abc"; a.RequestURL != want { + t.Errorf("RequestURL = %q, want %q", a.RequestURL, want) } - if a.Mode != kernel.AuthPAT || a.Token != tc.token || a.ClientID != tc.clientID { - t.Errorf("auth = %+v, want PAT token=%q clientID=%q", a, tc.token, tc.clientID) + if calls != 0 { + t.Errorf("validateKernelConfig called the provider %d times, want 0 (no connect-time snapshot)", calls) } - if calls != 1 { - t.Errorf("validateKernelConfig resolved the provider: calls = %d, want 1", calls) + // The authenticator the kernel calls yields a fresh token each time + // (non-JWT tokens are never exchanged by the federation wrapper). + for want := 1; want <= 2; want++ { + req, _ := http.NewRequest(http.MethodPost, a.RequestURL, nil) + if err := a.Authenticator.Authenticate(req); err != nil { + t.Fatalf("Authenticate: %v", err) + } + if got := req.Header.Get("Authorization"); got != fmt.Sprintf("Bearer tok-%d", want) { + t.Errorf("Authorization = %q, want Bearer tok-%d", got, want) + } } }) } @@ -277,19 +291,16 @@ func TestValidateKernelConfig(t *testing.T) { } }) - t.Run("non-PAT/non-OAuth authenticator rejected", func(t *testing.T) { + t.Run("non-PAT/non-OAuth authenticator resolves to External", func(t *testing.T) { c := baseKernelConfig() c.AccessToken = "" c.Authenticator = nonPATAuth{} - _, err := validateKernelConfig(c) - if err == nil { - t.Fatal("expected an error for a custom token-provider/external/static authenticator") - } - // An unsupported authenticator is a "kernel can't honor this" rejection, so it - // must wrap ErrNotSupportedByKernel like every other unsupported option — the - // contract doc.go advertises for programmatic fallback via errors.Is. - if !errors.Is(err, dbsqlerr.ErrNotSupportedByKernel) { - t.Errorf("unsupported-auth rejection should wrap ErrNotSupportedByKernel, got %v", err) + a, err := validateKernelConfig(c) + if err != nil { + t.Fatalf("a custom authenticator should validate, got %v", err) + } + if a.Mode != kernel.AuthExternal || a.Authenticator != c.Authenticator { + t.Errorf("auth = %+v, want External carrying the custom authenticator", a) } }) From f4340497b6c000dd6f607abe8c5f2180c08ad328 Mon Sep 17 00:00:00 2001 From: Cathleen Yan <58714163+cathleeny@users.noreply.github.com> Date: Wed, 2 Dec 2026 20:23:16 +0000 Subject: [PATCH 2/6] fix(kernel): keep a port written in the host in the authenticator URL The request URL an external authenticator sees appended cfg.Port even when WithServerHostname already carried a port, so host "127.0.0.1:43337" became "https://127.0.0.1:43337:443/..." and every custom provider failed to parse it. A non-default port in the host now wins, as it does in the kernel's own endpoint, and is not appended a second time. Signed-off-by: Cathleen Yan <58714163+cathleeny@users.noreply.github.com> Co-authored-by: Isaac --- kernel_config.go | 19 +++++++++++++++++-- kernel_config_test.go | 24 ++++++++++++++++++++++++ 2 files changed, 41 insertions(+), 2 deletions(-) diff --git a/kernel_config.go b/kernel_config.go index f1e685327..1eeff26f6 100644 --- a/kernel_config.go +++ b/kernel_config.go @@ -4,6 +4,7 @@ import ( "context" "errors" "fmt" + "net" "net/url" "strconv" "strings" @@ -450,11 +451,25 @@ func resolveKernelAuthContext(_ context.Context, cfg *config.Config) (kernel.Aut } return kernel.Auth{Mode: kernel.AuthPAT, Token: token}, nil default: - // The kernel always connects over https; the URL matches the Thrift endpoint. return kernel.Auth{ Mode: kernel.AuthExternal, Authenticator: a, - RequestURL: fmt.Sprintf("https://%s:%d%s", cfg.Host, cfg.Port, cfg.HTTPPath), + RequestURL: kernelRequestURL(cfg), }, nil } } + +// kernelRequestURL is the URL an external authenticator sees for each kernel +// request: the Thrift endpoint URL (the kernel always connects over https). A +// non-default port already written in the host wins over cfg.Port, as in the +// kernel, so it is not appended a second time. +func kernelRequestURL(cfg *config.Config) string { + host := cfg.Host + if h, p, err := net.SplitHostPort(host); err == nil { + if p != "443" { + return "https://" + host + cfg.HTTPPath + } + host = h + } + return fmt.Sprintf("https://%s:%d%s", host, cfg.Port, cfg.HTTPPath) +} diff --git a/kernel_config_test.go b/kernel_config_test.go index 1f0e7d1aa..29dad7caa 100644 --- a/kernel_config_test.go +++ b/kernel_config_test.go @@ -5,6 +5,7 @@ import ( "errors" "fmt" "net/http" + "net/url" "reflect" "testing" "time" @@ -261,6 +262,29 @@ func TestValidateKernelConfig(t *testing.T) { } }) + t.Run("external authenticator RequestURL keeps a port written in the host", func(t *testing.T) { + for _, tc := range []struct{ host, want string }{ + {"127.0.0.1:43337", "https://127.0.0.1:43337/sql/1.0/warehouses/abc"}, + {"h.databricks.com:443", "https://h.databricks.com:443/sql/1.0/warehouses/abc"}, + {"[::1]:8443", "https://[::1]:8443/sql/1.0/warehouses/abc"}, + } { + c := baseKernelConfig() + c.AccessToken = "" + c.Host = tc.host + WithExternalToken(func() (string, error) { return "tok", nil })(c) + a, err := validateKernelConfig(c) + if err != nil { + t.Fatalf("host %q: %v", tc.host, err) + } + if a.RequestURL != tc.want { + t.Errorf("host %q: RequestURL = %q, want %q", tc.host, a.RequestURL, tc.want) + } + if _, err := url.Parse(a.RequestURL); err != nil { + t.Errorf("host %q: RequestURL does not parse: %v", tc.host, err) + } + } + }) + t.Run("last-applied auth wins: M2M then PAT resolves to PAT", func(t *testing.T) { // Regression for the auth-mode divergence: cfg.Authenticator is the single // source of truth, so setting an M2M authenticator and then a PAT (a later From 6e295b85e8835a1c4335c7fb72a5c3fdda7388ed Mon Sep 17 00:00:00 2001 From: Cathleen Yan <58714163+cathleeny@users.noreply.github.com> Date: Wed, 2 Dec 2026 22:20:24 +0000 Subject: [PATCH 3/6] Fix IPv6 authenticator request URLs Signed-off-by: Cathleen Yan <58714163+cathleeny@users.noreply.github.com> Co-authored-by: Isaac --- kernel_config.go | 2 +- kernel_config_test.go | 16 ++++++++++++---- 2 files changed, 13 insertions(+), 5 deletions(-) diff --git a/kernel_config.go b/kernel_config.go index 1eeff26f6..5894427e3 100644 --- a/kernel_config.go +++ b/kernel_config.go @@ -469,7 +469,7 @@ func kernelRequestURL(cfg *config.Config) string { if p != "443" { return "https://" + host + cfg.HTTPPath } - host = h + return "https://" + net.JoinHostPort(h, strconv.Itoa(cfg.Port)) + cfg.HTTPPath } return fmt.Sprintf("https://%s:%d%s", host, cfg.Port, cfg.HTTPPath) } diff --git a/kernel_config_test.go b/kernel_config_test.go index 29dad7caa..e6b0c0a68 100644 --- a/kernel_config_test.go +++ b/kernel_config_test.go @@ -263,14 +263,22 @@ func TestValidateKernelConfig(t *testing.T) { }) t.Run("external authenticator RequestURL keeps a port written in the host", func(t *testing.T) { - for _, tc := range []struct{ host, want string }{ - {"127.0.0.1:43337", "https://127.0.0.1:43337/sql/1.0/warehouses/abc"}, - {"h.databricks.com:443", "https://h.databricks.com:443/sql/1.0/warehouses/abc"}, - {"[::1]:8443", "https://[::1]:8443/sql/1.0/warehouses/abc"}, + for _, tc := range []struct { + host string + port int + want string + }{ + {"127.0.0.1:43337", 443, "https://127.0.0.1:43337/sql/1.0/warehouses/abc"}, + {"h.databricks.com:443", 443, "https://h.databricks.com:443/sql/1.0/warehouses/abc"}, + {"h.databricks.com:443", 8443, "https://h.databricks.com:8443/sql/1.0/warehouses/abc"}, + {"[::1]:443", 443, "https://[::1]:443/sql/1.0/warehouses/abc"}, + {"[::1]:443", 8443, "https://[::1]:8443/sql/1.0/warehouses/abc"}, + {"[::1]:8443", 443, "https://[::1]:8443/sql/1.0/warehouses/abc"}, } { c := baseKernelConfig() c.AccessToken = "" c.Host = tc.host + c.Port = tc.port WithExternalToken(func() (string, error) { return "tok", nil })(c) a, err := validateKernelConfig(c) if err != nil { From 1bb3dbe0a907d778103ff8e8f9d8948fa5d725bd Mon Sep 17 00:00:00 2001 From: Cathleen Yan <58714163+cathleeny@users.noreply.github.com> Date: Thu, 3 Dec 2026 21:48:42 +0000 Subject: [PATCH 4/6] fix(kernel): preserve authenticator error identity Signed-off-by: Cathleen Yan <58714163+cathleeny@users.noreply.github.com> Co-authored-by: Isaac --- CONNECTION_PARAMETERS.md | 10 +++-- internal/backend/kernel/auth_callback.go | 37 ++++++++++++++++--- internal/backend/kernel/auth_callback_test.go | 8 +++- internal/backend/kernel/backend.go | 8 ++-- internal/backend/kernel/errors_classify.go | 27 ++++++++++++-- .../backend/kernel/errors_classify_test.go | 30 +++++++++++++++ internal/backend/kernel/operation.go | 6 +-- internal/backend/kernel/rows.go | 4 +- 8 files changed, 106 insertions(+), 24 deletions(-) diff --git a/CONNECTION_PARAMETERS.md b/CONNECTION_PARAMETERS.md index 7111f0808..70ca536bc 100644 --- a/CONNECTION_PARAMETERS.md +++ b/CONNECTION_PARAMETERS.md @@ -66,12 +66,14 @@ Notes for the SEA/kernel backend: Thrift authenticator sees), and the `Authorization` and extra headers it sets are sent. `User-Agent`, `Content-Type`, `Content-Length`, `Host`, `Transfer-Encoding`, `Connection` and `x-databricks-org-id` are ignored, and a value with CR, LF or NUL fails - the request. The request context is `context.Background()`. + 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 with the error's message; Thrift retries - it under `WithRetries`. The connection and its session stay usable. The kernel also calls the authenticator once before its first - request at connect. +- 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 diff --git a/internal/backend/kernel/auth_callback.go b/internal/backend/kernel/auth_callback.go index 56803cbd8..32e794ebf 100644 --- a/internal/backend/kernel/auth_callback.go +++ b/internal/backend/kernel/auth_callback.go @@ -23,7 +23,9 @@ import "C" import ( "fmt" + "net/http" "runtime/cgo" + "sync/atomic" "unsafe" "github.com/databricks/databricks-sql-go/v2/auth" @@ -32,17 +34,40 @@ import ( // 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 + authr auth.Authenticator + url string + lastErr atomic.Pointer[authError] } -// setAuthExternal registers authr as the session's credentials callback. The +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, authr auth.Authenticator, url string) error { - h := cgo.NewHandle(&externalAuth{authr: authr, url: url}) +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 { @@ -66,7 +91,7 @@ func kernelAuthHeadersTrampoline(userData unsafe.Pointer, headers *C.KernelAuthH } }() ext := cgo.Handle(*(*C.uintptr_t)(userData)).Value().(*externalAuth) - pairs, err := externalHeaders(ext.authr, ext.url) + pairs, err := externalHeaders(ext, ext.url) if err != nil { setAuthHeadersError(headers, err.Error()) return 1 diff --git a/internal/backend/kernel/auth_callback_test.go b/internal/backend/kernel/auth_callback_test.go index 2e88db895..12aaf0973 100644 --- a/internal/backend/kernel/auth_callback_test.go +++ b/internal/backend/kernel/auth_callback_test.go @@ -215,13 +215,15 @@ func TestExternalAuthNoExtraRequests(t *testing.T) { func TestExternalAuthErrorAtOpen(t *testing.T) { s := newAuthServer(t) var calls atomic.Int32 + sentinel := errors.New("ddf-authenticator-broken") k := s.backend(func(*http.Request) error { calls.Add(1) - return errors.New("ddf-authenticator-broken") + return sentinel }) k.cfg.Retry = nil // the kernel's default retry policy: a provider error is still not retried err := k.OpenSession(context.Background()) require.ErrorContains(t, err, "ddf-authenticator-broken") + require.ErrorIs(t, err, sentinel) require.Equal(t, int32(1), calls.Load(), "fail fast: one call, no retry (Thrift retried 3x)") require.Empty(t, s.requests(), "nothing sent without a credential") } @@ -233,10 +235,11 @@ func TestExternalAuthErrorMidSession(t *testing.T) { s := newAuthServer(t) var calls atomic.Int32 var fail atomic.Bool + sentinel := errors.New("ddf-mid-session-failure") k := s.backend(func(r *http.Request) error { calls.Add(1) if fail.Load() { - return errors.New("ddf-mid-session-failure") + return sentinel } r.Header.Set("Authorization", "Bearer ok") return nil @@ -249,6 +252,7 @@ func TestExternalAuthErrorMidSession(t *testing.T) { before, sent := calls.Load(), len(s.requests()) err := runStatement(t, k, context.Background(), "SELECT 1") require.ErrorContains(t, err, "ddf-mid-session-failure") + require.ErrorIs(t, err, sentinel) require.Equal(t, before+1, calls.Load(), "fail fast: one call, no retry loop") require.Equal(t, sent, len(s.requests()), "nothing sent with a missing credential") require.True(t, k.SessionValid(), "a local provider failure must not evict the session") diff --git a/internal/backend/kernel/backend.go b/internal/backend/kernel/backend.go index 320820173..9ca7f0e2e 100644 --- a/internal/backend/kernel/backend.go +++ b/internal/backend/kernel/backend.go @@ -96,6 +96,7 @@ var kernelSessionSeq atomic.Uint64 // which may briefly outlive a client-timeout return while its cancel RPC ends. type KernelBackend struct { cfg Config + external *externalAuth session *C.kernel_session_t sessionID string valid bool @@ -346,7 +347,7 @@ func (k *KernelBackend) OpenSession(ctx context.Context) error { err := call(func() C.KernelStatusCode { return C.kernel_session_open(cfg, &sess) }) consumed = true if err != nil { - return fmt.Errorf("kernel: session_open: %w", toConnError(err)) + return fmt.Errorf("kernel: session_open: %w", k.external.wrapProviderFailure(toConnError(err))) } k.session = sess k.valid = true @@ -673,7 +674,8 @@ func (k *KernelBackend) setAuth(cfg *C.KernelSessionConfig) error { return fmt.Errorf("kernel: set_u2m_token_cache_config: %w", toConnError(err)) } case AuthExternal: - if err := setAuthExternal(cfg, k.cfg.Auth.Authenticator, k.cfg.Auth.RequestURL); err != nil { + k.external = &externalAuth{authr: k.cfg.Auth.Authenticator, url: k.cfg.Auth.RequestURL} + if err := setAuthExternal(cfg, k.external); err != nil { return fmt.Errorf("kernel: set_auth_external: %w", toConnError(err)) } default: // AuthPAT @@ -888,7 +890,7 @@ func (k *KernelBackend) CloseSession(ctx context.Context) error { err := call(func() C.KernelStatusCode { return C.kernel_session_close(k.session) }) k.session = nil k.valid = false - return toConnError(err) + return k.external.wrapProviderFailure(toConnError(err)) } // SessionValid backs conn.IsValid → pool eviction. No I/O; inspects state diff --git a/internal/backend/kernel/errors_classify.go b/internal/backend/kernel/errors_classify.go index 690ae0dda..a20af49be 100644 --- a/internal/backend/kernel/errors_classify.go +++ b/internal/backend/kernel/errors_classify.go @@ -151,14 +151,33 @@ func isSessionFatal(ke *KernelError) bool { } } -// isLocalProviderFailure reports whether an Unauthenticated error came from the -// kernel's custom credentials provider bridge (the callback failed or returned -// headers the kernel rejects) rather than from the server: the kernel names the -// provider in the message, and no HTTP response was received. +// isLocalProviderFailure reports whether the kernel's custom provider bridge +// failed before receiving an HTTP response. The text match depends on the kernel's +// "Custom credentials provider failed: ...", "Custom credentials provider returned +// an invalid header name ...", and "Custom credentials provider returned an invalid +// value for header ..." messages (src/auth/external.rs). The exact failed-message +// format is also used by wrapProviderFailure. TestKernelCustomProviderFailureKeepsPooledSession +// guards the eviction coupling when the kernel pin changes. func isLocalProviderFailure(ke *KernelError) bool { return ke.HTTPStatus == 0 && strings.Contains(strings.ToLower(ke.Message), "custom credentials provider") } +// wrapProviderFailure restores the original error only for the exact callback +// failure message emitted by the kernel. A concurrent or earlier failure with the +// same text can still attach the wrong error: the C callback has no request identity. +func wrapProviderFailure(err, providerErr error) error { + var ke *KernelError + if providerErr == nil || !errors.As(err, &ke) || ke.Code != statusUnauthenticated || !isLocalProviderFailure(ke) { + return err + } + const prefix = "Custom credentials provider failed: " + message := providerErr.Error() + if message == "" || ke.Message != prefix+message { + return err + } + return fmt.Errorf("%w: %w", err, providerErr) +} + // isUserFault reports whether a status code is a user/query fault (a bad SQL // statement or a bad argument) rather than an infrastructure problem. Used to // pick the log level for a kernel-call failure: user faults are routine — a diff --git a/internal/backend/kernel/errors_classify_test.go b/internal/backend/kernel/errors_classify_test.go index abcd7e4d8..02160c6b3 100644 --- a/internal/backend/kernel/errors_classify_test.go +++ b/internal/backend/kernel/errors_classify_test.go @@ -112,6 +112,36 @@ func TestIsSessionFatalCustomProviderFailure(t *testing.T) { } } +func TestWrapProviderFailure(t *testing.T) { + tests := []struct { + name, stored, message string + code int + httpStatus uint16 + want bool + }{ + {"exact", "token expired", "Custom credentials provider failed: token expired", statusUnauthenticated, 0, true}, + {"substring", "token", "Custom credentials provider failed: token expired", statusUnauthenticated, 0, false}, + {"empty", "", "Custom credentials provider failed: ", statusUnauthenticated, 0, false}, + {"extra context", "token", "Custom credentials provider failed: token (extra context)", statusUnauthenticated, 0, false}, + {"wrong prefix", "token", "other: Custom credentials provider failed: token", statusUnauthenticated, 0, false}, + {"HTTP response", "token", "Custom credentials provider failed: token", statusUnauthenticated, 401, false}, + {"wrong code", "token", "Custom credentials provider failed: token", statusNetworkError, 0, false}, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + original := errors.New(tc.stored) + ke := &KernelError{Code: tc.code, Message: tc.message, HTTPStatus: tc.httpStatus} + got := wrapProviderFailure(ke, original) + if errors.Is(got, original) != tc.want { + t.Fatalf("errors.Is(%v, original) = %v, want %v", got, !tc.want, tc.want) + } + if !errors.Is(got, ke) { + t.Fatalf("lost kernel error: %v", got) + } + }) + } +} + func TestIsSessionFatalNotFound(t *testing.T) { cases := []struct { name string diff --git a/internal/backend/kernel/operation.go b/internal/backend/kernel/operation.go index 7b3ccd225..517199469 100644 --- a/internal/backend/kernel/operation.go +++ b/internal/backend/kernel/operation.go @@ -223,13 +223,13 @@ func (k *KernelBackend) execute(ctx context.Context, req backend.ExecRequest) (b if ctx.Err() != nil { klogCtx(ctx, "Execute failed under cancelled ctx: kernelErr=%v ctxErr=%v", execErr, ctx.Err()) op.close() - return op, fmt.Errorf("kernel: execute cancelled: %w (kernel error: %w)", ctx.Err(), toStatementError(execErr)) + return op, fmt.Errorf("kernel: execute cancelled: %w (kernel error: %w)", ctx.Err(), k.external.wrapProviderFailure(toStatementError(execErr))) } klogCtx(ctx, "Execute failed: %v", execErr) // We still return the PLAIN error (toStatementError, never ErrBadConn), so the // conn is discarded without database/sql re-running the statement. op.close() - return op, fmt.Errorf("kernel: execute: %w", toStatementError(execErr)) + return op, fmt.Errorf("kernel: execute: %w", k.external.wrapProviderFailure(toStatementError(execErr))) } op.exec = exec // Capture the modified-row count and server query id now, while exec is live — @@ -381,7 +381,7 @@ func (o *kernelOp) Results(ctx context.Context, callbacks *dbsqlrows.TelemetryCa // leaking the statement / executed handle (and its server operation). o.backend.evictIfSessionFatal(err) o.close() - return nil, fmt.Errorf("kernel: get_result_stream: %w", toStatementError(err)) + return nil, fmt.Errorf("kernel: get_result_stream: %w", o.backend.external.wrapProviderFailure(toStatementError(err))) } return newKernelRows(ctx, o, stream, callbacks) } diff --git a/internal/backend/kernel/rows.go b/internal/backend/kernel/rows.go index b272df8ce..45a830eed 100644 --- a/internal/backend/kernel/rows.go +++ b/internal/backend/kernel/rows.go @@ -108,7 +108,7 @@ func newKernelRows(ctx context.Context, op *kernelOp, stream *C.kernel_result_st }); err != nil { op.backend.evictIfSessionFatal(err) r.Close() - return nil, fmt.Errorf("kernel: get_schema: %w", toStatementError(err)) + return nil, fmt.Errorf("kernel: get_schema: %w", op.backend.external.wrapProviderFailure(toStatementError(err))) } sch, err := cdata.ImportCArrowSchema((*cdata.CArrowSchema)(unsafe.Pointer(&csch))) if err != nil { @@ -314,7 +314,7 @@ func (r *kernelRows) nextBatch() error { return C.kernel_result_stream_next_batch(r.stream, &carr, &csch) }); err != nil { r.op.backend.evictIfSessionFatal(err) - return fmt.Errorf("kernel: next_batch: %w", toStatementError(err)) + return fmt.Errorf("kernel: next_batch: %w", r.op.backend.external.wrapProviderFailure(toStatementError(err))) } if probePending { return io.ErrNoProgress From a0592d5c32c765df8dbf3dcde2c27a6681391df1 Mon Sep 17 00:00:00 2001 From: Cathleen Yan <58714163+cathleeny@users.noreply.github.com> Date: Thu, 3 Dec 2026 23:43:43 +0000 Subject: [PATCH 5/6] Pin the kernel to merged #527 (6d6c1e4) Signed-off-by: Cathleen Yan <58714163+cathleeny@users.noreply.github.com> Co-authored-by: Isaac --- KERNEL_REV | 2 +- .../kernel/include/databricks_kernel.h | 63 ++++++++++++++++--- 2 files changed, 57 insertions(+), 8 deletions(-) diff --git a/KERNEL_REV b/KERNEL_REV index f2e9a9eb8..bf66d751f 100644 --- a/KERNEL_REV +++ b/KERNEL_REV @@ -1 +1 @@ -159a2ff0b69dd74e1b9bd98a4e03d6db47b142c8 +6d6c1e4eb70e3d5bebea75b76c5b19c459d9a467 diff --git a/internal/backend/kernel/include/databricks_kernel.h b/internal/backend/kernel/include/databricks_kernel.h index b5c8b642f..793885986 100644 --- a/internal/backend/kernel/include/databricks_kernel.h +++ b/internal/backend/kernel/include/databricks_kernel.h @@ -191,6 +191,18 @@ typedef struct KernelError { */ bool kernel_get_last_error(KernelError* out); +/* + * Details of the last error recorded on the calling thread. Strings are NULL + * when absent and valid until the next kernel call on that thread. + * - `_code`: string code such as `VOLUME_PATH_NOT_ALLOWED`. + * - `_local_os_error`: OS error number behind a local file error (errno, or + * a Windows error code on Windows), or 0. + * - `_local_path`: local path of a local file error. + */ +const char* kernel_get_last_error_code(void); +int32_t kernel_get_last_error_local_os_error(void); +const char* kernel_get_last_error_local_path(void); + /* ─── Opaque handles ────────────────────────────────────────────────── * * All handles are owned heap allocations on the Rust side; the C side @@ -322,7 +334,10 @@ KernelStatusCode kernel_session_config_set_auth_azure_sp(KernelSessionConfig* co * kernel_auth_headers_set_error first to give the reason (no credentials). The * kernel copies every string before the callback returns. Values with CR, LF or * NUL fail the request; User-Agent, Content-Type, Content-Length, Host, - * Transfer-Encoding, Connection and x-databricks-org-id are ignored. The + * Transfer-Encoding, Connection, Accept-Encoding, x-databricks-org-id and the + * per-request x-databricks-metadata-operation-type, + * x-databricks-sea-can-run-fully-sync and + * x-databricks-require-thrift-native-metadata are ignored. The * kernel's token-federation exchange does not run for this mode, and * set_identity_federation_client_id does not apply to it. * @@ -416,7 +431,9 @@ KernelStatusCode kernel_session_config_set_sea_response_compression_enabled( /* Configure the total timeout for one HTTP request, from connection start * through response-body completion. A separate 30s connection timeout also * applies, so connection establishment is bounded by the shorter limit. - * `request_timeout_ms == 0` keeps the kernel default (120s). */ + * `request_timeout_ms == 0` keeps the kernel default (120s). For Volume file + * transfers it is an idle limit: a transfer fails after this long without + * progress. */ KernelStatusCode kernel_session_config_set_request_timeout(KernelSessionConfig* config, uint64_t request_timeout_ms); @@ -657,10 +674,8 @@ KernelStatusCode kernel_session_config_set_u2m_token_cache_config(KernelSessionC * * Counterpart to kernel_session_config_set_session_conf: that one carries * SERVER session confs (ANSI_MODE, TIMEZONE, ...) to the SEA wire; this one - * sets CLIENT-SIDE knobs that tune how the kernel fetches, buffers, and - * post-processes results and are NEVER sent to the server. The two channels - * are deliberately separate (conflating them is what made a client flag - * masquerade as a rejected server conf). + * configures how the kernel requests, fetches, buffers, and post-processes + * results. These keys are kept out of the server session configuration. * * Key/value (rather than one typed setter per knob) so the signature never * changes as new result knobs are added, and so a host that already has DSN @@ -671,6 +686,9 @@ KernelStatusCode kernel_session_config_set_u2m_token_cache_config(KernelSessionC * Recognised keys (case-insensitive): * - "cloudfetch_enabled" = "true"|"false" — false serves every result * through paged inline delivery without cloud-storage downloads. + * - "lz4_compression_enabled" = "true"|"false", for LZ4 compression + * for Arrow results. Sets the session default; defaults to "true". + * The C ABI has no per-statement compression setter. * - "cloudfetch_link_prefetch_window" = positive integer. * - "cloudfetch_max_chunks_in_memory" = positive integer (bounds peak RSS; * values above the kernel ceiling of 256 are clamped with a warning). @@ -831,6 +849,21 @@ KernelStatusCode kernel_statement_bind_parameter(kernel_statement_t* stmt, KernelStatusCode kernel_statement_set_query_tags(kernel_statement_t* stmt, const char* query_tags); +/* + * Set the Volume transfer options for later executions of `stmt`. With them, + * executing a Volume PUT, GET or REMOVE also runs its file transfer, and the + * execution fails if the transfer does. `allowed_paths_json`: JSON array of + * local directories a transfer may use; the local path, with symlinks + * resolved, must be inside one of them. NULL clears the options, so a Volume + * statement returns its instruction row without transferring. + * `remove_not_found_is_success`: report success when REMOVE targets a missing + * object. The options survive kernel_statement_set_sql. This API takes no upload + * bytes, so `PUT '__input_stream__'` fails. + */ +KernelStatusCode kernel_statement_set_volume_options(kernel_statement_t* stmt, + const char* allowed_paths_json, + bool remove_not_found_is_success); + /* * Wait-for-result execution without an overall client polling deadline. * On success, release `*out` with @@ -988,6 +1021,10 @@ KernelStatusCode kernel_executed_statement_get_result_stream(kernel_executed_sta */ int64_t kernel_executed_statement_num_modified_rows(const kernel_executed_statement_t* exec); +/* Whether the server marked the statement as a Volume PUT, GET or REMOVE. */ +KernelStatusCode kernel_executed_statement_is_volume_operation( + const kernel_executed_statement_t* exec, bool* out); + /* * Server statement (query) id of a successfully executed statement, as a * NUL-terminated C string — the success-path counterpart to the query id on @@ -1017,10 +1054,18 @@ KernelStatusCode kernel_executed_async_statement_status( * state returns KernelStatusCode_InvalidArgument rather than blocking (v0 * collapses invalid-state into that code). This is single-consumption: * a second successful take is rejected. Close the stream with - * kernel_result_stream_close. */ + * kernel_result_stream_close. For a statement the server marks as a Volume + * PUT, GET or REMOVE, it runs the file transfer before returning. */ KernelStatusCode kernel_executed_async_statement_get_result_stream( kernel_executed_async_statement_t* exec, kernel_result_stream_t** out); +/* Whether the last status poll reported success for a statement the server + * marks as a Volume PUT, GET or REMOVE. False before that poll and once the + * result stream is taken. Returns KernelStatusCode_InvalidStatementHandle + * after the parent statement is re-executed or closed. */ +KernelStatusCode kernel_executed_async_statement_is_volume_operation( + const kernel_executed_async_statement_t* exec, bool* out); + /* Most recently observed DML count, or -1 when unavailable. */ int64_t kernel_executed_async_statement_num_modified_rows( const kernel_executed_async_statement_t* exec); @@ -1097,6 +1142,10 @@ KernelStatusCode kernel_result_stream_canceller_cancel( KernelStatusCode kernel_result_stream_canceller_free( kernel_result_stream_canceller_t* canceller); +/* Whether the server marked this result as a Volume PUT, GET or REMOVE. */ +KernelStatusCode kernel_result_stream_is_volume_operation(const kernel_result_stream_t* stream, + bool* out); + /* ─── Metadata ──────────────────────────────────────────────────────── * * Each returns a self-contained result stream (released via From 9fc382f5eca36ec8392d7f890cc125cb98b642cf Mon Sep 17 00:00:00 2001 From: Cathleen Yan <58714163+cathleeny@users.noreply.github.com> Date: Fri, 4 Dec 2026 00:01:11 +0000 Subject: [PATCH 6/6] Document kernel-managed authentication headers Signed-off-by: Cathleen Yan <58714163+cathleeny@users.noreply.github.com> Co-authored-by: Isaac --- CONNECTION_PARAMETERS.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/CONNECTION_PARAMETERS.md b/CONNECTION_PARAMETERS.md index 70ca536bc..7c05898aa 100644 --- a/CONNECTION_PARAMETERS.md +++ b/CONNECTION_PARAMETERS.md @@ -65,8 +65,10 @@ Notes for the SEA/kernel backend: 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` and `x-databricks-org-id` are ignored, and a value with CR, LF or NUL fails - the request. The request context is `context.Background()`, so caller cancellation and + `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.