-
Notifications
You must be signed in to change notification settings - Fork 696
/
Copy pathtoken_source_provider.go
302 lines (259 loc) · 9.12 KB
/
token_source_provider.go
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
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
package admin
import (
"context"
"fmt"
"io/ioutil"
"net/url"
"os"
"strings"
"sync"
"k8s.io/apimachinery/pkg/util/wait"
"k8s.io/client-go/util/retry"
"golang.org/x/oauth2"
"golang.org/x/oauth2/clientcredentials"
"github.com/flyteorg/flyte/flyteidl/clients/go/admin/cache"
"github.com/flyteorg/flyte/flyteidl/clients/go/admin/deviceflow"
"github.com/flyteorg/flyte/flyteidl/clients/go/admin/externalprocess"
"github.com/flyteorg/flyte/flyteidl/clients/go/admin/pkce"
"github.com/flyteorg/flyte/flyteidl/clients/go/admin/tokenorchestrator"
"github.com/flyteorg/flyte/flyteidl/gen/pb-go/flyteidl/service"
"github.com/flyteorg/flyte/flytestdlib/logger"
)
//go:generate mockery -name TokenSource
type TokenSource interface {
Token() (*oauth2.Token, error)
}
const (
audienceKey = "audience"
)
// TokenSourceProvider defines the interface needed to provide a TokenSource that is used to
// create a client with authentication enabled.
type TokenSourceProvider interface {
GetTokenSource(ctx context.Context) (oauth2.TokenSource, error)
}
func NewTokenSourceProvider(ctx context.Context, cfg *Config, tokenCache cache.TokenCache,
authClient service.AuthMetadataServiceClient) (TokenSourceProvider, error) {
var tokenProvider TokenSourceProvider
var err error
switch cfg.AuthType {
case AuthTypeClientSecret:
tokenURL := cfg.TokenURL
if len(tokenURL) == 0 {
metadata, err := authClient.GetOAuth2Metadata(ctx, &service.OAuth2MetadataRequest{})
if err != nil {
return nil, fmt.Errorf("failed to fetch auth metadata. Error: %v", err)
}
tokenURL = metadata.TokenEndpoint
}
scopes := cfg.Scopes
audienceValue := cfg.Audience
if len(scopes) == 0 || cfg.UseAudienceFromAdmin {
publicClientConfig, err := authClient.GetPublicClientConfig(ctx, &service.PublicClientAuthConfigRequest{})
if err != nil {
return nil, fmt.Errorf("failed to fetch client metadata. Error: %v", err)
}
// Update scopes from publicClientConfig
if len(scopes) == 0 {
scopes = publicClientConfig.Scopes
}
// Update audience from publicClientConfig
if cfg.UseAudienceFromAdmin {
audienceValue = publicClientConfig.Audience
}
}
tokenProvider, err = NewClientCredentialsTokenSourceProvider(ctx, cfg, scopes, tokenURL, tokenCache, audienceValue)
if err != nil {
return nil, err
}
case AuthTypePkce:
baseTokenOrchestrator, err := tokenorchestrator.NewBaseTokenOrchestrator(ctx, tokenCache, authClient)
if err != nil {
return nil, err
}
tokenProvider, err = NewPKCETokenSourceProvider(baseTokenOrchestrator, cfg.PkceConfig)
if err != nil {
return nil, err
}
case AuthTypeExternalCommand:
tokenProvider, err = NewExternalTokenSourceProvider(cfg.Command)
if err != nil {
return nil, err
}
case AuthTypeDeviceFlow:
baseTokenOrchestrator, err := tokenorchestrator.NewBaseTokenOrchestrator(ctx, tokenCache, authClient)
if err != nil {
return nil, err
}
tokenProvider, err = NewDeviceFlowTokenSourceProvider(baseTokenOrchestrator, cfg.DeviceFlowConfig)
if err != nil {
return nil, err
}
default:
return nil, fmt.Errorf("unsupported type %v", cfg.AuthType)
}
return tokenProvider, nil
}
type ExternalTokenSourceProvider struct {
command []string
}
func NewExternalTokenSourceProvider(command []string) (TokenSourceProvider, error) {
return &ExternalTokenSourceProvider{command: command}, nil
}
func (e ExternalTokenSourceProvider) GetTokenSource(ctx context.Context) (oauth2.TokenSource, error) {
output, err := externalprocess.Execute(e.command)
if err != nil {
return nil, err
}
return oauth2.StaticTokenSource(&oauth2.Token{
AccessToken: strings.Trim(string(output), "\t \n"),
TokenType: "bearer",
}), nil
}
type PKCETokenSourceProvider struct {
tokenOrchestrator pkce.TokenOrchestrator
}
func NewPKCETokenSourceProvider(baseTokenOrchestrator tokenorchestrator.BaseTokenOrchestrator, pkceCfg pkce.Config) (TokenSourceProvider, error) {
tokenOrchestrator, err := pkce.NewTokenOrchestrator(baseTokenOrchestrator, pkceCfg)
if err != nil {
return nil, err
}
return PKCETokenSourceProvider{tokenOrchestrator: tokenOrchestrator}, nil
}
func (p PKCETokenSourceProvider) GetTokenSource(ctx context.Context) (oauth2.TokenSource, error) {
return GetPKCEAuthTokenSource(ctx, p.tokenOrchestrator)
}
// Returns the token source which would be used for three legged oauth. eg : for admin to authorize access to flytectl
func GetPKCEAuthTokenSource(ctx context.Context, pkceTokenOrchestrator pkce.TokenOrchestrator) (oauth2.TokenSource, error) {
// explicitly ignore error while fetching token from cache.
authToken, err := pkceTokenOrchestrator.FetchTokenFromCacheOrRefreshIt(ctx, pkceTokenOrchestrator.Config.BrowserSessionTimeout)
if err != nil {
logger.Warnf(ctx, "Failed fetching from cache. Will restart the flow. Error: %v", err)
}
if authToken == nil {
// Fetch using auth flow
if authToken, err = pkceTokenOrchestrator.FetchTokenFromAuthFlow(ctx); err != nil {
logger.Errorf(ctx, "Error fetching token using auth flow due to %v", err)
return nil, err
}
}
return &pkce.SimpleTokenSource{
CachedToken: authToken,
}, nil
}
type ClientCredentialsTokenSourceProvider struct {
ccConfig clientcredentials.Config
tokenCache cache.TokenCache
cfg *Config
}
func NewClientCredentialsTokenSourceProvider(ctx context.Context, cfg *Config, scopes []string, tokenURL string,
tokenCache cache.TokenCache, audience string) (TokenSourceProvider, error) {
var secret string
if len(cfg.ClientSecretEnvVar) > 0 {
secret = os.Getenv(cfg.ClientSecretEnvVar)
} else if len(cfg.ClientSecretLocation) > 0 {
secretBytes, err := ioutil.ReadFile(cfg.ClientSecretLocation)
if err != nil {
logger.Errorf(ctx, "Error reading secret from location %s", cfg.ClientSecretLocation)
return nil, err
}
secret = string(secretBytes)
}
endpointParams := url.Values{}
if len(audience) > 0 {
endpointParams = url.Values{audienceKey: {audience}}
}
secret = strings.TrimSpace(secret)
if tokenCache == nil {
tokenCache = cache.NewTokenCacheInMemoryProvider()
}
return ClientCredentialsTokenSourceProvider{
ccConfig: clientcredentials.Config{
ClientID: cfg.ClientID,
ClientSecret: secret,
TokenURL: tokenURL,
Scopes: scopes,
EndpointParams: endpointParams,
},
tokenCache: tokenCache,
cfg: cfg,
}, nil
}
func (p ClientCredentialsTokenSourceProvider) GetTokenSource(ctx context.Context) (oauth2.TokenSource, error) {
return &customTokenSource{
ctx: ctx,
new: p.ccConfig.TokenSource(ctx),
mu: sync.Mutex{},
tokenCache: p.tokenCache,
cfg: p.cfg,
}, nil
}
type customTokenSource struct {
ctx context.Context
mu sync.Mutex // guards everything else
new oauth2.TokenSource
tokenCache cache.TokenCache
cfg *Config
}
func (s *customTokenSource) Token() (*oauth2.Token, error) {
s.mu.Lock()
defer s.mu.Unlock()
if token, err := s.tokenCache.GetToken(); err == nil && token.Valid() {
return token, nil
}
totalAttempts := s.cfg.MaxRetries + 1 // Add one for initial request attempt
backoff := wait.Backoff{
Duration: s.cfg.PerRetryTimeout.Duration,
Steps: totalAttempts,
}
var token *oauth2.Token
err := retry.OnError(backoff, func(err error) bool {
return err != nil
}, func() (err error) {
token, err = s.new.Token()
if err != nil {
logger.Infof(s.ctx, "failed to get token: %w", err)
return fmt.Errorf("failed to get token: %w", err)
}
return nil
})
if err != nil {
return nil, err
}
logger.Infof(s.ctx, "retrieved token with expiry %v", token.Expiry)
err = s.tokenCache.SaveToken(token)
if err != nil {
logger.Warnf(s.ctx, "failed to cache token: %v", err)
}
return token, nil
}
type DeviceFlowTokenSourceProvider struct {
tokenOrchestrator deviceflow.TokenOrchestrator
}
func NewDeviceFlowTokenSourceProvider(baseTokenOrchestrator tokenorchestrator.BaseTokenOrchestrator, deviceFlowConfig deviceflow.Config) (TokenSourceProvider, error) {
tokenOrchestrator, err := deviceflow.NewDeviceFlowTokenOrchestrator(baseTokenOrchestrator, deviceFlowConfig)
if err != nil {
return nil, err
}
return DeviceFlowTokenSourceProvider{tokenOrchestrator: tokenOrchestrator}, nil
}
func (p DeviceFlowTokenSourceProvider) GetTokenSource(ctx context.Context) (oauth2.TokenSource, error) {
return GetDeviceFlowAuthTokenSource(ctx, p.tokenOrchestrator)
}
// GetDeviceFlowAuthTokenSource Returns the token source which would be used for device auth flow
func GetDeviceFlowAuthTokenSource(ctx context.Context, deviceFlowOrchestrator deviceflow.TokenOrchestrator) (oauth2.TokenSource, error) {
// explicitly ignore error while fetching token from cache.
authToken, err := deviceFlowOrchestrator.FetchTokenFromCacheOrRefreshIt(ctx, deviceFlowOrchestrator.Config.TokenRefreshGracePeriod)
if err != nil {
logger.Warnf(ctx, "Failed fetching from cache. Will restart the flow. Error: %v", err)
}
if authToken == nil {
// Fetch using auth flow
if authToken, err = deviceFlowOrchestrator.FetchTokenFromAuthFlow(ctx); err != nil {
logger.Errorf(ctx, "Error fetching token using auth flow due to %v", err)
return nil, err
}
}
return &pkce.SimpleTokenSource{
CachedToken: authToken,
}, nil
}