Skip to content

Commit a21c43e

Browse files
vuanhphungIsaac
andcommitted
fix(auth): send the connector User-Agent on OAuth M2M requests
Attribute OAuth discovery, grants and refreshes without changing main's grant routing. Resolve default transports per request and retain shared authenticator caches and existing timeout caps. Fixes #413 Signed-off-by: Vu Anh Phung <vu.phung@databricks.com> Co-authored-by: Isaac <no-reply@databricks.com>
1 parent bec2847 commit a21c43e

7 files changed

Lines changed: 394 additions & 33 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
### Driver changes
66

77
- **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).
8+
- OAuth M2M discovery, grants and refreshes now send the connector User-Agent (databricks/databricks-sql-go#413).
89

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

‎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: 7 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,13 @@ 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.
6258
client := &http.Client{Timeout: hostConfigTimeout}
59+
if supplied, ok := ctx.Value(oauth2.HTTPClient).(*http.Client); ok && supplied != nil {
60+
*client = *supplied
61+
if client.Timeout <= 0 || client.Timeout > hostConfigTimeout {
62+
client.Timeout = hostConfigTimeout
63+
}
64+
}
6365
issuerURL := resolveOIDCIssuer(ctx, client, hostName)
6466
ctx = oidc.ClientContext(ctx, client)
6567
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: 34 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -646,25 +646,48 @@ func PooledClient(cfg *config.Config) *http.Client {
646646
return nil
647647
}
648648

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,
649+
base := cfg.Transport
650+
if base == nil {
651+
base = PooledTransport(cfg)
652+
}
653+
authenticator := cfg.Authenticator
654+
if configurable, ok := authenticator.(interface {
655+
WithHTTPClient(*http.Client) auth.Authenticator
656+
}); ok {
657+
httpClient := &http.Client{
658+
Transport: &userAgentTransport{base: defaultTransport{}, userAgent: BuildUserAgent(cfg)},
659+
Timeout: cfg.ClientTimeout,
659660
}
661+
authenticator = configurable.WithHTTPClient(httpClient)
660662
}
661663

662664
return &http.Client{
663-
Transport: tr,
665+
Transport: &Transport{Base: base, Authr: authenticator},
664666
Timeout: cfg.ClientTimeout,
665667
}
666668
}
667669

670+
type defaultTransport struct{}
671+
672+
func (defaultTransport) RoundTrip(request *http.Request) (*http.Response, error) {
673+
base := http.DefaultClient.Transport
674+
if base == nil {
675+
base = http.DefaultTransport
676+
}
677+
return base.RoundTrip(request)
678+
}
679+
680+
type userAgentTransport struct {
681+
base http.RoundTripper
682+
userAgent string
683+
}
684+
685+
func (transport *userAgentTransport) RoundTrip(request *http.Request) (*http.Response, error) {
686+
cloned := cloneRequest(request)
687+
cloned.Header.Set("User-Agent", transport.userAgent)
688+
return transport.base.RoundTrip(cloned)
689+
}
690+
668691
// cloneRequest returns a clone of the provided *http.Request.
669692
// The clone is a shallow copy of the struct and its Header map.
670693
func cloneRequest(r *http.Request) *http.Request {

0 commit comments

Comments
 (0)