Skip to content

Commit 76461ca

Browse files
vuanhphungIsaac
andcommitted
fix(auth): honor connector HTTP settings in OAuth M2M
Carry the connector User-Agent through M2M discovery, grants and refreshes so OAuth token traffic retains partner attribution. Use one verified driver-owned pool with shared authenticator caches. Connector M2M no longer honors global HTTP client/transport overrides. Fixes #413 Signed-off-by: Vu Anh Phung <vu.phung@databricks.com> Co-authored-by: Isaac <no-reply@databricks.com>
1 parent 73b9a3a commit 76461ca

7 files changed

Lines changed: 356 additions & 33 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,11 @@
11
# Release History
22

3+
## Unreleased
4+
5+
### Driver changes
6+
7+
- **Behavior change:** Connector M2M discovery, grants and refreshes send the connector User-Agent over a driver-owned transport (`HTTPS_PROXY`/`NO_PROXY`, system roots including `SSL_CERT_FILE`); changes to `http.DefaultTransport`/`http.DefaultClient` no longer reach them (databricks/databricks-sql-go#413).
8+
39
## v2.0.0 (2026-11-23)
410

511
### Breaking changes

‎auth/oauth/m2m/m2m.go‎

Lines changed: 33 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ func NewAuthenticatorWithScopes(clientID, clientSecret, hostName string, scopes
2727
clientSecret: clientSecret,
2828
hostName: hostName,
2929
scopes: scopes,
30+
cache: &tokenCache{},
3031
}
3132
}
3233

@@ -35,8 +36,20 @@ type authClient struct {
3536
clientSecret string
3637
hostName string
3738
scopes []string
38-
tokenSource oauth2.TokenSource
39-
mx sync.Mutex
39+
httpClient *http.Client
40+
cache *tokenCache
41+
}
42+
43+
type tokenCache struct {
44+
mutex sync.Mutex
45+
token *oauth2.Token
46+
config *clientcredentials.Config
47+
}
48+
49+
func (c *authClient) WithHTTPClient(client *http.Client) auth.Authenticator {
50+
configured := *c
51+
configured.httpClient = client
52+
return &configured
4053
}
4154

