-
Notifications
You must be signed in to change notification settings - Fork 158
Expand file tree
/
Copy pathauth.go
More file actions
799 lines (739 loc) · 28.4 KB
/
auth.go
File metadata and controls
799 lines (739 loc) · 28.4 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
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
package gosnowflake
import (
"context"
"crypto/sha256"
"crypto/x509"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
sferrors "github.com/snowflakedb/gosnowflake/v2/internal/errors"
"io"
"net/http"
"net/url"
"os"
"runtime"
"slices"
"strconv"
"strings"
"time"
"github.com/golang-jwt/jwt/v5"
"github.com/snowflakedb/gosnowflake/v2/internal/compilation"
sfconfig "github.com/snowflakedb/gosnowflake/v2/internal/config"
internalos "github.com/snowflakedb/gosnowflake/v2/internal/os"
)
const (
clientType = "Go"
)
const (
clientStoreTemporaryCredential = "CLIENT_STORE_TEMPORARY_CREDENTIAL"
clientRequestMfaToken = "CLIENT_REQUEST_MFA_TOKEN"
idTokenAuthenticator = "ID_TOKEN"
)
// AuthType indicates the type of authentication in Snowflake
type AuthType = sfconfig.AuthType
const (
// AuthTypeSnowflake is the general username password authentication
AuthTypeSnowflake = sfconfig.AuthTypeSnowflake
// AuthTypeOAuth is the OAuth authentication
AuthTypeOAuth = sfconfig.AuthTypeOAuth
// AuthTypeExternalBrowser is to use a browser to access an Fed and perform SSO authentication
AuthTypeExternalBrowser = sfconfig.AuthTypeExternalBrowser
// AuthTypeOkta is to use a native okta URL to perform SSO authentication on Okta
AuthTypeOkta = sfconfig.AuthTypeOkta
// AuthTypeJwt is to use Jwt to perform authentication
AuthTypeJwt = sfconfig.AuthTypeJwt
// AuthTypeTokenAccessor is to use the provided token accessor and bypass authentication
AuthTypeTokenAccessor = sfconfig.AuthTypeTokenAccessor
// AuthTypeUsernamePasswordMFA is to use username and password with mfa
AuthTypeUsernamePasswordMFA = sfconfig.AuthTypeUsernamePasswordMFA
// AuthTypePat is to use programmatic access token
AuthTypePat = sfconfig.AuthTypePat
// AuthTypeOAuthAuthorizationCode is to use browser-based OAuth2 flow
AuthTypeOAuthAuthorizationCode = sfconfig.AuthTypeOAuthAuthorizationCode
// AuthTypeOAuthClientCredentials is to use non-interactive OAuth2 flow
AuthTypeOAuthClientCredentials = sfconfig.AuthTypeOAuthClientCredentials
// AuthTypeWorkloadIdentityFederation is to use CSP identity for authentication
AuthTypeWorkloadIdentityFederation = sfconfig.AuthTypeWorkloadIdentityFederation
)
func isOauthNativeFlow(authType AuthType) bool {
return authType == AuthTypeOAuthAuthorizationCode || authType == AuthTypeOAuthClientCredentials
}
var refreshOAuthTokenErrorCodes = []string{
strconv.Itoa(ErrMissingAccessATokenButRefreshTokenPresent),
invalidOAuthAccessTokenCode,
expiredOAuthAccessTokenCode,
}
// userAgent shows up in User-Agent HTTP header
var userAgent = fmt.Sprintf("%v/%v (%v-%v) %v/%v",
clientType,
SnowflakeGoDriverVersion,
runtime.GOOS,
runtime.GOARCH,
runtime.Compiler,
runtime.Version())
type authRequestClientEnvironment struct {
Application string `json:"APPLICATION"`
ApplicationPath string `json:"APPLICATION_PATH"`
Os string `json:"OS"`
OsVersion string `json:"OS_VERSION"`
OsDetails map[string]string `json:"OS_DETAILS,omitempty"`
Isa string `json:"ISA,omitempty"`
OCSPMode string `json:"OCSP_MODE"`
GoVersion string `json:"GO_VERSION"`
OAuthType string `json:"OAUTH_TYPE,omitempty"`
CertRevocationCheckMode string `json:"CERT_REVOCATION_CHECK_MODE,omitempty"`
Platform []string `json:"PLATFORM,omitempty"`
CoreVersion string `json:"CORE_VERSION,omitempty"`
CoreLoadError string `json:"CORE_LOAD_ERROR,omitempty"`
CoreFileName string `json:"CORE_FILE_NAME,omitempty"`
CgoEnabled bool `json:"CGO_ENABLED,omitempty"`
}
type authRequestData struct {
ClientAppID string `json:"CLIENT_APP_ID"`
ClientAppVersion string `json:"CLIENT_APP_VERSION"`
SvnRevision string `json:"SVN_REVISION"`
AccountName string `json:"ACCOUNT_NAME"`
LoginName string `json:"LOGIN_NAME,omitempty"`
Password string `json:"PASSWORD,omitempty"`
RawSAMLResponse string `json:"RAW_SAML_RESPONSE,omitempty"`
ExtAuthnDuoMethod string `json:"EXT_AUTHN_DUO_METHOD,omitempty"`
Passcode string `json:"PASSCODE,omitempty"`
Authenticator string `json:"AUTHENTICATOR,omitempty"`
SessionParameters map[string]interface{} `json:"SESSION_PARAMETERS,omitempty"`
ClientEnvironment authRequestClientEnvironment `json:"CLIENT_ENVIRONMENT"`
BrowserModeRedirectPort string `json:"BROWSER_MODE_REDIRECT_PORT,omitempty"`
ProofKey string `json:"PROOF_KEY,omitempty"`
Token string `json:"TOKEN,omitempty"`
Provider string `json:"PROVIDER,omitempty"`
}
type authRequest struct {
Data authRequestData `json:"data"`
}
type nameValueParameter struct {
Name string `json:"name"`
Value interface{} `json:"value"`
}
type authResponseSessionInfo struct {
DatabaseName string `json:"databaseName"`
SchemaName string `json:"schemaName"`
WarehouseName string `json:"warehouseName"`
RoleName string `json:"roleName"`
}
type authResponseMain struct {
Token string `json:"token,omitempty"`
Validity time.Duration `json:"validityInSeconds,omitempty"`
MasterToken string `json:"masterToken,omitempty"`
MasterValidity time.Duration `json:"masterValidityInSeconds"`
MfaToken string `json:"mfaToken,omitempty"`
MfaTokenValidity time.Duration `json:"mfaTokenValidityInSeconds"`
IDToken string `json:"idToken,omitempty"`
IDTokenValidity time.Duration `json:"idTokenValidityInSeconds"`
DisplayUserName string `json:"displayUserName"`
ServerVersion string `json:"serverVersion"`
FirstLogin bool `json:"firstLogin"`
RemMeToken string `json:"remMeToken"`
RemMeValidity time.Duration `json:"remMeValidityInSeconds"`
HealthCheckInterval time.Duration `json:"healthCheckInterval"`
NewClientForUpgrade string `json:"newClientForUpgrade"`
SessionID int64 `json:"sessionId"`
Parameters []nameValueParameter `json:"parameters"`
SessionInfo authResponseSessionInfo `json:"sessionInfo"`
TokenURL string `json:"tokenUrl,omitempty"`
SSOURL string `json:"ssoUrl,omitempty"`
ProofKey string `json:"proofKey,omitempty"`
}
type authResponse struct {
Data authResponseMain `json:"data"`
Message string `json:"message"`
Code string `json:"code"`
Success bool `json:"success"`
}
func postAuth(
ctx context.Context,
sr *snowflakeRestful,
client *http.Client,
params *url.Values,
headers map[string]string,
bodyCreator bodyCreatorType,
timeout time.Duration) (
data *authResponse, err error) {
params.Set(requestIDKey, getOrGenerateRequestIDFromContext(ctx).String())
params.Set(requestGUIDKey, NewUUID().String())
fullURL := sr.getFullURL(loginRequestPath, params)
logger.WithContext(ctx).Infof("full URL: %v", fullURL)
resp, err := sr.FuncAuthPost(ctx, client, fullURL, headers, bodyCreator, timeout, sr.MaxRetryCount)
if err != nil {
return nil, err
}
defer func() {
if closeErr := resp.Body.Close(); closeErr != nil {
logger.WithContext(ctx).Errorf("failed to close HTTP response body for %v. err: %v", fullURL, closeErr)
}
}()
if resp.StatusCode == http.StatusOK {
var respd authResponse
err = json.NewDecoder(resp.Body).Decode(&respd)
if err != nil {
logger.WithContext(ctx).Errorf("failed to decode JSON. err: %v", err)
return nil, err
}
return &respd, nil
}
switch resp.StatusCode {
case http.StatusBadGateway, http.StatusServiceUnavailable, http.StatusGatewayTimeout:
// service availability or connectivity issue. Most likely server side issue.
return nil, &SnowflakeError{
Number: ErrCodeServiceUnavailable,
SQLState: SQLStateConnectionWasNotEstablished,
Message: sferrors.ErrMsgServiceUnavailable,
MessageArgs: []interface{}{resp.StatusCode, fullURL},
}
case http.StatusUnauthorized, http.StatusForbidden:
// failed to connect to db. account name may be wrong
return nil, &SnowflakeError{
Number: ErrCodeFailedToConnect,
SQLState: SQLStateConnectionRejected,
Message: sferrors.ErrMsgFailedToConnect,
MessageArgs: []interface{}{resp.StatusCode, fullURL},
}
}
b, err := io.ReadAll(resp.Body)
if err != nil {
logger.WithContext(ctx).Errorf("failed to extract HTTP response body. err: %v", err)
return nil, err
}
logger.WithContext(ctx).Infof("HTTP: %v, URL: %v, Body: %v", resp.StatusCode, fullURL, b)
logger.WithContext(ctx).Infof("Header: %v", resp.Header)
return nil, &SnowflakeError{
Number: ErrFailedToAuth,
SQLState: SQLStateConnectionRejected,
Message: sferrors.ErrMsgFailedToAuth,
MessageArgs: []interface{}{resp.StatusCode, fullURL},
}
}
// Generates a map of headers needed to authenticate
// with Snowflake.
func getHeaders() map[string]string {
headers := make(map[string]string)
headers[httpHeaderContentType] = headerContentTypeApplicationJSON
headers[httpHeaderAccept] = headerAcceptTypeApplicationSnowflake
headers[httpClientAppID] = clientType
headers[httpClientAppVersion] = SnowflakeGoDriverVersion
headers[httpHeaderUserAgent] = userAgent
return headers
}
// Used to authenticate the user with Snowflake.
func authenticate(
ctx context.Context,
sc *snowflakeConn,
samlResponse []byte,
proofKey []byte,
) (resp *authResponseMain, err error) {
if sc.cfg.Authenticator == AuthTypeTokenAccessor {
logger.WithContext(ctx).Info("Bypass authentication using existing token from token accessor")
sessionInfo := authResponseSessionInfo{
DatabaseName: sc.cfg.Database,
SchemaName: sc.cfg.Schema,
WarehouseName: sc.cfg.Warehouse,
RoleName: sc.cfg.Role,
}
token, masterToken, sessionID := sc.cfg.TokenAccessor.GetTokens()
return &authResponseMain{
Token: token,
MasterToken: masterToken,
SessionID: sessionID,
SessionInfo: sessionInfo,
}, nil
}
headers := getHeaders()
// Get the current application path
applicationPath, err := os.Executable()
if err != nil {
logger.WithContext(ctx).Warnf("Failed to get executable path: %v", err)
applicationPath = "unknown"
}
oauthType := ""
switch sc.cfg.Authenticator {
case AuthTypeOAuthAuthorizationCode:
oauthType = "OAUTH_AUTHORIZATION_CODE"
case AuthTypeOAuthClientCredentials:
oauthType = "OAUTH_CLIENT_CREDENTIALS"
}
clientEnvironment := newAuthRequestClientEnvironment()
clientEnvironment.Application = sc.cfg.Application
clientEnvironment.ApplicationPath = applicationPath
clientEnvironment.OAuthType = oauthType
clientEnvironment.CertRevocationCheckMode = sc.cfg.CertRevocationCheckMode.String()
clientEnvironment.Platform = getDetectedPlatforms()
sessionParameters := make(map[string]interface{})
paramsMutex.Lock()
for k, v := range sc.cfg.Params {
// upper casing to normalize keys
sessionParameters[strings.ToUpper(k)] = *v
}
paramsMutex.Unlock()
sessionParameters[sessionClientValidateDefaultParameters] = sc.cfg.ValidateDefaultParameters != ConfigBoolFalse
if sc.cfg.ClientRequestMfaToken == ConfigBoolTrue {
sessionParameters[clientRequestMfaToken] = true
}
if sc.cfg.ClientStoreTemporaryCredential == ConfigBoolTrue {
sessionParameters[clientStoreTemporaryCredential] = true
}
bodyCreator := func() ([]byte, error) {
return createRequestBody(sc, sessionParameters, clientEnvironment, proofKey, samlResponse)
}
params := &url.Values{}
if sc.cfg.Database != "" {
params.Add("databaseName", sc.cfg.Database)
}
if sc.cfg.Schema != "" {
params.Add("schemaName", sc.cfg.Schema)
}
if sc.cfg.Warehouse != "" {
params.Add("warehouse", sc.cfg.Warehouse)
}
if sc.cfg.Role != "" {
params.Add("roleName", sc.cfg.Role)
}
logger.WithContext(ctx).Infof("Information for Auth: Host: %v, User: %v, Authenticator: %v, Params: %v, Protocol: %v, Port: %v, LoginTimeout: %v",
sc.rest.Host, sc.cfg.User, sc.cfg.Authenticator.String(), params, sc.rest.Protocol, sc.rest.Port, sc.rest.LoginTimeout)
respd, err := sc.rest.FuncPostAuth(ctx, sc.rest, sc.rest.getClientFor(sc.cfg.Authenticator), params, headers, bodyCreator, sc.rest.LoginTimeout)
if err != nil {
return nil, err
}
if !respd.Success {
logger.WithContext(ctx).Error("Authentication FAILED")
sc.rest.TokenAccessor.SetTokens("", "", -1)
if sessionParameters[clientRequestMfaToken] == true {
credentialsStorage.deleteCredential(newMfaTokenSpec(sc.cfg.Host, sc.cfg.User))
}
if sessionParameters[clientStoreTemporaryCredential] == true && sc.cfg.Authenticator == AuthTypeExternalBrowser {
credentialsStorage.deleteCredential(newIDTokenSpec(sc.cfg.Host, sc.cfg.User))
}
if sessionParameters[clientStoreTemporaryCredential] == true && isOauthNativeFlow(sc.cfg.Authenticator) {
credentialsStorage.deleteCredential(newOAuthAccessTokenSpec(sc.cfg.OauthTokenRequestURL, sc.cfg.User))
}
code, err := strconv.Atoi(respd.Code)
if err != nil {
return nil, err
}
return nil, exceptionTelemetry(&SnowflakeError{
Number: code,
SQLState: SQLStateConnectionRejected,
Message: respd.Message,
}, sc)
}
logger.WithContext(ctx).Info("Authentication SUCCESS")
sc.rest.TokenAccessor.SetTokens(respd.Data.Token, respd.Data.MasterToken, respd.Data.SessionID)
if sessionParameters[clientRequestMfaToken] == true {
token := respd.Data.MfaToken
credentialsStorage.setCredential(newMfaTokenSpec(sc.cfg.Host, sc.cfg.User), token)
}
if sessionParameters[clientStoreTemporaryCredential] == true {
token := respd.Data.IDToken
credentialsStorage.setCredential(newIDTokenSpec(sc.cfg.Host, sc.cfg.User), token)
}
return &respd.Data, nil
}
func newAuthRequestClientEnvironment() authRequestClientEnvironment {
var coreVersion string
var coreLoadError string
// Try to get minicore version, but don't block if it's not loaded yet
if !compilation.MinicoreEnabled {
logger.Trace("minicore disabled at compile time")
coreLoadError = "Minicore is disabled at compile time (built with -tags minicore_disabled)"
} else if strings.EqualFold(os.Getenv(disableMinicoreEnv), "true") {
logger.Trace("minicore loading disabled")
coreLoadError = "Minicore is disabled with SF_DISABLE_MINICORE env variable"
} else if mc := getMiniCore(); mc != nil {
var err error
coreVersion, err = mc.FullVersion()
if err != nil {
logger.Debugf("Minicore loading failed. %v", err)
var mcErr *miniCoreError
if errors.As(err, &mcErr) {
coreLoadError = fmt.Sprintf("Failed to load binary: %v", mcErr.errorType)
} else {
coreLoadError = "Failed to load binary: unknown"
}
}
} else {
// Minicore not loaded yet - this is expected during startup
coreVersion = ""
coreLoadError = "Minicore is still loading"
logger.Debugf("Minicore not yet loaded for client environment telemetry")
}
return authRequestClientEnvironment{
Os: runtime.GOOS,
OsVersion: osVersion,
OsDetails: internalos.GetOsDetails(),
Isa: runtime.GOARCH,
GoVersion: runtime.Version(),
CoreVersion: coreVersion,
CoreFileName: getMiniCoreFileName(),
CoreLoadError: coreLoadError,
CgoEnabled: compilation.CgoEnabled,
}
}
func createRequestBody(sc *snowflakeConn, sessionParameters map[string]interface{},
clientEnvironment authRequestClientEnvironment, proofKey []byte, samlResponse []byte,
) ([]byte, error) {
requestMain := authRequestData{
ClientAppID: clientType,
ClientAppVersion: SnowflakeGoDriverVersion,
AccountName: sc.cfg.Account,
SessionParameters: sessionParameters,
ClientEnvironment: clientEnvironment,
}
switch sc.cfg.Authenticator {
case AuthTypeExternalBrowser:
if sc.idToken != "" {
requestMain.Authenticator = idTokenAuthenticator
requestMain.Token = sc.idToken
requestMain.LoginName = sc.cfg.User
} else {
requestMain.ProofKey = string(proofKey)
requestMain.Token = string(samlResponse)
requestMain.LoginName = sc.cfg.User
requestMain.Authenticator = AuthTypeExternalBrowser.String()
}
case AuthTypeOAuth:
requestMain.LoginName = sc.cfg.User
requestMain.Authenticator = AuthTypeOAuth.String()
var err error
if requestMain.Token, err = sfconfig.GetToken(sc.cfg); err != nil {
return nil, fmt.Errorf("failed to get OAuth token: %w", err)
}
case AuthTypeOkta:
samlResponse, err := authenticateBySAML(
sc.ctx,
sc.rest,
sc.cfg.OktaURL,
sc.cfg.Application,
sc.cfg.Account,
sc.cfg.User,
sc.cfg.Password,
sc.cfg.DisableSamlURLCheck)
if err != nil {
return nil, err
}
requestMain.RawSAMLResponse = string(samlResponse)
case AuthTypeJwt:
requestMain.Authenticator = AuthTypeJwt.String()
jwtTokenString, err := prepareJWTToken(sc.cfg)
if err != nil {
return nil, err
}
requestMain.Token = jwtTokenString
case AuthTypePat:
logger.WithContext(sc.ctx).Info("Programmatic access token")
requestMain.Authenticator = AuthTypePat.String()
requestMain.LoginName = sc.cfg.User
var err error
if requestMain.Token, err = sfconfig.GetToken(sc.cfg); err != nil {
return nil, fmt.Errorf("failed to get PAT token: %w", err)
}
case AuthTypeSnowflake:
logger.WithContext(sc.ctx).Debug("Username and password")
requestMain.LoginName = sc.cfg.User
requestMain.Password = sc.cfg.Password
switch {
case sc.cfg.PasscodeInPassword:
requestMain.ExtAuthnDuoMethod = "passcode"
case sc.cfg.Passcode != "":
requestMain.Passcode = sc.cfg.Passcode
requestMain.ExtAuthnDuoMethod = "passcode"
}
case AuthTypeUsernamePasswordMFA:
logger.WithContext(sc.ctx).Debug("Username and password MFA")
requestMain.LoginName = sc.cfg.User
requestMain.Password = sc.cfg.Password
switch {
case sc.mfaToken != "":
requestMain.Token = sc.mfaToken
case sc.cfg.PasscodeInPassword:
requestMain.ExtAuthnDuoMethod = "passcode"
case sc.cfg.Passcode != "":
requestMain.Passcode = sc.cfg.Passcode
requestMain.ExtAuthnDuoMethod = "passcode"
}
case AuthTypeOAuthAuthorizationCode:
logger.WithContext(sc.ctx).Debug("OAuth authorization code")
token, err := authenticateByAuthorizationCode(sc)
if err != nil {
return nil, err
}
requestMain.LoginName = sc.cfg.User
requestMain.Token = token
case AuthTypeOAuthClientCredentials:
logger.WithContext(sc.ctx).Debug("OAuth client credentials")
oauthClient, err := newOauthClient(sc.ctx, sc.cfg, sc)
if err != nil {
return nil, err
}
token, err := oauthClient.authenticateByOAuthClientCredentials()
if err != nil {
return nil, err
}
requestMain.LoginName = sc.cfg.User
requestMain.Token = token
case AuthTypeWorkloadIdentityFederation:
logger.WithContext(sc.ctx).Debug("Workload Identity Federation")
wifAttestationProvider := createWifAttestationProvider(sc.ctx, sc.cfg, sc.telemetry)
wifAttestation, err := wifAttestationProvider.getAttestation(sc.cfg.WorkloadIdentityProvider)
if err != nil {
return nil, err
}
if wifAttestation == nil {
return nil, errors.New("workload identity federation attestation is not available, please check your configuration")
}
requestMain.Authenticator = AuthTypeWorkloadIdentityFederation.String()
requestMain.Token = wifAttestation.Credential
requestMain.Provider = wifAttestation.ProviderType
}
logger.WithContext(sc.ctx).Debugf("Request body is created for the authentication. Authenticator: %s, User: %s, Account: %s", sc.cfg.Authenticator.String(), sc.cfg.User, sc.cfg.Account)
authRequest := authRequest{
Data: requestMain,
}
jsonBody, err := json.Marshal(authRequest)
if err != nil {
logger.WithContext(sc.ctx).Errorf("Failed to marshal JSON. err: %v", err)
return nil, err
}
return jsonBody, nil
}
type oauthLockKey struct {
tokenRequestURL string
user string
flowType string
}
func newOAuthAuthorizationCodeLockKey(tokenRequestURL, user string) *oauthLockKey {
return &oauthLockKey{
tokenRequestURL: tokenRequestURL,
user: user,
flowType: "authorization_code",
}
}
func newRefreshTokenLockKey(tokenRequestURL, user string) *oauthLockKey {
return &oauthLockKey{
tokenRequestURL: tokenRequestURL,
user: user,
flowType: "refresh_token",
}
}
func (o *oauthLockKey) lockID() string {
return o.tokenRequestURL + "|" + o.user + "|" + o.flowType
}
func authenticateByAuthorizationCode(sc *snowflakeConn) (string, error) {
oauthClient, err := newOauthClient(sc.ctx, sc.cfg, sc)
if err != nil {
return "", err
}
if !isEligibleForParallelLogin(sc.cfg, sc.cfg.ClientStoreTemporaryCredential) {
return oauthClient.authenticateByOAuthAuthorizationCode()
}
lockKey := newOAuthAuthorizationCodeLockKey(oauthClient.tokenURL(), sc.cfg.User)
valueAwaiter := valueAwaitHolder.get(lockKey)
defer valueAwaiter.resumeOne()
token, err := awaitValue(valueAwaiter, func() (string, error) {
return credentialsStorage.getCredential(newOAuthAccessTokenSpec(oauthClient.tokenURL(), sc.cfg.User)), nil
}, func(s string, err error) bool {
return s != ""
}, func() string {
return ""
})
if err != nil || token != "" {
return token, err
}
token, err = oauthClient.authenticateByOAuthAuthorizationCode()
if err != nil {
return "", err
}
valueAwaiter.done()
return token, err
}
// Generate a JWT token in string given the configuration
func prepareJWTToken(config *Config) (string, error) {
if config.PrivateKey == nil {
return "", errors.New("trying to use keypair authentication, but PrivateKey was not provided in the driver config")
}
logger.Debug("preparing JWT for keypair authentication")
pubBytes, err := x509.MarshalPKIXPublicKey(config.PrivateKey.Public())
if err != nil {
return "", err
}
hash := sha256.Sum256(pubBytes)
accountName := sfconfig.ExtractAccountName(config.Account)
userName := strings.ToUpper(config.User)
issueAtTime := time.Now().UTC()
jwtClaims := jwt.MapClaims{
"iss": fmt.Sprintf("%s.%s.%s", accountName, userName, "SHA256:"+base64.StdEncoding.EncodeToString(hash[:])),
"sub": fmt.Sprintf("%s.%s", accountName, userName),
"iat": issueAtTime.Unix(),
"nbf": time.Date(2015, 10, 10, 12, 0, 0, 0, time.UTC).Unix(),
"exp": issueAtTime.Add(config.JWTExpireTimeout).Unix(),
}
token := jwt.NewWithClaims(jwt.SigningMethodRS256, jwtClaims)
tokenString, err := token.SignedString(config.PrivateKey)
if err != nil {
return "", err
}
logger.Debugf("successfully generated JWT with following claims: %v", jwtClaims)
return tokenString, err
}
type tokenLockKey struct {
snowflakeHost string
user string
tokenType string
}
func newMfaTokenLockKey(snowflakeHost, user string) *tokenLockKey {
return &tokenLockKey{
snowflakeHost: snowflakeHost,
user: user,
tokenType: "MFA",
}
}
func newIDTokenLockKey(snowflakeHost, user string) *tokenLockKey {
return &tokenLockKey{
snowflakeHost: snowflakeHost,
user: user,
tokenType: "ID",
}
}
func (m *tokenLockKey) lockID() string {
return m.snowflakeHost + "|" + m.user + "|" + m.tokenType
}
func authenticateWithConfig(sc *snowflakeConn) error {
var authData *authResponseMain
var samlResponse []byte
var proofKey []byte
var err error
mfaTokenLockKey := newMfaTokenLockKey(sc.cfg.Host, sc.cfg.User)
idTokenLockKey := newIDTokenLockKey(sc.cfg.Host, sc.cfg.User)
if sc.cfg.Authenticator == AuthTypeExternalBrowser || sc.cfg.Authenticator == AuthTypeOAuthAuthorizationCode || sc.cfg.Authenticator == AuthTypeOAuthClientCredentials {
if (runtime.GOOS == "windows" || runtime.GOOS == "darwin") && sc.cfg.ClientStoreTemporaryCredential == sfconfig.BoolNotSet {
sc.cfg.ClientStoreTemporaryCredential = ConfigBoolTrue
}
if sc.cfg.Authenticator == AuthTypeExternalBrowser {
if isEligibleForParallelLogin(sc.cfg, sc.cfg.ClientStoreTemporaryCredential) {
valueAwaiter := valueAwaitHolder.get(idTokenLockKey)
defer valueAwaiter.resumeOne()
sc.idToken, _ = awaitValue(valueAwaiter, func() (string, error) {
credential := credentialsStorage.getCredential(newIDTokenSpec(sc.cfg.Host, sc.cfg.User))
return credential, nil
}, func(s string, err error) bool {
return s != ""
}, func() string {
return ""
})
} else if sc.cfg.ClientStoreTemporaryCredential == ConfigBoolTrue {
sc.idToken = credentialsStorage.getCredential(newIDTokenSpec(sc.cfg.Host, sc.cfg.User))
}
}
// Disable console login by default
if sc.cfg.DisableConsoleLogin == sfconfig.BoolNotSet {
sc.cfg.DisableConsoleLogin = ConfigBoolTrue
}
}
if sc.cfg.Authenticator == AuthTypeUsernamePasswordMFA {
if (runtime.GOOS == "windows" || runtime.GOOS == "darwin") && sc.cfg.ClientRequestMfaToken == sfconfig.BoolNotSet {
sc.cfg.ClientRequestMfaToken = ConfigBoolTrue
}
if isEligibleForParallelLogin(sc.cfg, sc.cfg.ClientRequestMfaToken) {
valueAwaiter := valueAwaitHolder.get(mfaTokenLockKey)
defer valueAwaiter.resumeOne()
sc.mfaToken, _ = awaitValue(valueAwaiter, func() (string, error) {
credential := credentialsStorage.getCredential(newMfaTokenSpec(sc.cfg.Host, sc.cfg.User))
return credential, nil
}, func(s string, err error) bool {
return s != ""
}, func() string {
return ""
})
} else if sc.cfg.ClientRequestMfaToken == ConfigBoolTrue {
sc.mfaToken = credentialsStorage.getCredential(newMfaTokenSpec(sc.cfg.Host, sc.cfg.User))
}
}
logger.WithContext(sc.ctx).Infof("Authenticating via %v", sc.cfg.Authenticator.String())
switch sc.cfg.Authenticator {
case AuthTypeExternalBrowser:
if sc.idToken == "" {
samlResponse, proofKey, err = authenticateByExternalBrowser(
sc.ctx,
sc.rest,
sc.cfg.Authenticator.String(),
sc.cfg.Application,
sc.cfg.Account,
sc.cfg.User,
sc.cfg.ExternalBrowserTimeout,
sc.cfg.DisableConsoleLogin)
if err != nil {
sc.cleanup()
return err
}
}
}
authData, err = authenticate(
sc.ctx,
sc,
samlResponse,
proofKey)
if err != nil {
var se *SnowflakeError
if errors.As(err, &se) && slices.Contains(refreshOAuthTokenErrorCodes, strconv.Itoa(se.Number)) {
credentialsStorage.deleteCredential(newOAuthAccessTokenSpec(sc.cfg.OauthTokenRequestURL, sc.cfg.User))
if sc.cfg.Authenticator == AuthTypeOAuthAuthorizationCode {
doRefreshTokenWithLock(sc)
}
// if refreshing succeeds for authorization code, we will take a token from cache
// if it fails, we will just run the full flow
authData, err = authenticate(sc.ctx, sc, nil, nil)
}
if err != nil {
sc.cleanup()
return err
}
}
if sc.cfg.Authenticator == AuthTypeUsernamePasswordMFA && isEligibleForParallelLogin(sc.cfg, sc.cfg.ClientRequestMfaToken) {
valueAwaiter := valueAwaitHolder.get(mfaTokenLockKey)
valueAwaiter.done()
}
if sc.cfg.Authenticator == AuthTypeExternalBrowser && isEligibleForParallelLogin(sc.cfg, sc.cfg.ClientStoreTemporaryCredential) {
valueAwaiter := valueAwaitHolder.get(idTokenLockKey)
valueAwaiter.done()
}
sc.populateSessionParameters(authData.Parameters)
sc.configureTelemetry()
sc.ctx = context.WithValue(sc.ctx, SFSessionIDKey, authData.SessionID)
return nil
}
func doRefreshTokenWithLock(sc *snowflakeConn) {
if oauthClient, err := newOauthClient(sc.ctx, sc.cfg, sc); err != nil {
logger.Warnf("failed to create oauth client. %v", err)
} else {
lockKey := newRefreshTokenLockKey(oauthClient.tokenURL(), sc.cfg.User)
if _, err = getValueWithLock(chooseLockerForAuth(sc.cfg), lockKey, func() (string, error) {
if err = oauthClient.refreshToken(); err != nil {
logger.Warnf("cannot refresh token. %v", err)
credentialsStorage.deleteCredential(newOAuthRefreshTokenSpec(sc.cfg.OauthTokenRequestURL, sc.cfg.User))
return "", err
}
return "", nil
}); err != nil {
logger.Warnf("failed to refresh token with lock. %v", err)
}
}
}
func chooseLockerForAuth(cfg *Config) locker {
if cfg.SingleAuthenticationPrompt == ConfigBoolFalse {
return noopLocker
}
if cfg.User == "" {
return noopLocker
}
return exclusiveLocker
}
func isEligibleForParallelLogin(cfg *Config, cacheEnabled ConfigBool) bool {
return cfg.SingleAuthenticationPrompt != ConfigBoolFalse && cfg.User != "" && cacheEnabled == ConfigBoolTrue
}