-
Notifications
You must be signed in to change notification settings - Fork 76
Expand file tree
/
Copy pathauth.go
More file actions
481 lines (398 loc) · 12.5 KB
/
auth.go
File metadata and controls
481 lines (398 loc) · 12.5 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
package auth
import (
"context"
"crypto/hmac"
"crypto/rand"
"crypto/sha1"
"crypto/sha256"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"math/big"
"net/http"
"net/url"
"os/exec"
"sort"
"strings"
"time"
"github.com/xdevplatform/xurl/config"
xurlErrors "github.com/xdevplatform/xurl/errors"
"github.com/xdevplatform/xurl/store"
"runtime"
"golang.org/x/oauth2"
)
type Auth struct {
TokenStore *store.TokenStore
infoURL string
clientID string
clientSecret string
authURL string
tokenURL string
redirectURI string
appName string // explicit app override (empty = use default)
}
// NewAuth creates a new Auth object.
// Credentials are resolved in order: env-var config → active app in .xurl store.
// If env var credentials are present, they're also backfilled into any migrated
// app that has tokens but no stored credentials.
func NewAuth(cfg *config.Config) *Auth {
ts := store.NewTokenStoreWithCredentials(cfg.ClientID, cfg.ClientSecret)
// Resolve client ID / secret: env vars take priority, then the active app.
clientID := cfg.ClientID
clientSecret := cfg.ClientSecret
appName := cfg.AppName
app := ts.ResolveApp(appName)
if clientID == "" && app != nil {
clientID = app.ClientID
}
if clientSecret == "" && app != nil {
clientSecret = app.ClientSecret
}
return &Auth{
TokenStore: ts,
infoURL: cfg.InfoURL,
clientID: clientID,
clientSecret: clientSecret,
authURL: cfg.AuthURL,
tokenURL: cfg.TokenURL,
redirectURI: cfg.RedirectURI,
appName: appName,
}
}
// WithTokenStore sets the token store for the Auth object
func (a *Auth) WithTokenStore(tokenStore *store.TokenStore) *Auth {
a.TokenStore = tokenStore
return a
}
// WithAppName sets the explicit app name override.
func (a *Auth) WithAppName(appName string) *Auth {
a.appName = appName
app := a.TokenStore.ResolveApp(appName)
if app != nil {
a.clientID = app.ClientID // unconditional override
a.clientSecret = app.ClientSecret // unconditional override
}
return a
}
// AppName returns the current explicit app name override.
func (a *Auth) AppName() string {
return a.appName
}
// GetOAuth1Header gets the OAuth1 header for a request
func (a *Auth) GetOAuth1Header(method, urlStr string, additionalParams map[string]string) (string, error) {
token := a.TokenStore.GetOAuth1TokensForApp(a.appName)
if token == nil || token.OAuth1 == nil {
return "", xurlErrors.NewAuthError("TokenNotFound", errors.New("OAuth1 token not found"))
}
oauth1Token := token.OAuth1
parsedURL, err := url.Parse(urlStr)
if err != nil {
return "", xurlErrors.NewAuthError("InvalidURL", err)
}
params := make(map[string]string)
query := parsedURL.Query()
for key := range query {
params[key] = query.Get(key)
}
for key, value := range additionalParams {
params[key] = value
}
params["oauth_consumer_key"] = oauth1Token.ConsumerKey
params["oauth_nonce"] = generateNonce()
params["oauth_signature_method"] = "HMAC-SHA1"
params["oauth_timestamp"] = generateTimestamp()
params["oauth_token"] = oauth1Token.AccessToken
params["oauth_version"] = "1.0"
signature, err := generateSignature(method, urlStr, params, oauth1Token.ConsumerSecret, oauth1Token.TokenSecret)
if err != nil {
return "", xurlErrors.NewAuthError("SignatureGenerationError", err)
}
var oauthParams []string
oauthParams = append(oauthParams, fmt.Sprintf("oauth_consumer_key=\"%s\"", encode(oauth1Token.ConsumerKey)))
oauthParams = append(oauthParams, fmt.Sprintf("oauth_nonce=\"%s\"", encode(params["oauth_nonce"])))
oauthParams = append(oauthParams, fmt.Sprintf("oauth_signature=\"%s\"", encode(signature)))
oauthParams = append(oauthParams, fmt.Sprintf("oauth_signature_method=\"%s\"", encode("HMAC-SHA1")))
oauthParams = append(oauthParams, fmt.Sprintf("oauth_timestamp=\"%s\"", encode(params["oauth_timestamp"])))
oauthParams = append(oauthParams, fmt.Sprintf("oauth_token=\"%s\"", encode(oauth1Token.AccessToken)))
oauthParams = append(oauthParams, fmt.Sprintf("oauth_version=\"%s\"", encode("1.0")))
return "OAuth " + strings.Join(oauthParams, ", "), nil
}
// GetOAuth2Header gets or refreshes an OAuth2 token
func (a *Auth) GetOAuth2Header(username string) (string, error) {
var token *store.Token
if username != "" {
token = a.TokenStore.GetOAuth2TokenForApp(a.appName, username)
} else {
token = a.TokenStore.GetFirstOAuth2TokenForApp(a.appName)
}
if token == nil {
return a.OAuth2Flow(username)
}
accessToken, err := a.RefreshOAuth2Token(username)
if err != nil {
return "", xurlErrors.NewAuthError("RefreshTokenError", err)
}
return "Bearer " + accessToken, nil
}
// OAuth2Flow starts the OAuth2 flow
func (a *Auth) OAuth2Flow(username string) (string, error) {
config := &oauth2.Config{
ClientID: a.clientID,
ClientSecret: a.clientSecret,
Endpoint: oauth2.Endpoint{
AuthURL: a.authURL,
TokenURL: a.tokenURL,
},
RedirectURL: a.redirectURI,
Scopes: getOAuth2Scopes(),
}
b := make([]byte, 32)
if _, err := rand.Read(b); err != nil {
return "", xurlErrors.NewAuthError("IOError", err)
}
state := base64.StdEncoding.EncodeToString(b)
verifier, challenge := generateCodeVerifierAndChallenge()
authURL := config.AuthCodeURL(state,
oauth2.SetAuthURLParam("code_challenge", challenge),
oauth2.SetAuthURLParam("code_challenge_method", "S256"))
err := openBrowser(authURL)
if err != nil {
fmt.Println("Failed to open browser automatically. Please visit this URL manually:")
fmt.Println(authURL)
}
codeChan := make(chan string, 1)
callback := func(code, receivedState string) error {
if receivedState != state {
return xurlErrors.NewAuthError("InvalidState", errors.New("invalid state parameter"))
}
if code == "" {
return xurlErrors.NewAuthError("InvalidCode", errors.New("empty authorization code"))
}
codeChan <- code
return nil
}
go func() {
parsedURL, err := url.Parse(a.redirectURI)
if err != nil {
codeChan <- ""
return
}
port := 8080
if parsedURL.Port() != "" {
fmt.Sscanf(parsedURL.Port(), "%d", &port)
}
if err := StartListener(port, callback); err != nil {
fmt.Printf("Error in OAuth listener: %v\n", err)
}
}()
var code string
select {
case code = <-codeChan:
if code == "" {
return "", xurlErrors.NewAuthError("ListenerError", errors.New("oauth2 listener failed"))
}
case <-time.After(5 * time.Minute):
return "", xurlErrors.NewAuthError("Timeout", errors.New("authentication timed out"))
}
token, err := config.Exchange(context.Background(), code, oauth2.SetAuthURLParam("code_verifier", verifier))
if err != nil {
return "", xurlErrors.NewAuthError("TokenExchangeError", err)
}
var usernameStr string
if username != "" {
usernameStr = username
} else {
fetchedUsername, err := a.fetchUsername(token.AccessToken)
if err != nil {
return "", err
}
usernameStr = fetchedUsername
}
expirationTime := uint64(time.Now().Add(time.Duration(token.Expiry.Unix()-time.Now().Unix()) * time.Second).Unix())
err = a.TokenStore.SaveOAuth2TokenForApp(a.appName, usernameStr, token.AccessToken, token.RefreshToken, expirationTime)
if err != nil {
return "", xurlErrors.NewAuthError("TokenStorageError", err)
}
return token.AccessToken, nil
}
// RefreshOAuth2Token validates and refreshes an OAuth2 token if needed
func (a *Auth) RefreshOAuth2Token(username string) (string, error) {
var token *store.Token
if username != "" {
token = a.TokenStore.GetOAuth2TokenForApp(a.appName, username)
} else {
token = a.TokenStore.GetFirstOAuth2TokenForApp(a.appName)
}
if token == nil || token.OAuth2 == nil {
return "", xurlErrors.NewAuthError("TokenNotFound", errors.New("oauth2 token not found"))
}
currentTime := time.Now().Unix()
if uint64(currentTime) < token.OAuth2.ExpirationTime {
return token.OAuth2.AccessToken, nil
}
config := &oauth2.Config{
ClientID: a.clientID,
ClientSecret: a.clientSecret,
Endpoint: oauth2.Endpoint{
TokenURL: a.tokenURL,
},
}
tokenSource := config.TokenSource(context.Background(), &oauth2.Token{
RefreshToken: token.OAuth2.RefreshToken,
})
newToken, err := tokenSource.Token()
if err != nil {
return "", xurlErrors.NewAuthError("RefreshTokenError", err)
}
var usernameStr string
if username != "" {
usernameStr = username
} else {
fetchedUsername, err := a.fetchUsername(newToken.AccessToken)
if err != nil {
return "", xurlErrors.NewAuthError("UsernameFetchError", err)
}
usernameStr = fetchedUsername
}
expirationTime := uint64(time.Now().Add(time.Duration(newToken.Expiry.Unix()-time.Now().Unix()) * time.Second).Unix())
err = a.TokenStore.SaveOAuth2TokenForApp(a.appName, usernameStr, newToken.AccessToken, newToken.RefreshToken, expirationTime)
if err != nil {
return "", xurlErrors.NewAuthError("RefreshTokenError", err)
}
return newToken.AccessToken, nil
}
// GetBearerTokenHeader gets the bearer token from the token store
func (a *Auth) GetBearerTokenHeader() (string, error) {
token := a.TokenStore.GetBearerTokenForApp(a.appName)
if token == nil {
return "", xurlErrors.NewAuthError("TokenNotFound", errors.New("bearer token not found"))
}
return "Bearer " + token.Bearer, nil
}
func (a *Auth) fetchUsername(accessToken string) (string, error) {
req, err := http.NewRequest("GET", a.infoURL, nil)
if err != nil {
return "", xurlErrors.NewAuthError("RequestCreationError", err)
}
req.Header.Add("Authorization", "Bearer "+accessToken)
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return "", xurlErrors.NewAuthError("NetworkError", err)
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return "", xurlErrors.NewAuthError("IOError", err)
}
var data map[string]any
if err := json.Unmarshal(body, &data); err != nil {
return "", xurlErrors.NewAuthError("JSONDeserializationError", err)
}
if data["data"] != nil {
if userData, ok := data["data"].(map[string]any); ok {
if username, ok := userData["username"].(string); ok {
return username, nil
}
}
}
return "", xurlErrors.NewAuthError("UsernameNotFound", errors.New("username not found when fetching username"))
}
func generateSignature(method, urlStr string, params map[string]string, consumerSecret, tokenSecret string) (string, error) {
parsedURL, err := url.Parse(urlStr)
if err != nil {
return "", xurlErrors.NewAuthError("InvalidURL", err)
}
baseURL := fmt.Sprintf("%s://%s%s", parsedURL.Scheme, parsedURL.Host, parsedURL.Path)
var keys []string
for key := range params {
keys = append(keys, key)
}
sort.Strings(keys)
var paramPairs []string
for _, key := range keys {
paramPairs = append(paramPairs, fmt.Sprintf("%s=%s", encode(key), encode(params[key])))
}
paramString := strings.Join(paramPairs, "&")
signatureBaseString := fmt.Sprintf("%s&%s&%s",
strings.ToUpper(method),
encode(baseURL),
encode(paramString))
signingKey := fmt.Sprintf("%s&%s", encode(consumerSecret), encode(tokenSecret))
h := hmac.New(sha1.New, []byte(signingKey))
h.Write([]byte(signatureBaseString))
signature := base64.StdEncoding.EncodeToString(h.Sum(nil))
return signature, nil
}
func generateNonce() string {
n, _ := rand.Int(rand.Reader, big.NewInt(1000000000))
return n.String()
}
func generateTimestamp() string {
return fmt.Sprintf("%d", time.Now().Unix())
}
func encode(s string) string {
return url.QueryEscape(s)
}
func generateCodeVerifierAndChallenge() (string, string) {
b := make([]byte, 32)
rand.Read(b)
verifier := base64.RawURLEncoding.EncodeToString(b)
h := sha256.New()
h.Write([]byte(verifier))
challenge := base64.RawURLEncoding.EncodeToString(h.Sum(nil))
return verifier, challenge
}
func getOAuth2Scopes() []string {
readScopes := []string{
"tweet.read",
"users.read",
"bookmark.read",
"follows.read",
"list.read",
"block.read",
"mute.read",
"like.read",
"users.email",
"dm.read",
}
writeScopes := []string{
"tweet.write",
"tweet.moderate.write",
"follows.write",
"bookmark.write",
"block.write",
"mute.write",
"like.write",
"list.write",
"media.write",
"dm.write",
}
otherScopes := []string{
"offline.access",
"space.read",
}
var scopes []string
scopes = append(scopes, readScopes...)
scopes = append(scopes, writeScopes...)
scopes = append(scopes, otherScopes...)
return scopes
}
func openBrowser(url string) error {
var cmd string
var args []string
switch runtime.GOOS {
case "windows":
cmd = "cmd"
args = []string{"/c", "start", url}
case "darwin":
cmd = "open"
args = []string{url}
default:
cmd = "xdg-open"
args = []string{url}
}
return exec.Command(cmd, args...).Start()
}