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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
- **Behavior change:** Bound each whole-transfer Thrift CloudFetch download attempt, including `WithTransport`, by the existing 900s `ClientTimeout`, and omit the link's presigned query string from download errors (databricks/databricks-sql-go#475).
- **Behavior change:** Without direct results, `ArrowIPCStreamIterator.SchemaBytes()` and `ArrowBatchIterator.Schema()` now retrieve result metadata without fetching data and return the result schema, including for empty results, and can return request or schema-conversion errors. Schemas inferred from Thrift metadata may differ from CloudFetch file schemas when server ArrowSchema is absent (databricks/databricks-sql-go#312).
- Evict kernel connections when SEA reports a missing or invalid session, and reject later requests locally without replaying the failed statement.
- OAuth M2M discovery, grants and refreshes now send the connector User-Agent (databricks/databricks-sql-go#413).

## v2.0.0 (2026-11-23)

Expand Down
50 changes: 33 additions & 17 deletions auth/oauth/m2m/m2m.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ func NewAuthenticatorWithScopes(clientID, clientSecret, hostName string, scopes
clientSecret: clientSecret,
hostName: hostName,
scopes: scopes,
cache: &tokenCache{},
}
}

Expand All @@ -35,8 +36,20 @@ type authClient struct {
clientSecret string
hostName string
scopes []string
tokenSource oauth2.TokenSource
mx sync.Mutex
httpClient *http.Client
cache *tokenCache
}

type tokenCache struct {
mutex sync.Mutex
token *oauth2.Token
config *clientcredentials.Config
}

func (c *authClient) WithHTTPClient(client *http.Client) auth.Authenticator {
configured := *c
configured.httpClient = client
return &configured
}

// M2MCredentials exposes the raw client-credentials so the SEA-via-kernel backend
Expand All @@ -56,31 +69,33 @@ func (c *authClient) M2MScopes() []string {
// Auth will start the OAuth Authorization Flow to authenticate the cli client
// using the users credentials in the browser. Compatible with SSO.
func (c *authClient) Authenticate(r *http.Request) error {
c.mx.Lock()
defer c.mx.Unlock()
if c.tokenSource != nil {
token, err := c.tokenSource.Token()
if err != nil {
return err
}
token.SetAuthHeader(r)
c.cache.mutex.Lock()
defer c.cache.mutex.Unlock()
if c.cache.token.Valid() {
c.cache.token.SetAuthHeader(r)
return nil
}

ctx := withTokenRequestTimeout(context.Background())
config, err := getConfig(ctx, c.hostName, c.clientID, c.clientSecret, c.scopes)
if err != nil {
return fmt.Errorf("unable to generate clientCredentials.Config: %w", err)
ctx := context.Background()
if c.httpClient != nil {
ctx = context.WithValue(ctx, oauth2.HTTPClient, c.httpClient)
}
ctx = withTokenRequestTimeout(ctx)
if c.cache.config == nil {
config, err := getConfig(ctx, c.hostName, c.clientID, c.clientSecret, c.scopes)
if err != nil {
return fmt.Errorf("unable to generate clientCredentials.Config: %w", err)
}
c.cache.config = &config
}

// The token source keeps ctx, so refreshes are bounded too.
c.tokenSource = config.TokenSource(ctx)
token, err := c.tokenSource.Token()
token, err := c.cache.config.Token(ctx)
if err != nil {
logger.Err(err).Msg("failed to get token")

return err
}
c.cache.token = token
// Log via the driver's configurable logger (defaults to Warn) rather than the
// global zerolog logger, so this line honors SetLogLevel like every other.
logger.Debug().Msgf("databricks OAuth token fetched successfully")
Expand Down Expand Up @@ -119,6 +134,7 @@ func GetTokenSource(config clientcredentials.Config) oauth2.TokenSource {
return tokenSource
}

// GetConfig uses the oauth2.HTTPClient from ctx for discovery when set.
func GetConfig(ctx context.Context, issuerURL, clientID, clientSecret string, scopes []string) (clientcredentials.Config, error) {
// Get the endpoint based on the host name
endpoint, err := oauth.GetEndpoint(ctx, issuerURL)
Expand Down
12 changes: 7 additions & 5 deletions auth/oauth/oauth.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ var azureTenants = map[string]string{
".databricks.azure.cn": "2ff814a6-3304-4ab8-85cb-cd0e6f879c1d",
}

// GetEndpoint uses the oauth2.HTTPClient from ctx for discovery when set.
func GetEndpoint(ctx context.Context, hostName string) (oauth2.Endpoint, error) {
if ctx == nil {
ctx = context.Background()
Expand All @@ -54,12 +55,13 @@ func GetEndpoint(ctx context.Context, hostName string) (oauth2.Endpoint, error)
// use their account-rooted endpoint instead of the account-agnostic console login.
// For normal workspace hosts this resolves to https://<host>/oidc, identical to
// the previous behavior.
//
// NOTE: this client uses the default transport, matching the existing
// oidc.NewProvider discovery below. A connector-supplied transport / TLS config
// (WithTransport, WithSkipTLSHostVerify) is not yet threaded into the OAuth
// endpoint-resolution path; that is a pre-existing limitation, tracked separately.
client := &http.Client{Timeout: hostConfigTimeout}
if supplied, ok := ctx.Value(oauth2.HTTPClient).(*http.Client); ok && supplied != nil {
*client = *supplied
if client.Timeout <= 0 || client.Timeout > hostConfigTimeout {
client.Timeout = hostConfigTimeout
}
}
issuerURL := resolveOIDCIssuer(ctx, client, hostName)
ctx = oidc.ClientContext(ctx, client)
ctx = oidc.InsecureIssuerURLContext(ctx, issuerURL)
Expand Down
40 changes: 40 additions & 0 deletions connector_test.go
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
package dbsql

import (
"fmt"
"net/http"
"net/http/httptest"
"net/url"
"testing"
"time"

"github.com/databricks/databricks-sql-go/v2/auth"
"github.com/databricks/databricks-sql-go/v2/auth/pat"
"github.com/databricks/databricks-sql-go/v2/auth/tokenprovider"
dbsqlerr "github.com/databricks/databricks-sql-go/v2/errors"
Expand Down Expand Up @@ -55,6 +58,43 @@ func TestFederatedTokenAuthenticatorPreservesThriftTokenExchange(t *testing.T) {
assert.Equal(t, subjectToken, exchange.subjectToken)
}

type connectorOAuthRecorder struct {
auth.Authenticator
client *http.Client
}

func (recorder *connectorOAuthRecorder) WithHTTPClient(client *http.Client) auth.Authenticator {
recorder.client = client
return recorder.Authenticator.(interface {
WithHTTPClient(*http.Client) auth.Authenticator
}).WithHTTPClient(client)
}

func TestM2MConnectorHTTPConfiguration(t *testing.T) {
agents := make(chan string, 1)
server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
agents <- request.UserAgent()
writer.WriteHeader(http.StatusOK)
}))
t.Cleanup(server.Close)
caller := &http.Transport{Proxy: func(*http.Request) (*url.URL, error) {
return nil, fmt.Errorf("OAuth must not use the caller transport")
}}
t.Cleanup(caller.CloseIdleConnections)
recorder := &connectorOAuthRecorder{}
_, err := NewConnector(WithServerHostname("test.cloud.databricks.com"), WithHTTPPath("/query"),
WithClientCredentials("id", "secret"), WithUserAgentEntry("Issue413/partner"), WithTransport(caller),
func(cfg *config.Config) {
recorder.Authenticator, cfg.Authenticator = cfg.Authenticator, recorder
})
require.NoError(t, err)
require.NotNil(t, recorder.client)
response, err := recorder.client.Get(server.URL)
require.NoError(t, err, "bound OAuth base must bypass the caller transport")
require.NoError(t, response.Body.Close())
assert.Contains(t, <-agents, "Issue413/partner")
}

func TestWithClientQueryTimeout(t *testing.T) {
t.Run("omitted remains distinguishable from explicit zero", func(t *testing.T) {
con, err := NewConnector(WithUseKernel(true))
Expand Down
45 changes: 34 additions & 11 deletions internal/client/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -646,25 +646,48 @@ func PooledClient(cfg *config.Config) *http.Client {
return nil
}

var tr *Transport
if cfg.Transport != nil {
tr = &Transport{
Base: cfg.Transport,
Authr: cfg.Authenticator,
}
} else {
tr = &Transport{
Base: PooledTransport(cfg),
Authr: cfg.Authenticator,
base := cfg.Transport
if base == nil {
base = PooledTransport(cfg)
}
authenticator := cfg.Authenticator
if configurable, ok := authenticator.(interface {
WithHTTPClient(*http.Client) auth.Authenticator
}); ok {
httpClient := &http.Client{

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Low — The new OAuth client only reuses http.DefaultClient's Transport and drops its CheckRedirect and Jar. The old code copied the whole default client in withTokenRequestTimeout, so any custom redirect policy was kept, and now it is lost. Copy the other fields from http.DefaultClient into the new client and add a redirect-policy test. This only affects apps that customise http.DefaultClient, so the impact is narrow.

🔀 Found by GPT-6.1 Sol · confirmed by the judge

@vuanhphung vuanhphung Nov 24, 2026 •

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Confirmed as a limitation versus main, but it predates this routing revision: 76461ca already creates the UA client with only Transport and Timeout (client.go:660-663). Redirect-policy work was explicitly deferred in the prior accepted scope (also noted in the November 20 scope comment). This maintainer revision restores request-time transport routing, not all DefaultClient state; copying its Jar would additionally introduce cookies into discovery that main does not carry. Keeping global redirect/cookie policy as a separate follow-up rather than expanding this patch.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Still open at 975d73a: client.go:657-660 still omits http.DefaultClient.CheckRedirect. Keeping this thread open to track the deferred follow-up.

Transport: &userAgentTransport{base: defaultTransport{}, userAgent: BuildUserAgent(cfg)},
Timeout: cfg.ClientTimeout,
}
authenticator = configurable.WithHTTPClient(httpClient)
}

return &http.Client{
Transport: tr,
Transport: &Transport{Base: base, Authr: authenticator},
Timeout: cfg.ClientTimeout,
}
}

type defaultTransport struct{}

func (defaultTransport) RoundTrip(request *http.Request) (*http.Response, error) {
base := http.DefaultClient.Transport
if base == nil {
base = http.DefaultTransport
}
return base.RoundTrip(request)
}

type userAgentTransport struct {
base http.RoundTripper
userAgent string
}

func (transport *userAgentTransport) RoundTrip(request *http.Request) (*http.Response, error) {
cloned := cloneRequest(request)
cloned.Header.Set("User-Agent", transport.userAgent)
return transport.base.RoundTrip(cloned)
}

// cloneRequest returns a clone of the provided *http.Request.
// The clone is a shallow copy of the struct and its Header map.
func cloneRequest(r *http.Request) *http.Request {
Expand Down
Loading
Loading