forked from snowflakedb/gosnowflake
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauth_oauth.go
More file actions
459 lines (411 loc) · 14.7 KB
/
auth_oauth.go
File metadata and controls
459 lines (411 loc) · 14.7 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
package gosnowflake
import (
"bufio"
"bytes"
"cmp"
"context"
"encoding/json"
"errors"
"fmt"
"html"
"io"
"net"
"net/http"
"net/url"
"strconv"
"strings"
"time"
"golang.org/x/oauth2"
"golang.org/x/oauth2/clientcredentials"
)
const (
oauthSuccessHTML = `<!DOCTYPE html><html><head><meta charset="UTF-8"/>
<title>OAuth for Snowflake</title></head>
<body>
OAuth authentication completed successfully.
</body></html>`
localApplicationClientCredentials = "LOCAL_APPLICATION"
)
var defaultAuthorizationCodeProviderFactory = func() authorizationCodeProvider {
return &browserBasedAuthorizationCodeProvider{}
}
type oauthClient struct {
ctx context.Context
cfg *Config
client *http.Client
port int
redirectURITemplate string
authorizationCodeProviderFactory func() authorizationCodeProvider
}
func newOauthClient(ctx context.Context, cfg *Config, sc *snowflakeConn) (*oauthClient, error) {
port := 0
if cfg.OauthRedirectURI != "" {
logger.Debugf("Using oauthRedirectUri from config: %v", cfg.OauthRedirectURI)
uri, err := url.Parse(cfg.OauthRedirectURI)
if err != nil {
return nil, err
}
portStr := uri.Port()
if portStr != "" {
if port, err = strconv.Atoi(portStr); err != nil {
return nil, err
}
}
}
redirectURITemplate := ""
if cfg.OauthRedirectURI == "" {
redirectURITemplate = "http://127.0.0.1:%v"
}
logger.Debugf("Redirect URI template: %v, port: %v", redirectURITemplate, port)
transport, err := newTransportFactory(cfg, sc.telemetry).createTransport()
if err != nil {
return nil, err
}
client := &http.Client{
Transport: transport,
}
return &oauthClient{
ctx: context.WithValue(ctx, oauth2.HTTPClient, client),
cfg: cfg,
client: client,
port: port,
redirectURITemplate: redirectURITemplate,
authorizationCodeProviderFactory: defaultAuthorizationCodeProviderFactory,
}, nil
}
type oauthBrowserResult struct {
accessToken string
refreshToken string
err error
}
func (oauthClient *oauthClient) authenticateByOAuthAuthorizationCode() (string, error) {
accessTokenSpec := oauthClient.accessTokenSpec()
if oauthClient.cfg.ClientStoreTemporaryCredential == ConfigBoolTrue {
if accessToken := credentialsStorage.getCredential(accessTokenSpec); accessToken != "" {
logger.Debugf("Access token retrieved from cache")
return accessToken, nil
}
if refreshToken := credentialsStorage.getCredential(oauthClient.refreshTokenSpec()); refreshToken != "" {
return "", &SnowflakeError{Number: ErrMissingAccessATokenButRefreshTokenPresent}
}
}
logger.Debugf("Access token not present in cache, running full auth code flow")
resultChan := make(chan oauthBrowserResult, 1)
tcpListener, callbackPort, err := oauthClient.setupListener()
if err != nil {
return "", err
}
defer func() {
logger.Debug("Closing tcp listener")
if err := tcpListener.Close(); err != nil {
logger.Warnf("error while closing TCP listener. %v", err)
}
}()
go GoroutineWrapper(oauthClient.ctx, func() {
resultChan <- oauthClient.doAuthenticateByOAuthAuthorizationCode(tcpListener, callbackPort)
})
select {
case <-time.After(oauthClient.cfg.ExternalBrowserTimeout):
return "", errors.New("authentication via browser timed out")
case result := <-resultChan:
if oauthClient.cfg.ClientStoreTemporaryCredential == ConfigBoolTrue {
logger.Debug("saving oauth access token in cache")
credentialsStorage.setCredential(oauthClient.accessTokenSpec(), result.accessToken)
credentialsStorage.setCredential(oauthClient.refreshTokenSpec(), result.refreshToken)
}
return result.accessToken, result.err
}
}
func (oauthClient *oauthClient) doAuthenticateByOAuthAuthorizationCode(tcpListener *net.TCPListener, callbackPort int) oauthBrowserResult {
authCodeProvider := oauthClient.authorizationCodeProviderFactory()
successChan := make(chan []byte)
errChan := make(chan error)
responseBodyChan := make(chan string, 2)
closeListenerChan := make(chan bool, 2)
defer func() {
closeListenerChan <- true
close(successChan)
close(errChan)
close(responseBodyChan)
close(closeListenerChan)
}()
logger.Debugf("opening socket on port %v", callbackPort)
defer func(tcpListener *net.TCPListener) {
<-closeListenerChan
}(tcpListener)
go handleOAuthSocket(tcpListener, successChan, errChan, responseBodyChan, closeListenerChan)
oauth2cfg := oauthClient.buildAuthorizationCodeConfig(callbackPort)
codeVerifier := authCodeProvider.createCodeVerifier()
state := authCodeProvider.createState()
authorizationURL := oauth2cfg.AuthCodeURL(state, oauth2.S256ChallengeOption(codeVerifier))
if err := authCodeProvider.run(authorizationURL); err != nil {
responseBodyChan <- err.Error()
closeListenerChan <- true
return oauthBrowserResult{"", "", err}
}
err := <-errChan
if err != nil {
responseBodyChan <- err.Error()
return oauthBrowserResult{"", "", err}
}
codeReqBytes := <-successChan
codeReq, err := http.ReadRequest(bufio.NewReader(bytes.NewReader(codeReqBytes)))
if err != nil {
responseBodyChan <- err.Error()
return oauthBrowserResult{"", "", err}
}
logger.Debugf("Received authorization code from %v", oauthClient.authorizationURL())
tokenResponse, err := oauthClient.exchangeAccessToken(codeReq, state, oauth2cfg, codeVerifier, responseBodyChan)
if err != nil {
return oauthBrowserResult{"", "", err}
}
logger.Debugf("Received token from %v", oauthClient.tokenURL())
return oauthBrowserResult{tokenResponse.AccessToken, tokenResponse.RefreshToken, err}
}
func (oauthClient *oauthClient) setupListener() (*net.TCPListener, int, error) {
tcpListener, err := createLocalTCPListener(oauthClient.port)
if err != nil {
return nil, 0, err
}
callbackPort := tcpListener.Addr().(*net.TCPAddr).Port
logger.Debugf("oauthClient.port: %v, callbackPort: %v", oauthClient.port, callbackPort)
return tcpListener, callbackPort, nil
}
func (oauthClient *oauthClient) exchangeAccessToken(codeReq *http.Request, state string, oauth2cfg *oauth2.Config, codeVerifier string, responseBodyChan chan string) (*oauth2.Token, error) {
queryParams := codeReq.URL.Query()
errorMsg := queryParams.Get("error")
if errorMsg != "" {
errorDesc := queryParams.Get("error_description")
errMsg := fmt.Sprintf("error while getting authentication from oauth: %v. Details: %v", errorMsg, errorDesc)
responseBodyChan <- html.EscapeString(errMsg)
return nil, errors.New(errMsg)
}
receivedState := queryParams.Get("state")
if state != receivedState {
errMsg := "invalid oauth state received"
responseBodyChan <- errMsg
return nil, errors.New(errMsg)
}
code := queryParams.Get("code")
opts := []oauth2.AuthCodeOption{oauth2.VerifierOption(codeVerifier)}
if oauthClient.cfg.EnableSingleUseRefreshTokens {
opts = append(opts, oauth2.SetAuthURLParam("enable_single_use_refresh_tokens", "true"))
}
token, err := oauth2cfg.Exchange(oauthClient.ctx, code, opts...)
if err != nil {
responseBodyChan <- err.Error()
return nil, err
}
responseBodyChan <- oauthSuccessHTML
return token, nil
}
func (oauthClient *oauthClient) buildAuthorizationCodeConfig(callbackPort int) *oauth2.Config {
clientID, clientSecret := oauthClient.cfg.OauthClientID, oauthClient.cfg.OauthClientSecret
if oauthClient.eligibleForDefaultClientCredentials() {
clientID, clientSecret = localApplicationClientCredentials, localApplicationClientCredentials
}
oauthClient.logIfHTTPInUse(oauthClient.authorizationURL())
oauthClient.logIfHTTPInUse(oauthClient.tokenURL())
return &oauth2.Config{
ClientID: clientID,
ClientSecret: clientSecret,
RedirectURL: oauthClient.buildRedirectURI(callbackPort),
Scopes: oauthClient.buildScopes(),
Endpoint: oauth2.Endpoint{
AuthURL: oauthClient.authorizationURL(),
TokenURL: oauthClient.tokenURL(),
AuthStyle: oauth2.AuthStyleInHeader,
},
}
}
func (oauthClient *oauthClient) eligibleForDefaultClientCredentials() bool {
return oauthClient.cfg.OauthClientID == "" && oauthClient.cfg.OauthClientSecret == "" && oauthClient.isSnowflakeAsIDP()
}
func (oauthClient *oauthClient) isSnowflakeAsIDP() bool {
return (oauthClient.cfg.OauthAuthorizationURL == "" || strings.Contains(oauthClient.cfg.OauthAuthorizationURL, oauthClient.cfg.Host)) &&
(oauthClient.cfg.OauthTokenRequestURL == "" || strings.Contains(oauthClient.cfg.OauthTokenRequestURL, oauthClient.cfg.Host))
}
func (oauthClient *oauthClient) authorizationURL() string {
return cmp.Or(oauthClient.cfg.OauthAuthorizationURL, oauthClient.defaultAuthorizationURL())
}
func (oauthClient *oauthClient) defaultAuthorizationURL() string {
return fmt.Sprintf("%v://%v:%v/oauth/authorize", oauthClient.cfg.Protocol, oauthClient.cfg.Host, oauthClient.cfg.Port)
}
func (oauthClient *oauthClient) tokenURL() string {
return cmp.Or(oauthClient.cfg.OauthTokenRequestURL, oauthClient.defaultTokenURL())
}
func (oauthClient *oauthClient) defaultTokenURL() string {
return fmt.Sprintf("%v://%v:%v/oauth/token-request", oauthClient.cfg.Protocol, oauthClient.cfg.Host, oauthClient.cfg.Port)
}
func (oauthClient *oauthClient) buildRedirectURI(port int) string {
if oauthClient.cfg.OauthRedirectURI != "" {
return oauthClient.cfg.OauthRedirectURI
}
return fmt.Sprintf(oauthClient.redirectURITemplate, port)
}
func (oauthClient *oauthClient) buildScopes() []string {
if oauthClient.cfg.OauthScope == "" {
return []string{"session:role:" + oauthClient.cfg.Role}
}
scopes := strings.Split(oauthClient.cfg.OauthScope, " ")
for i, scope := range scopes {
scopes[i] = strings.TrimSpace(scope)
}
return scopes
}
func handleOAuthSocket(tcpListener *net.TCPListener, successChan chan []byte, errChan chan error, responseBodyChan chan string, closeListenerChan chan bool) {
conn, err := tcpListener.AcceptTCP()
if err != nil {
logger.Warnf("error creating socket. %v", err)
return
}
defer func() {
if err := conn.Close(); err != nil {
logger.Warnf("error while closing connection (%v -> %v). %v", conn.LocalAddr(), conn.RemoteAddr(), err)
}
}()
var buf [bufSize]byte
codeResp := bytes.NewBuffer(nil)
for {
readBytes, err := conn.Read(buf[:])
if err == io.EOF {
break
}
if err != nil {
errChan <- err
return
}
codeResp.Write(buf[0:readBytes])
if readBytes < bufSize {
break
}
}
errChan <- nil
successChan <- codeResp.Bytes()
responseBody := <-responseBodyChan
respToBrowser, err := buildResponse(responseBody)
if err != nil {
logger.Warnf("cannot create response to browser. %v", err)
}
_, err = conn.Write(respToBrowser.Bytes())
if err != nil {
logger.Warnf("cannot write response to browser. %v", err)
}
closeListenerChan <- true
}
type authorizationCodeProvider interface {
run(authorizationURL string) error
createState() string
createCodeVerifier() string
}
type browserBasedAuthorizationCodeProvider struct {
}
func (provider *browserBasedAuthorizationCodeProvider) run(authorizationURL string) error {
return openBrowser(authorizationURL)
}
func (provider *browserBasedAuthorizationCodeProvider) createState() string {
return NewUUID().String()
}
func (provider *browserBasedAuthorizationCodeProvider) createCodeVerifier() string {
return oauth2.GenerateVerifier()
}
func (oauthClient *oauthClient) authenticateByOAuthClientCredentials() (string, error) {
accessTokenSpec := oauthClient.accessTokenSpec()
if oauthClient.cfg.ClientStoreTemporaryCredential == ConfigBoolTrue {
if accessToken := credentialsStorage.getCredential(accessTokenSpec); accessToken != "" {
return accessToken, nil
}
}
oauth2Cfg, err := oauthClient.buildClientCredentialsConfig()
if err != nil {
return "", err
}
token, err := oauth2Cfg.Token(oauthClient.ctx)
if err != nil {
return "", err
}
if oauthClient.cfg.ClientStoreTemporaryCredential == ConfigBoolTrue {
credentialsStorage.setCredential(accessTokenSpec, token.AccessToken)
}
return token.AccessToken, nil
}
func (oauthClient *oauthClient) buildClientCredentialsConfig() (*clientcredentials.Config, error) {
if oauthClient.cfg.OauthTokenRequestURL == "" {
return nil, errors.New("client credentials flow requires tokenRequestURL")
}
return &clientcredentials.Config{
ClientID: oauthClient.cfg.OauthClientID,
ClientSecret: oauthClient.cfg.OauthClientSecret,
TokenURL: oauthClient.cfg.OauthTokenRequestURL,
Scopes: oauthClient.buildScopes(),
}, nil
}
func (oauthClient *oauthClient) refreshToken() error {
if oauthClient.cfg.ClientStoreTemporaryCredential != ConfigBoolTrue {
logger.Debug("credentials storage is disabled, cannot use refresh tokens")
return nil
}
refreshTokenSpec := newOAuthRefreshTokenSpec(oauthClient.cfg.OauthTokenRequestURL, oauthClient.cfg.User)
refreshToken := credentialsStorage.getCredential(refreshTokenSpec)
if refreshToken == "" {
logger.Debug("no refresh token in cache, full flow must be run")
return nil
}
body := url.Values{}
body.Add("grant_type", "refresh_token")
body.Add("refresh_token", refreshToken)
body.Add("scope", strings.Join(oauthClient.buildScopes(), " "))
req, err := http.NewRequest("POST", oauthClient.tokenURL(), strings.NewReader(body.Encode()))
if err != nil {
return err
}
req.SetBasicAuth(oauthClient.cfg.OauthClientID, oauthClient.cfg.OauthClientSecret)
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
resp, err := oauthClient.client.Do(req)
if err != nil {
return err
}
defer func() {
if err := resp.Body.Close(); err != nil {
logger.Warnf("error while closing response body for %v. %v", req.URL, err)
}
}()
if resp.StatusCode != 200 {
respBody, err := io.ReadAll(resp.Body)
if err != nil {
return err
}
credentialsStorage.deleteCredential(refreshTokenSpec)
return errors.New(string(respBody))
}
var tokenResponse tokenExchangeResponseBody
if err = json.NewDecoder(resp.Body).Decode(&tokenResponse); err != nil {
return err
}
accessTokenSpec := oauthClient.accessTokenSpec()
credentialsStorage.setCredential(accessTokenSpec, tokenResponse.AccessToken)
if tokenResponse.RefreshToken != "" {
credentialsStorage.setCredential(refreshTokenSpec, tokenResponse.RefreshToken)
}
return nil
}
type tokenExchangeResponseBody struct {
AccessToken string `json:"access_token,omitempty"`
RefreshToken string `json:"refresh_token"`
}
func (oauthClient *oauthClient) accessTokenSpec() *secureTokenSpec {
return newOAuthAccessTokenSpec(oauthClient.tokenURL(), oauthClient.cfg.User)
}
func (oauthClient *oauthClient) refreshTokenSpec() *secureTokenSpec {
return newOAuthRefreshTokenSpec(oauthClient.tokenURL(), oauthClient.cfg.User)
}
func (oauthClient *oauthClient) logIfHTTPInUse(u string) {
parsed, err := url.Parse(u)
if err != nil {
logger.Warnf("Cannot parse URL: %v. %v", u, err)
return
}
if parsed.Scheme == "http" {
logger.Warnf("OAuth URL uses insecure HTTP protocol: %v", u)
}
}