-
Notifications
You must be signed in to change notification settings - Fork 61
Expand file tree
/
Copy pathexchange.go
More file actions
204 lines (171 loc) · 6.26 KB
/
exchange.go
File metadata and controls
204 lines (171 loc) · 6.26 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
package tokenprovider
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"strings"
"time"
"github.com/golang-jwt/jwt/v5"
"github.com/rs/zerolog/log"
)
// FederationProvider wraps another token provider and automatically handles token exchange
type FederationProvider struct {
baseProvider TokenProvider
databricksHost string
clientID string // For SP-wide federation
httpClient *http.Client
// Settings for token exchange
returnOriginalTokenIfAuthenticated bool
}
// NewFederationProvider creates a federation provider that wraps another provider
// It automatically detects when token exchange is needed and falls back gracefully
func NewFederationProvider(baseProvider TokenProvider, databricksHost string) *FederationProvider {
return &FederationProvider{
baseProvider: baseProvider,
databricksHost: databricksHost,
httpClient: &http.Client{Timeout: 30 * time.Second},
returnOriginalTokenIfAuthenticated: true,
}
}
// NewFederationProviderWithClientID creates a provider for SP-wide federation (M2M)
func NewFederationProviderWithClientID(baseProvider TokenProvider, databricksHost, clientID string) *FederationProvider {
return &FederationProvider{
baseProvider: baseProvider,
databricksHost: databricksHost,
clientID: clientID,
httpClient: &http.Client{Timeout: 30 * time.Second},
returnOriginalTokenIfAuthenticated: true,
}
}
// GetToken gets token from base provider and exchanges if needed
func (p *FederationProvider) GetToken(ctx context.Context) (*Token, error) {
// Get token from base provider
baseToken, err := p.baseProvider.GetToken(ctx)
if err != nil {
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) {
log.Debug().Msgf("federation provider: attempting token exchange for %s", p.baseProvider.Name())
// Try token exchange
exchangedToken, err := p.tryTokenExchange(ctx, baseToken.AccessToken)
if err != nil {
log.Warn().Err(err).Msg("federation provider: token exchange failed, using original token")
return baseToken, nil // Fall back to original token
}
log.Debug().Msg("federation provider: token exchange successful")
return exchangedToken, nil
}
// Use original token
return baseToken, nil
}
// needsTokenExchange determines if a token needs exchange by checking if it's from a different issuer
func (p *FederationProvider) needsTokenExchange(tokenString string) bool {
// Try to parse as JWT
token, _, err := new(jwt.Parser).ParseUnverified(tokenString, jwt.MapClaims{})
if err != nil {
log.Debug().Err(err).Msg("federation provider: not a JWT token, skipping exchange")
return false
}
claims, ok := token.Claims.(jwt.MapClaims)
if !ok {
return false
}
issuer, ok := claims["iss"].(string)
if !ok {
return false
}
// Check if issuer is different from Databricks host
return !p.isSameHost(issuer, p.databricksHost)
}
// tryTokenExchange attempts to exchange the token with Databricks
func (p *FederationProvider) tryTokenExchange(ctx context.Context, subjectToken string) (*Token, error) {
// Build exchange URL - add scheme if not present
exchangeURL := p.databricksHost
if !strings.HasPrefix(exchangeURL, "http://") && !strings.HasPrefix(exchangeURL, "https://") {
exchangeURL = "https://" + exchangeURL
}
if !strings.HasSuffix(exchangeURL, "/") {
exchangeURL += "/"
}
exchangeURL += "oidc/v1/token"
// Prepare form data for token exchange
data := url.Values{}
data.Set("grant_type", "urn:ietf:params:oauth:grant-type:token-exchange")
data.Set("scope", "sql")
data.Set("subject_token_type", "urn:ietf:params:oauth:token-type:jwt")
data.Set("subject_token", subjectToken)
if p.returnOriginalTokenIfAuthenticated {
data.Set("return_original_token_if_authenticated", "true")
}
// Add client_id for SP-wide federation
if p.clientID != "" {
data.Set("client_id", p.clientID)
}
// Create request
req, err := http.NewRequestWithContext(ctx, "POST", exchangeURL, strings.NewReader(data.Encode()))
if err != nil {
return nil, fmt.Errorf("failed to create request: %w", err)
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req.Header.Set("Accept", "*/*")
// Make request
resp, err := p.httpClient.Do(req)
if err != nil {
return nil, fmt.Errorf("request failed: %w", err)
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("failed to read response: %w", err)
}
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("exchange failed with status %d: %s", resp.StatusCode, string(body))
}
// Parse response
var tokenResp struct {
AccessToken string `json:"access_token"`
TokenType string `json:"token_type"`
ExpiresIn int `json:"expires_in"`
Scope string `json:"scope"`
}
if err := json.Unmarshal(body, &tokenResp); err != nil {
return nil, fmt.Errorf("failed to parse response: %w", err)
}
token := &Token{
AccessToken: tokenResp.AccessToken,
TokenType: tokenResp.TokenType,
Scopes: strings.Fields(tokenResp.Scope),
}
if tokenResp.ExpiresIn > 0 {
token.ExpiresAt = time.Now().Add(time.Duration(tokenResp.ExpiresIn) * time.Second)
}
return token, nil
}
// isSameHost compares two URLs to see if they have the same host
func (p *FederationProvider) isSameHost(url1, url2 string) bool {
// Add scheme to url2 if it doesn't have one (databricksHost may not have scheme)
parsedURL2 := url2
if !strings.HasPrefix(url2, "http://") && !strings.HasPrefix(url2, "https://") {
parsedURL2 = "https://" + url2
}
u1, err1 := url.Parse(url1)
u2, err2 := url.Parse(parsedURL2)
if err1 != nil || err2 != nil {
return false
}
// Use Hostname() instead of Host to ignore port differences
// This handles cases like "host.com:443" == "host.com" for HTTPS
return u1.Hostname() == u2.Hostname()
}
// Name returns the provider name
func (p *FederationProvider) Name() string {
baseName := p.baseProvider.Name()
if p.clientID != "" {
return fmt.Sprintf("federation[%s,sp:%s]", baseName, p.clientID[:8]) // Truncate client ID for readability
}
return fmt.Sprintf("federation[%s]", baseName)
}