diff --git a/CHANGELOG.md b/CHANGELOG.md index 94d6136a..99a8400e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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. - 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 8b31a592..7c05898a 100644 --- a/CONNECTION_PARAMETERS.md +++ b/CONNECTION_PARAMETERS.md @@ -54,18 +54,28 @@ 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`, `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 diff --git a/KERNEL_REV b/KERNEL_REV index 418c81d3..bf66d751 100644 --- a/KERNEL_REV +++ b/KERNEL_REV @@ -1 +1 @@ -a29235cbea9532efa5572ebff010045583a19cbe +6d6c1e4eb70e3d5bebea75b76c5b19c459d9a467 diff --git a/README.md b/README.md index 0e9040ba..0b58dc6e 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 3a4a50a8..03315168 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 aaf8cb74..bc9eec00 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 a3f3ecd7..705bcdb0 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 00000000..32e794eb --- /dev/null +++ b/internal/backend/kernel/auth_callback.go @@ -0,0 +1,123 @@ +//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" + "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)) + }) + 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()) + 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 00000000..12aaf097 --- /dev/null +++ b/internal/backend/kernel/auth_callback_test.go @@ -0,0 +1,428 @@ +//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 + sentinel := errors.New("ddf-authenticator-broken") + k := s.backend(func(*http.Request) error { + calls.Add(1) + 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") +} + +// 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 + sentinel := errors.New("ddf-mid-session-failure") + k := s.backend(func(r *http.Request) error { + calls.Add(1) + if fail.Load() { + return sentinel + } + 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.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") + 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 00000000..9a53ead0 --- /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 13b6c4f1..9ca7f0e2 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 @@ -624,7 +625,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 +673,11 @@ func (k *KernelBackend) setAuth(cfg *C.KernelSessionConfig) error { }); err != nil { return fmt.Errorf("kernel: set_u2m_token_cache_config: %w", toConnError(err)) } + case AuthExternal: + 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 tok := newCStr(k.cfg.Auth.Token) defer tok.free() @@ -883,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 8eb605ba..a20af49b 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,33 @@ func isSessionFatal(ke *KernelError) bool { } } +// 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 3c132dff..02160c6b 100644 --- a/internal/backend/kernel/errors_classify_test.go +++ b/internal/backend/kernel/errors_classify_test.go @@ -89,6 +89,59 @@ 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 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/include/databricks_kernel.h b/internal/backend/kernel/include/databricks_kernel.h index effd6057..79388598 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 @@ -231,8 +243,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 +325,38 @@ 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, 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. + * + * 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 @@ -387,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); @@ -628,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 @@ -642,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). @@ -802,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 @@ -959,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 @@ -988,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); @@ -1068,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 diff --git a/internal/backend/kernel/operation.go b/internal/backend/kernel/operation.go index 7b3ccd22..51719946 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 b272df8c..45a830ee 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 diff --git a/kernel_closed_conn_test.go b/kernel_closed_conn_test.go index efadf5d7..133b8e18 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 2e2b08d7..9577eabf 100644 --- a/kernel_config.go +++ b/kernel_config.go @@ -4,6 +4,7 @@ import ( "context" "errors" "fmt" + "net" "net/url" "strconv" "strings" @@ -88,10 +89,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 @@ -407,22 +406,13 @@ func resolveKernelProxy(cfg *config.Config, kc *kernel.Config) error { // 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 @@ -469,16 +459,25 @@ 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) + return kernel.Auth{ + Mode: kernel.AuthExternal, + Authenticator: a, + 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 + } + 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 8421b847..e6b0c0a6 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" @@ -18,8 +19,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,50 +204,95 @@ 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.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 a.Mode != kernel.AuthExternal || a.Authenticator != c.Authenticator { + t.Fatalf("auth = %+v, want External carrying cfg.Authenticator", a) } - if calls != 1 { - t.Errorf("validateKernelConfig resolved the provider: calls = %d, want 1", calls) + 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 calls != 0 { + t.Errorf("validateKernelConfig called the provider %d times, want 0 (no connect-time snapshot)", 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) + } } }) } }) + t.Run("external authenticator RequestURL keeps a port written in the host", func(t *testing.T) { + 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 { + 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 @@ -277,19 +323,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) } })