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 @@ -4,6 +4,7 @@

### Driver changes

- Cache federated token exchanges until the subject changes or the exchanged token nears expiry, avoiding an exchange on every request. Failed exchanges temporarily reuse the original token before retrying.
- 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.
- 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`.
Expand Down
205 changes: 186 additions & 19 deletions auth/tokenprovider/exchange.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,40 @@ import (
"net/http"
"net/url"
"strings"
"sync"
"time"

"github.com/databricks/databricks-sql-go/v2/logger"
"github.com/golang-jwt/jwt/v5"
)

const (
federationRefreshThreshold = 5 * time.Minute
fallbackRetryInterval = 5 * time.Minute
defaultExchangedTokenTTL = time.Hour
)

type federationCache struct {
subject string
token *Token
fallback bool
retryAt time.Time
subjectExpiry time.Time
expiresAt time.Time
}

type exchangeFlight struct {
done chan struct{}
token *Token
fallback bool
cancelled bool
}

type exchangeResult struct {
token *Token
expiresAt time.Time
}

// FederationProvider wraps another token provider and automatically handles token exchange
type FederationProvider struct {
baseProvider TokenProvider
Expand All @@ -22,6 +50,13 @@ type FederationProvider struct {
httpClient *http.Client
// Settings for token exchange
returnOriginalTokenIfAuthenticated bool

mu sync.Mutex
currentSubject string
cache *federationCache
flights map[string]*exchangeFlight
activeFlight *exchangeFlight
now func() time.Time
}

// NewFederationProvider creates a federation provider that wraps another provider
Expand All @@ -32,6 +67,7 @@ func NewFederationProvider(baseProvider TokenProvider, databricksHost string) *F
databricksHost: databricksHost,
httpClient: &http.Client{Timeout: 30 * time.Second},
returnOriginalTokenIfAuthenticated: true,
now: time.Now,
}
}

Expand All @@ -43,11 +79,13 @@ func NewFederationProviderWithClientID(baseProvider TokenProvider, databricksHos
clientID: clientID,
httpClient: &http.Client{Timeout: 30 * time.Second},
returnOriginalTokenIfAuthenticated: true,
now: time.Now,
}
}

// GetToken gets token from base provider and exchanges if needed
func (p *FederationProvider) GetToken(ctx context.Context) (*Token, error) {
retry:
// Check if context is already cancelled
if err := ctx.Err(); err != nil {
return nil, fmt.Errorf("federation provider: context cancelled: %w", err)
Expand All @@ -59,23 +97,142 @@ func (p *FederationProvider) GetToken(ctx context.Context) (*Token, error) {
return nil, fmt.Errorf("federation provider: failed to get base token: %w", err)
}

// Check if token is a JWT and needs exchange
if p.needsTokenExchange(baseToken.AccessToken) {
logger.Debug().Msgf("federation provider: attempting token exchange for %s", p.baseProvider.Name())
subject := baseToken.AccessToken
needsExchange := p.needsTokenExchange(subject)
p.mu.Lock()
if p.currentSubject != subject {
p.currentSubject = subject
p.cache = nil
p.activeFlight = nil
}
if !needsExchange {
p.mu.Unlock()
return baseToken, nil
}
if p.cache != nil && p.cache.subject == subject && p.cacheValid(baseToken) {
cached := p.cache
if cached.fallback {
p.mu.Unlock()
return baseToken, nil
}
token := cloneFederationToken(cached.token)
p.mu.Unlock()
return token, nil
}
if p.flights == nil {
p.flights = make(map[string]*exchangeFlight)
}
if flight := p.flights[subject]; flight != nil {
p.activeFlight = flight
p.mu.Unlock()
select {
case <-ctx.Done():
return nil, fmt.Errorf("federation provider: context cancelled: %w", ctx.Err())
case <-flight.done:
if flight.cancelled {
// The leader's cancellation must not make other callers fall back.
// Re-fetch the subject as it may have changed while we waited.
goto retry
}
if flight.fallback {
return baseToken, nil
}
return cloneFederationToken(flight.token), nil
}
}
flight := &exchangeFlight{done: make(chan struct{})}
p.flights[subject] = flight
p.activeFlight = flight
p.mu.Unlock()

logger.Debug().Msgf("federation provider: attempting token exchange for %s", p.baseProvider.Name())
result, err := p.tryTokenExchange(ctx, subject)
fallback := err != nil
Comment thread
cathleeny marked this conversation as resolved.
Resolved
var token *Token
var expiresAt time.Time
if fallback {
logger.Warn().Err(err).Msg("federation provider: token exchange failed, using original token")
} else {
token, expiresAt = result.token, result.expiresAt
logger.Debug().Msg("federation provider: token exchange successful")
}

p.mu.Lock()
flight.token, flight.fallback = cloneFederationToken(token), fallback
flight.cancelled = fallback && ctx.Err() != nil
if p.activeFlight == flight && p.currentSubject == subject {
p.activeFlight = nil
// A caller's cancellation should not suppress another caller's exchange.
if ctx.Err() == nil {
entry := &federationCache{subject: subject, token: cloneFederationToken(token), fallback: fallback, expiresAt: expiresAt}
if fallback {
entry.retryAt = p.now().Add(fallbackRetryInterval)
entry.subjectExpiry = subjectExpiry(baseToken)
}
p.cache = entry
}
}
if p.flights[subject] == flight {
delete(p.flights, subject)
}
close(flight.done)
p.mu.Unlock()
if fallback {
return baseToken, nil
}
return token, nil
}

// Try token exchange
exchangedToken, err := p.tryTokenExchange(ctx, baseToken.AccessToken)
if err != nil {
logger.Warn().Err(err).Msg("federation provider: token exchange failed, using original token")
return baseToken, nil // Fall back to original token
// cacheValid is called with p.mu held. Fallbacks are bounded by both the retry
// interval and the subject's expiry; successful exchanges use their own expiry.
func (p *FederationProvider) cacheValid(subject *Token) bool {
now := p.now()
if p.cache.fallback {
if !now.Before(p.cache.retryAt) {
return false
}
expiry := p.cache.subjectExpiry
if current := subjectExpiry(subject); !current.IsZero() && (expiry.IsZero() || current.Before(expiry)) {
expiry = current
}
return expiry.IsZero() || now.Before(expiry.Add(-federationRefreshThreshold))
}
return now.Before(p.cache.expiresAt.Add(-federationRefreshThreshold))
}

logger.Debug().Msg("federation provider: token exchange successful")
return exchangedToken, nil
func cloneFederationToken(token *Token) *Token {
if token == nil {
return nil
}
copy := *token
copy.Scopes = append([]string(nil), token.Scopes...)
return &copy
}

// Use original token
return baseToken, nil
// JWT claims are parsed without signature verification only to select a cache
// lifetime. The server remains responsible for token validation.
func jwtExpiry(tokenString string) time.Time {
token, _, err := new(jwt.Parser).ParseUnverified(tokenString, jwt.MapClaims{})
if err != nil {
return time.Time{}
}
claims, ok := token.Claims.(jwt.MapClaims)
if !ok {
return time.Time{}
}
expiry, err := claims.GetExpirationTime()
if err != nil || expiry == nil {
return time.Time{}
}
return expiry.Time
}

func subjectExpiry(token *Token) time.Time {
expiry := token.ExpiresAt
if jwtTime := jwtExpiry(token.AccessToken); !jwtTime.IsZero() && (expiry.IsZero() || jwtTime.Before(expiry)) {
return jwtTime
}
return expiry
}

// needsTokenExchange determines if a token needs exchange by checking if it's from a different issuer
Expand Down Expand Up @@ -106,7 +263,7 @@ func (p *FederationProvider) needsTokenExchange(tokenString string) bool {
}

// tryTokenExchange attempts to exchange the token with Databricks
func (p *FederationProvider) tryTokenExchange(ctx context.Context, subjectToken string) (*Token, error) {
func (p *FederationProvider) tryTokenExchange(ctx context.Context, subjectToken string) (*exchangeResult, error) {
// Build exchange URL - add scheme if not present
exchangeURL := p.databricksHost
if !strings.HasPrefix(exchangeURL, "http://") && !strings.HasPrefix(exchangeURL, "https://") {
Expand Down Expand Up @@ -166,7 +323,7 @@ func (p *FederationProvider) tryTokenExchange(ctx context.Context, subjectToken
var tokenResp struct {
AccessToken string `json:"access_token"`
TokenType string `json:"token_type"`
ExpiresIn int `json:"expires_in"`
ExpiresIn *int `json:"expires_in"`
Scope string `json:"scope"`
}

Expand All @@ -182,8 +339,8 @@ func (p *FederationProvider) tryTokenExchange(ctx context.Context, subjectToken
logger.Debug().Msg("token exchange: token_type not specified, defaulting to Bearer")
tokenResp.TokenType = "Bearer"
}
if tokenResp.ExpiresIn < 0 {
return nil, fmt.Errorf("token exchange returned invalid expires_in: %d", tokenResp.ExpiresIn)
if tokenResp.ExpiresIn != nil && *tokenResp.ExpiresIn < 0 {
return nil, fmt.Errorf("token exchange returned invalid expires_in: %d", *tokenResp.ExpiresIn)
}

token := &Token{
Expand All @@ -192,11 +349,21 @@ func (p *FederationProvider) tryTokenExchange(ctx context.Context, subjectToken
Scopes: strings.Fields(tokenResp.Scope),
}

if tokenResp.ExpiresIn > 0 {
token.ExpiresAt = time.Now().Add(time.Duration(tokenResp.ExpiresIn) * time.Second)
// Preserve the public Token's existing expiry semantics. The inferred JWT
// and default lifetimes are used only to decide when to refresh the cache.
var expiresAt time.Time
if tokenResp.ExpiresIn != nil {
expiresAt = p.now().Add(time.Duration(*tokenResp.ExpiresIn) * time.Second)
if *tokenResp.ExpiresIn > 0 {
token.ExpiresAt = expiresAt
}
} else if expiry := jwtExpiry(tokenResp.AccessToken); !expiry.IsZero() {
expiresAt = expiry
} else {
expiresAt = p.now().Add(defaultExchangedTokenTTL)
}

return token, nil
return &exchangeResult{token: token, expiresAt: expiresAt}, nil
}

// isSameHost compares two URLs to see if they have the same host
Expand Down
Loading
Loading