-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathauth_oauth.go
More file actions
531 lines (437 loc) · 15.3 KB
/
Copy pathauth_oauth.go
File metadata and controls
531 lines (437 loc) · 15.3 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
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
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
// Copyright 2026 Keyfactor
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package auth_providers
import (
"context"
"crypto/x509"
"fmt"
"log"
"net/http"
"os"
"strings"
"sync"
"time"
"golang.org/x/oauth2"
"golang.org/x/oauth2/clientcredentials"
)
const (
// DefaultKeyfactorAuthPort is the default port for Keyfactor authentication
DefaultKeyfactorAuthPort = "8444"
// DefaultTokenPrefix is the default token prefix for Keyfactor authentication headers
DefaultTokenPrefix = "Bearer"
// EnvKeyfactorClientID is the environment variable used to set the Client ID for oauth Client credentials authentication
EnvKeyfactorClientID = "KEYFACTOR_AUTH_CLIENT_ID"
// EnvKeyfactorClientSecret is the environment variable used to set the Client secret for oauth Client credentials authentication
EnvKeyfactorClientSecret = "KEYFACTOR_AUTH_CLIENT_SECRET"
// EnvKeyfactorAuthTokenURL EnvCommandTokenURL is the environment variable used to set the token URL for oauth Client credentials authentication
EnvKeyfactorAuthTokenURL = "KEYFACTOR_AUTH_TOKEN_URL"
// EnvKeyfactorAccessToken is the environment variable used to set the access token for oauth Client credentials authentication
EnvKeyfactorAccessToken = "KEYFACTOR_AUTH_ACCESS_TOKEN"
// EnvKeyfactorAuthAudience is the environment variable used to set the audience for oauth Client credentials
//authentication
EnvKeyfactorAuthAudience = "KEYFACTOR_AUTH_AUDIENCE"
// EnvKeyfactorAuthScopes is the environment variable used to set the scopes for oauth Client credentials authentication
EnvKeyfactorAuthScopes = "KEYFACTOR_AUTH_SCOPES"
// EnvAuthCACert is a path to a CA certificate for the OAuth Client credentials authentication
EnvAuthCACert = "KEYFACTOR_AUTH_CA_CERT"
)
var (
// DefaultScopes is the default scopes for Keyfactor authentication
DefaultScopes []string
)
// OAuth Authenticator
var _ Authenticator = &OAuthAuthenticator{}
// OAuthAuthenticator is an Authenticator that uses OAuth2 for authentication.
type OAuthAuthenticator struct {
Client *http.Client
}
type oauth2Transport struct {
base http.RoundTripper
src oauth2.TokenSource
}
// GetHttpClient returns the http client
func (a *OAuthAuthenticator) GetHttpClient() (*http.Client, error) {
return a.Client, nil
}
// CommandConfigOauth represents the configuration needed for authentication to Keyfactor Command API using OAuth2.
type CommandConfigOauth struct {
// CommandAuthConfig is a reference to the base configuration needed for authentication to Keyfactor Command API
CommandAuthConfig
// ClientID is the Client ID for OAuth authentication
ClientID string `json:"client_id,omitempty" yaml:"client_id,omitempty"`
// ClientSecret is the Client secret for OAuth authentication
ClientSecret string `json:"client_secret,omitempty" yaml:"client_secret,omitempty"`
// Audience is the audience for OAuth authentication
Audience string `json:"audience,omitempty" yaml:"audience,omitempty"`
// Scopes is the scopes for OAuth authentication
Scopes []string `json:"scopes,omitempty" yaml:"scopes,omitempty"`
// CACertificatePath is the path to the CA certificate for OAuth authentication
CACertificatePath string `json:"idp_ca_cert,omitempty" yaml:"idp_ca_cert,omitempty"`
// CACertificates is the CA certificates for authentication
CACertificates []*x509.Certificate `json:"-"`
// AccessToken is the access token for OAuth authentication
AccessToken string `json:"access_token,omitempty" yaml:"access_token,omitempty"`
// RefreshToken is the refresh token for OAuth authentication
RefreshToken string `json:"refresh_token,omitempty" yaml:"refresh_token,omitempty"`
// Expiry is the expiry time of the access token
Expiry time.Time `json:"expiry,omitempty" yaml:"expiry,omitempty"`
// TokenURL is the token URL for OAuth authentication
TokenURL string `json:"token_url,omitempty" yaml:"token_url,omitempty"`
// unexported: lazily initialized, shared across GetHttpClient() calls
tokenSource oauth2.TokenSource
tsMu sync.Mutex
}
// NewOAuthAuthenticatorBuilder creates a new CommandConfigOauth instance.
func NewOAuthAuthenticatorBuilder() *CommandConfigOauth {
return &CommandConfigOauth{}
}
// WithClientId sets the Client ID for OAuth authentication.
func (b *CommandConfigOauth) WithClientId(clientId string) *CommandConfigOauth {
b.ClientID = clientId
return b
}
// WithClientSecret sets the Client secret for OAuth authentication.
func (b *CommandConfigOauth) WithClientSecret(clientSecret string) *CommandConfigOauth {
b.ClientSecret = clientSecret
return b
}
// WithTokenUrl sets the token URL for OAuth authentication.
func (b *CommandConfigOauth) WithTokenUrl(tokenUrl string) *CommandConfigOauth {
b.TokenURL = tokenUrl
return b
}
// WithScopes sets the scopes for OAuth authentication.
func (b *CommandConfigOauth) WithScopes(scopes []string) *CommandConfigOauth {
b.Scopes = scopes
return b
}
// WithAudience sets the audience for OAuth authentication.
func (b *CommandConfigOauth) WithAudience(audience string) *CommandConfigOauth {
b.Audience = audience
return b
}
// WithCaCertificatePath sets the CA certificate path for OAuth authentication.
func (b *CommandConfigOauth) WithCaCertificatePath(caCertificatePath string) *CommandConfigOauth {
b.CACertificatePath = caCertificatePath
return b
}
// WithCaCertificates sets the CA certificates for OAuth authentication.
func (b *CommandConfigOauth) WithCaCertificates(caCertificates []*x509.Certificate) *CommandConfigOauth {
b.CACertificates = caCertificates
return b
}
// WithAccessToken sets the access token for OAuth authentication.
func (b *CommandConfigOauth) WithAccessToken(accessToken string) *CommandConfigOauth {
if accessToken != "" {
b.AccessToken = accessToken
}
return b
}
func (b *CommandConfigOauth) WithHttpClient(httpClient *http.Client) *CommandConfigOauth {
b.HttpClient = httpClient
return b
}
// GetHttpClient returns an HTTP client for oAuth authentication.
func (b *CommandConfigOauth) GetHttpClient() (*http.Client, error) {
cErr := b.ValidateAuthConfig()
if cErr != nil {
return nil, cErr
}
var client http.Client
baseTransport, tErr := b.BuildTransport()
if tErr != nil {
return nil, tErr
}
if b.AccessToken != "" {
client.Transport = &oauth2.Transport{
Base: baseTransport,
Source: oauth2.StaticTokenSource(
&oauth2.Token{
AccessToken: b.AccessToken,
TokenType: DefaultTokenPrefix,
},
),
}
return &client, nil
}
config := &clientcredentials.Config{
ClientID: b.ClientID,
ClientSecret: b.ClientSecret,
TokenURL: b.TokenURL,
Scopes: b.Scopes,
}
if b.Audience != "" {
config.EndpointParams = map[string][]string{
"audience": {b.Audience},
}
}
if len(b.Scopes) == 0 {
b.Scopes = DefaultScopes
}
ctx := context.WithValue(context.Background(), oauth2.HTTPClient, &http.Client{Transport: baseTransport})
// Lazily initialize the token source and cache it
b.tsMu.Lock()
if b.tokenSource == nil {
log.Printf("[DEBUG] Initializing OAuth2 token source for client ID: %s", b.ClientID)
b.tokenSource = config.TokenSource(ctx)
}
tokenSource := b.tokenSource
b.tsMu.Unlock()
client = http.Client{
Transport: &oauth2Transport{
base: baseTransport,
src: tokenSource,
},
}
return &client, nil
}
// Build creates an OAuth authenticator.
func (b *CommandConfigOauth) Build() (Authenticator, error) {
client, cErr := b.GetHttpClient()
if cErr != nil {
return nil, cErr
}
return &OAuthAuthenticator{Client: client}, nil
}
// LoadConfig loads the configuration for Keyfactor Command API using OAuth2.
func (b *CommandConfigOauth) LoadConfig(profile, path string, silentLoad bool) (*Server, error) {
serverConfig, sErr := b.CommandAuthConfig.LoadConfig(profile, path, silentLoad)
if sErr != nil {
if !silentLoad {
return nil, sErr
}
// if silentLoad is true, return nil and nil
return nil, nil
}
if !silentLoad {
b.ClientID = serverConfig.ClientID
b.ClientSecret = serverConfig.ClientSecret
b.TokenURL = serverConfig.OAuthTokenUrl
b.CACertificatePath = serverConfig.CACertPath
} else {
if b.ClientID == "" {
b.ClientID = serverConfig.ClientID
}
if b.ClientSecret == "" {
b.ClientSecret = serverConfig.ClientSecret
}
if b.TokenURL == "" {
b.TokenURL = serverConfig.OAuthTokenUrl
}
//if b.AccessToken == "" {
// b.AccessToken = serverConfig.AccessToken
//}
if b.Audience == "" {
b.Audience = serverConfig.Audience
}
if b.Scopes == nil || len(b.Scopes) == 0 {
b.Scopes = serverConfig.Scopes
}
if b.CACertificatePath == "" {
b.CACertificatePath = serverConfig.CACertPath
}
}
return serverConfig, nil
}
// ValidateAuthConfig validates the configuration for Keyfactor Command API using OAuth2.
func (b *CommandConfigOauth) ValidateAuthConfig() error {
silentLoad := true
if b.CommandAuthConfig.ConfigProfile != "" {
silentLoad = false
} else if b.CommandAuthConfig.ConfigFilePath != "" {
silentLoad = false
}
serverConfig, cErr := b.CommandAuthConfig.LoadConfig(
b.CommandAuthConfig.ConfigProfile,
b.CommandAuthConfig.ConfigFilePath,
silentLoad,
)
if !silentLoad && cErr != nil {
return cErr
}
if b.AccessToken == "" {
// check if access token is set in the environment
if accessToken, ok := os.LookupEnv(EnvKeyfactorAccessToken); ok {
b.AccessToken = accessToken
} else {
// check if client ID, client secret, and token URL are provided
if b.ClientID == "" {
if clientId, idOk := os.LookupEnv(EnvKeyfactorClientID); idOk {
b.ClientID = clientId
} else {
if serverConfig != nil && serverConfig.ClientID != "" {
b.ClientID = serverConfig.ClientID
} else {
return fmt.Errorf("client ID or environment variable %s is required", EnvKeyfactorClientID)
}
}
}
if b.ClientSecret == "" {
if clientSecret, sOk := os.LookupEnv(EnvKeyfactorClientSecret); sOk {
b.ClientSecret = clientSecret
} else {
if serverConfig != nil && serverConfig.ClientSecret != "" {
b.ClientSecret = serverConfig.ClientSecret
} else {
return fmt.Errorf(
"client secret or environment variable %s is required",
EnvKeyfactorClientSecret,
)
}
}
}
if b.TokenURL == "" {
if tokenUrl, uOk := os.LookupEnv(EnvKeyfactorAuthTokenURL); uOk {
b.TokenURL = tokenUrl
} else {
if serverConfig != nil && serverConfig.OAuthTokenUrl != "" {
b.TokenURL = serverConfig.OAuthTokenUrl
} else {
return fmt.Errorf(
"token URL or environment variable %s is required",
EnvKeyfactorAuthTokenURL,
)
}
}
}
}
}
if b.Audience == "" {
if audience, ok := os.LookupEnv(EnvKeyfactorAuthAudience); ok {
b.Audience = audience
} else {
if serverConfig != nil && serverConfig.Audience != "" {
b.Audience = serverConfig.Audience
}
}
}
if len(b.Scopes) == 0 {
if scopes, ok := os.LookupEnv(EnvKeyfactorAuthScopes); ok {
// split the scopes by comma
b.Scopes = strings.Split(scopes, ",")
} else {
if serverConfig != nil && len(serverConfig.Scopes) > 0 {
b.Scopes = serverConfig.Scopes
} else {
b.Scopes = DefaultScopes
}
}
}
return b.CommandAuthConfig.ValidateAuthConfig()
}
// Authenticate authenticates to Keyfactor Command API using OAuth2.
func (b *CommandConfigOauth) Authenticate() error {
// validate auth config
vErr := b.ValidateAuthConfig()
if vErr != nil {
return vErr
}
// create oauth Client
oauthy, err := b.GetHttpClient()
if err != nil {
return err
} else if oauthy == nil {
return fmt.Errorf("unable to create http client")
}
b.SetClient(oauthy)
//b.DefaultHttpClient = oauthy
aErr := b.CommandAuthConfig.Authenticate()
if aErr != nil {
return aErr
}
return nil
}
// GetServerConfig returns the server configuration for Keyfactor Command API using OAuth2.
func (b *CommandConfigOauth) GetServerConfig() *Server {
server := Server{
Host: b.CommandHostName,
Port: b.CommandPort,
ClientID: b.ClientID,
ClientSecret: b.ClientSecret,
AccessToken: b.AccessToken,
OAuthTokenUrl: b.TokenURL,
APIPath: b.CommandAPIPath,
Scopes: b.Scopes,
Audience: b.Audience,
//AuthProvider: AuthProvider{},
SkipTLSVerify: b.SkipVerify,
CACertPath: b.CommandCACert,
AuthType: "oauth",
}
return &server
}
// GetAccessToken returns the OAuth2 token source for the given configuration.
func (b *CommandConfigOauth) GetAccessToken() (*oauth2.Token, error) {
if b == nil {
return nil, fmt.Errorf("CommandConfigOauth is nil")
}
_ = b.ValidateAuthConfig() // sets client config if not already set but eats the error so that we can return and
// error fetching the token
if b.AccessToken != "" && (b.ClientID == "" || b.ClientSecret == "" || b.TokenURL == "") {
log.Printf("[DEBUG] Access token is explicitly set, and no client credentials are provided. Using static token source.")
return &oauth2.Token{
AccessToken: b.AccessToken,
TokenType: DefaultTokenPrefix,
Expiry: b.Expiry,
}, nil
}
log.Printf("[DEBUG] Getting OAuth2 token source for client ID: %s", b.ClientID)
if b.ClientID == "" || b.ClientSecret == "" || b.TokenURL == "" {
return nil, fmt.Errorf("client ID, client secret, and token URL must be provided")
}
config := &clientcredentials.Config{
ClientID: b.ClientID,
ClientSecret: b.ClientSecret,
TokenURL: b.TokenURL,
Scopes: b.Scopes,
}
if b.Audience != "" {
log.Printf("[DEBUG] Setting audience for OAuth2 token source: %s", b.Audience)
config.EndpointParams = map[string][]string{
"audience": {b.Audience},
}
}
ctx := context.Background()
log.Printf("[DEBUG] Returning call config.TokenSource() for client ID: %s", b.ClientID)
tokenSource := config.TokenSource(ctx)
if tokenSource == nil {
return nil, fmt.Errorf("failed to create token source for client ID: %s", b.ClientID)
}
token, tErr := tokenSource.Token()
if tErr != nil {
return nil, fmt.Errorf("failed to retrieve token for client ID %s: %w", b.ClientID, tErr)
}
if token == nil || token.AccessToken == "" {
return nil, fmt.Errorf("received empty OAuth token for client ID: %s", b.ClientID)
}
return token, nil
}
// RoundTrip executes a single HTTP transaction, adding the OAuth2 token to the request
func (t *oauth2Transport) RoundTrip(req *http.Request) (*http.Response, error) {
log.Printf("[DEBUG] Attempting to get oAuth token from: %s %s", req.Method, req.URL)
token, err := t.src.Token()
if err != nil {
return nil, fmt.Errorf("failed to retrieve OAuth token: %w", err)
}
if token == nil || token.AccessToken == "" {
return nil, fmt.Errorf("received empty OAuth token")
}
// Clone the request to avoid mutating the original
log.Printf("[DEBUG] Adding oAuth token to request: %s %s", req.Method, req.URL)
reqCopy := req.Clone(req.Context())
token.SetAuthHeader(reqCopy)
requestCurlStr, _ := RequestToCurl(reqCopy)
log.Printf("[TRACE] curl command: %s", requestCurlStr)
return t.base.RoundTrip(reqCopy)
}