4255
// M2MCredentials exposes the raw client-credentials so the SEA-via-kernel backend
@@ -56,31 +69,33 @@ func (c *authClient) M2MScopes() []string {
5669
// Auth will start the OAuth Authorization Flow to authenticate the cli client
5770
// using the users credentials in the browser. Compatible with SSO.
5871
func (c *authClient) Authenticate(r *http.Request) error {
59-
c.mx.Lock()
60-
defer c.mx.Unlock()
61-
if c.tokenSource != nil {
62-
token, err := c.tokenSource.Token()
63-
if err != nil {
64-
return err
65-
}
66-
token.SetAuthHeader(r)
72+
c.cache.mutex.Lock()
73+
defer c.cache.mutex.Unlock()
74+
if c.cache.token.Valid() {
75+
c.cache.token.SetAuthHeader(r)
6776
return nil
6877
}
6978

70-
ctx := withTokenRequestTimeout(context.Background())
71-
config, err := getConfig(ctx, c.hostName, c.clientID, c.clientSecret, c.scopes)
72-
if err != nil {
73-
return fmt.Errorf("unable to generate clientCredentials.Config: %w", err)
79+
ctx := context.Background()
80+
if c.httpClient != nil {
81+
ctx = context.WithValue(ctx, oauth2.HTTPClient, c.httpClient)
82+
}
83+
ctx = withTokenRequestTimeout(ctx)
84+
if c.cache.config == nil {
85+
config, err := getConfig(ctx, c.hostName, c.clientID, c.clientSecret, c.scopes)
86+
if err != nil {
87+
return fmt.Errorf("unable to generate clientCredentials.Config: %w", err)
88+
}
89+
c.cache.config = &config
7490
}
7591

76-
// The token source keeps ctx, so refreshes are bounded too.
77-
c.tokenSource = config.TokenSource(ctx)
78-
token, err := c.tokenSource.Token()
92+
token, err := c.cache.config.Token(ctx)
7993
if err != nil {
8094
logger.Err(err).Msg("failed to get token")
8195

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

137+
// GetConfig uses the oauth2.HTTPClient from ctx for discovery when set.
122138
func GetConfig(ctx context.Context, issuerURL, clientID, clientSecret string, scopes []string) (clientcredentials.Config, error) {
123139
// Get the endpoint based on the host name
124140
endpoint, err := oauth.GetEndpoint(ctx, issuerURL)

‎auth/oauth/oauth.go‎

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@ var azureTenants = map[string]string{
3232
".databricks.azure.cn": "2ff814a6-3304-4ab8-85cb-cd0e6f879c1d",
3333
}
3434

35+
// GetEndpoint uses the oauth2.HTTPClient from ctx for discovery when set.
3536
func GetEndpoint(ctx context.Context, hostName string) (oauth2.Endpoint, error) {
3637
if ctx == nil {
3738
ctx = context.Background()
@@ -54,12 +55,15 @@ func GetEndpoint(ctx context.Context, hostName string) (oauth2.Endpoint, error)
5455
// use their account-rooted endpoint instead of the account-agnostic console login.
5556
// For normal workspace hosts this resolves to https://<host>/oidc, identical to
5657
// the previous behavior.
57-
//
58-
// NOTE: this client uses the default transport, matching the existing
59-
// oidc.NewProvider discovery below. A connector-supplied transport / TLS config
60-
// (WithTransport, WithSkipTLSHostVerify) is not yet threaded into the OAuth
61-
// endpoint-resolution path; that is a pre-existing limitation, tracked separately.
58+
// NOTE: M2M connectors supply the driver's verified transport, not the
59+
// caller's SQL transport or WithSkipTLSHostVerify settings.
6260
client := &http.Client{Timeout: hostConfigTimeout}
61+
if supplied, ok := ctx.Value(oauth2.HTTPClient).(*http.Client); ok && supplied != nil {
62+
*client = *supplied
63+
if client.Timeout <= 0 || client.Timeout > hostConfigTimeout {
64+
client.Timeout = hostConfigTimeout
65+
}
66+
}
6367
issuerURL := resolveOIDCIssuer(ctx, client, hostName)
6468
ctx = oidc.ClientContext(ctx, client)
6569
ctx = oidc.InsecureIssuerURLContext(ctx, issuerURL)

‎connector_test.go‎

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,14 @@
11
package dbsql
22

33
import (
4+
"fmt"
45
"net/http"
56
"net/http/httptest"
7+
"net/url"
68
"testing"
79
"time"
810

11+
"github.com/databricks/databricks-sql-go/v2/auth"
912
"github.com/databricks/databricks-sql-go/v2/auth/pat"
1013
"github.com/databricks/databricks-sql-go/v2/auth/tokenprovider"
1114
dbsqlerr "github.com/databricks/databricks-sql-go/v2/errors"
@@ -55,6 +58,43 @@ func TestFederatedTokenAuthenticatorPreservesThriftTokenExchange(t *testing.T) {
5558
assert.Equal(t, subjectToken, exchange.subjectToken)
5659
}
5760

61+
type connectorOAuthRecorder struct {
62+
auth.Authenticator
63+
client *http.Client
64+
}
65+
66+
func (recorder *connectorOAuthRecorder) WithHTTPClient(client *http.Client) auth.Authenticator {
67+
recorder.client = client
68+
return recorder.Authenticator.(interface {
69+
WithHTTPClient(*http.Client) auth.Authenticator
70+
}).WithHTTPClient(client)
71+
}
72+
73+
func TestM2MConnectorHTTPConfiguration(t *testing.T) {
74+
agents := make(chan string, 1)
75+
server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
76+
agents <- request.UserAgent()
77+
writer.WriteHeader(http.StatusOK)
78+
}))
79+
t.Cleanup(server.Close)
80+
caller := &http.Transport{Proxy: func(*http.Request) (*url.URL, error) {
81+
return nil, fmt.Errorf("OAuth must not use the caller transport")
82+
}}
83+
t.Cleanup(caller.CloseIdleConnections)
84+
recorder := &connectorOAuthRecorder{}
85+
_, err := NewConnector(WithServerHostname("test.cloud.databricks.com"), WithHTTPPath("/query"),
86+
WithClientCredentials("id", "secret"), WithUserAgentEntry("Issue413/partner"), WithTransport(caller),
87+
func(cfg *config.Config) {
88+
recorder.Authenticator, cfg.Authenticator = cfg.Authenticator, recorder
89+
})
90+
require.NoError(t, err)
91+
require.NotNil(t, recorder.client)
92+
response, err := recorder.client.Get(server.URL)
93+
require.NoError(t, err, "bound OAuth base must bypass the caller transport")
94+
require.NoError(t, response.Body.Close())
95+
assert.Contains(t, <-agents, "Issue413/partner")
96+
}
97+
5898
func TestWithClientQueryTimeout(t *testing.T) {
5999
t.Run("omitted remains distinguishable from explicit zero", func(t *testing.T) {
60100
con, err := NewConnector(WithUseKernel(true))

‎internal/client/client.go‎

Lines changed: 27 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ import (
1818
"runtime"
1919
"strconv"
2020
"strings"
21+
"sync"
2122
"sync/atomic"
2223
"time"
2324

@@ -641,30 +642,45 @@ func PooledTransport(cfg *config.Config) *http.Transport {
641642
return transport
642643
}
643644

645+
var oauthTransport = sync.OnceValue(func() *http.Transport { return PooledTransport(&config.Config{}) })
646+
644647
func PooledClient(cfg *config.Config) *http.Client {
645648
if cfg.Authenticator == nil {
646649
return nil
647650
}
648651

649-
var tr *Transport
650-
if cfg.Transport != nil {
651-
tr = &Transport{
652-
Base: cfg.Transport,
653-
Authr: cfg.Authenticator,
654-
}
655-
} else {
656-
tr = &Transport{
657-
Base: PooledTransport(cfg),
658-
Authr: cfg.Authenticator,
652+
base := cfg.Transport
653+
if base == nil {
654+
base = PooledTransport(cfg)
655+
}
656+
authenticator := cfg.Authenticator
657+
if configurable, ok := authenticator.(interface {
658+
WithHTTPClient(*http.Client) auth.Authenticator
659+
}); ok {
660+
httpClient := &http.Client{
661+
Transport: &userAgentTransport{base: oauthTransport(), userAgent: BuildUserAgent(cfg)},
662+
Timeout: cfg.ClientTimeout,
659663
}
664+
authenticator = configurable.WithHTTPClient(httpClient)
660665
}
661666

662667
return &http.Client{
663-
Transport: tr,
668+
Transport: &Transport{Base: base, Authr: authenticator},
664669
Timeout: cfg.ClientTimeout,
665670
}
666671
}
667672

673+
type userAgentTransport struct {
674+
base http.RoundTripper
675+
userAgent string
676+
}
677+
678+
func (transport *userAgentTransport) RoundTrip(request *http.Request) (*http.Response, error) {
679+
cloned := cloneRequest(request)
680+
cloned.Header.Set("User-Agent", transport.userAgent)
681+
return transport.base.RoundTrip(cloned)
682+
}
683+
668684
// cloneRequest returns a clone of the provided *http.Request.
669685
// The clone is a shallow copy of the struct and its Header map.
670686
func cloneRequest(r *http.Request) *http.Request {

0 commit comments

Comments
 (0)