-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauth.go
More file actions
595 lines (487 loc) · 17.8 KB
/
auth.go
File metadata and controls
595 lines (487 loc) · 17.8 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
package main
import (
"context"
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"os/exec"
"runtime"
"strings"
"time"
)
// GenerateCodeVerifier generates a random string for PKCE
func GenerateCodeVerifier() (string, error) {
// Generate 32 random bytes
bytes := make([]byte, 32)
_, err := rand.Read(bytes)
if err != nil {
return "", err
}
// Encode using base64 URL encoding without padding
verifier := base64.RawURLEncoding.EncodeToString(bytes)
return verifier, nil
}
// GenerateCodeChallenge generates the code challenge from the verifier
func GenerateCodeChallenge(verifier string) string {
// Hash the verifier using SHA256
hash := sha256.Sum256([]byte(verifier))
// Encode using base64 URL encoding without padding
challenge := base64.RawURLEncoding.EncodeToString(hash[:])
return challenge
}
// StartLocalListenerWithState starts a local HTTP server to listen for the OAuth callback with a specific state
func StartLocalListenerWithState(port, expectedState string) (string, error) {
// Channel to receive the authorization code
codeChan := make(chan string, 1)
errorChan := make(chan error, 1)
mux := http.NewServeMux()
// Handle the redirect URL - /callback
mux.HandleFunc("/callback", func(w http.ResponseWriter, r *http.Request) {
// Check for authorization code or error in query parameters
queryCode := r.URL.Query().Get("code")
queryState := r.URL.Query().Get("state")
queryError := r.URL.Query().Get("error")
if queryError != "" {
errorDescription := r.URL.Query().Get("error_description")
err := fmt.Errorf("authorization error: %s - %s", queryError, errorDescription)
errorChan <- err
http.Error(w, "Authorization failed", http.StatusBadRequest)
return
}
if queryState != expectedState {
err := fmt.Errorf("invalid state parameter")
errorChan <- err
http.Error(w, "Invalid state", http.StatusBadRequest)
return
}
if queryCode == "" {
err := fmt.Errorf("no authorization code in callback")
errorChan <- err
http.Error(w, "No authorization code", http.StatusBadRequest)
return
}
// Send the code back to the main thread
codeChan <- queryCode
// Respond to the browser
w.Header().Set("Content-Type", "text/html")
w.WriteHeader(http.StatusOK)
fmt.Fprintf(w, `
<!DOCTYPE html>
<html>
<head>
<title>Authorization Successful</title>
<style>
body { font-family: Arial, sans-serif; text-align: center; padding: 50px; }
.success { color: green; }
</style>
</head>
<body>
<h1 class="success">Authorization Successful!</h1>
<p>You can now close this window and return to the CLI tool.</p>
</body>
</html>`)
})
server := &http.Server{
Addr: ":" + port,
Handler: mux,
}
// Start the server in a goroutine
go func() {
if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
select {
case errorChan <- err:
default:
// Error channel is already filled, likely because we closed the server early
}
}
}()
// Wait for a code or an error
select {
case code := <-codeChan:
// Close the server
ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
defer cancel()
_ = server.Shutdown(ctx)
return code, nil
case err := <-errorChan:
// Close the server
ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
defer cancel()
_ = server.Shutdown(ctx)
return "", err
case <-time.After(2 * time.Minute):
// Timeout after 2 minutes - close the server and return an error
ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
defer cancel()
_ = server.Shutdown(ctx)
return "", fmt.Errorf("authorization timed out after 2 minutes")
}
}
// ExchangeToken exchanges the authorization code for access and refresh tokens (PKCE flow)
func ExchangeToken(code, verifier, clientID, redirectURI string) (*TokenResponse, error) {
return ExchangeTokenWithSecretAndPKCE(code, verifier, clientID, "", redirectURI)
}
// ExchangeTokenWithSecret exchanges the authorization code for tokens (standard OAuth flow with client secret)
func ExchangeTokenWithSecret(code, clientID, clientSecret, redirectURI string) (*TokenResponse, error) {
// Standard flow without PKCE (deprecated, use PKCE instead)
data := url.Values{}
data.Set("grant_type", "authorization_code")
data.Set("client_id", clientID)
data.Set("client_secret", clientSecret)
data.Set("code", code)
data.Set("redirect_uri", redirectURI)
req, err := http.NewRequest("POST", "https://identity.xero.com/connect/token",
strings.NewReader(data.Encode()))
if err != nil {
return nil, fmt.Errorf("failed to create token request: %w", err)
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
if verboseOutput {
fmt.Printf("\n[DEBUG] Token Exchange Request:\n")
fmt.Printf(" URL: %s\n", req.URL)
fmt.Printf(" Method: %s\n", req.Method)
fmt.Printf(" Body: %s\n", data.Encode())
}
client := &http.Client{Timeout: 30 * time.Second}
resp, err := client.Do(req)
if err != nil {
return nil, fmt.Errorf("failed to send token request: %w", err)
}
defer resp.Body.Close()
responseBody, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("failed to read token response: %w", err)
}
if verboseOutput {
fmt.Printf("\n[DEBUG] Token Exchange Response:\n")
fmt.Printf(" Status: %d\n", resp.StatusCode)
fmt.Printf(" Body: %s\n", string(responseBody))
}
if resp.StatusCode != http.StatusOK {
// Try to parse error response for better error message
var errResp map[string]interface{}
if json.Unmarshal(responseBody, &errResp) == nil {
if errDesc, ok := errResp["error_description"].(string); ok {
return nil, fmt.Errorf("token exchange failed with status %d: %s - %s", resp.StatusCode, errResp["error"], errDesc)
}
}
return nil, fmt.Errorf("token exchange failed with status %d: %s", resp.StatusCode, string(responseBody))
}
var tokenResp TokenResponse
err = json.Unmarshal(responseBody, &tokenResp)
if err != nil {
return nil, fmt.Errorf("failed to parse token response: %w", err)
}
return &tokenResp, nil
}
// ExchangeTokenWithSecretAndPKCE exchanges authorization code using PKCE flow with optional client secret
func ExchangeTokenWithSecretAndPKCE(code, verifier, clientID, clientSecret, redirectURI string) (*TokenResponse, error) {
data := url.Values{}
data.Set("grant_type", "authorization_code")
data.Set("client_id", clientID)
data.Set("code", code)
data.Set("redirect_uri", redirectURI)
data.Set("code_verifier", verifier)
// Add client_secret if provided (optional with PKCE)
if clientSecret != "" {
data.Set("client_secret", clientSecret)
}
req, err := http.NewRequest("POST", "https://identity.xero.com/connect/token",
strings.NewReader(data.Encode()))
if err != nil {
return nil, fmt.Errorf("failed to create token request: %w", err)
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
if verboseOutput {
fmt.Printf("\n[DEBUG] Token Exchange Request:\n")
fmt.Printf(" URL: %s\n", req.URL)
fmt.Printf(" Method: %s\n", req.Method)
fmt.Printf(" Body: %s\n", data.Encode())
}
client := &http.Client{Timeout: 30 * time.Second}
resp, err := client.Do(req)
if err != nil {
return nil, fmt.Errorf("failed to send token request: %w", err)
}
defer resp.Body.Close()
responseBody, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("failed to read token response: %w", err)
}
if verboseOutput {
fmt.Printf("\n[DEBUG] Token Exchange Response:\n")
fmt.Printf(" Status: %d\n", resp.StatusCode)
fmt.Printf(" Body: %s\n", string(responseBody))
}
if resp.StatusCode != http.StatusOK {
// Try to parse error response for better error message
var errResp map[string]interface{}
if json.Unmarshal(responseBody, &errResp) == nil {
if errDesc, ok := errResp["error_description"].(string); ok {
return nil, fmt.Errorf("token exchange failed with status %d: %s - %s", resp.StatusCode, errResp["error"], errDesc)
}
}
return nil, fmt.Errorf("token exchange failed with status %d: %s", resp.StatusCode, string(responseBody))
}
var tokenResp TokenResponse
err = json.Unmarshal(responseBody, &tokenResp)
if err != nil {
return nil, fmt.Errorf("failed to parse token response: %w", err)
}
return &tokenResp, nil
}
// ExchangeTokenAuto automatically exchanges authorization code using PKCE flow with optional client secret
func ExchangeTokenAuto(code, verifier, clientID, clientSecret, redirectURI string) (*TokenResponse, error) {
return ExchangeTokenWithSecretAndPKCE(code, verifier, clientID, clientSecret, redirectURI)
}
// RefreshTokenAuto refreshes token using PKCE flow with optional client secret
func RefreshTokenAuto(refreshToken, clientID, clientSecret string) (*TokenResponse, error) {
data := url.Values{}
data.Set("grant_type", "refresh_token")
data.Set("client_id", clientID)
data.Set("refresh_token", refreshToken)
// Add client_secret if provided (optional with PKCE)
if clientSecret != "" {
data.Set("client_secret", clientSecret)
}
req, err := http.NewRequest("POST", "https://identity.xero.com/connect/token",
strings.NewReader(data.Encode()))
if err != nil {
return nil, fmt.Errorf("failed to create refresh token request: %w", err)
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
if verboseOutput {
fmt.Printf("\n[DEBUG] Refresh Token Request:\n")
fmt.Printf(" URL: %s\n", req.URL)
fmt.Printf(" Method: %s\n", req.Method)
fmt.Printf(" Body: %s\n", data.Encode())
}
client := &http.Client{Timeout: 30 * time.Second}
resp, err := client.Do(req)
if err != nil {
return nil, fmt.Errorf("failed to send refresh token request: %w", err)
}
defer resp.Body.Close()
responseBody, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("failed to read refresh token response: %w", err)
}
if verboseOutput {
fmt.Printf("\n[DEBUG] Refresh Token Response:\n")
fmt.Printf(" Status: %d\n", resp.StatusCode)
fmt.Printf(" Body: %s\n", string(responseBody))
}
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("token refresh failed with status %d: %s", resp.StatusCode, string(responseBody))
}
var tokenResp TokenResponse
err = json.Unmarshal(responseBody, &tokenResp)
if err != nil {
return nil, fmt.Errorf("failed to parse refresh token response: %w", err)
}
return &tokenResp, nil
}
// RevokeToken revokes the refresh token
func RevokeToken(refreshToken, clientID string) error {
data := url.Values{}
data.Set("token", refreshToken)
// Create Authorization header with Basic auth: base64(client_id:)
authString := base64.StdEncoding.EncodeToString([]byte(clientID + ":"))
req, err := http.NewRequest("POST", "https://identity.xero.com/connect/revocation",
strings.NewReader(data.Encode()))
if err != nil {
return fmt.Errorf("failed to create revoke token request: %w", err)
}
req.Header.Set("Authorization", "Basic "+authString)
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
client := &http.Client{Timeout: 30 * time.Second}
resp, err := client.Do(req)
if err != nil {
return fmt.Errorf("failed to send revoke token request: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
responseBody, _ := io.ReadAll(resp.Body)
return fmt.Errorf("token revoke failed with status %d: %s", resp.StatusCode, string(responseBody))
}
return nil
}
// BuildAuthorizeURL builds the OAuth2 authorization URL (PKCE flow)
func BuildAuthorizeURL(config *Config, challenge, state string) string {
params := url.Values{}
params.Set("response_type", "code")
params.Set("client_id", config.ClientID)
params.Set("redirect_uri", config.RedirectURI)
params.Set("scope", config.Scopes)
params.Set("code_challenge", challenge)
params.Set("code_challenge_method", "S256")
params.Set("state", state)
return "https://login.xero.com/identity/connect/authorize?" + params.Encode()
}
// BuildAuthorizeURLStandard builds the OAuth2 authorization URL (standard flow without PKCE)
func BuildAuthorizeURLStandard(config *Config, state string) string {
params := url.Values{}
params.Set("response_type", "code")
params.Set("client_id", config.ClientID)
params.Set("redirect_uri", config.RedirectURI)
params.Set("scope", config.Scopes)
params.Set("state", state)
return "https://login.xero.com/identity/connect/authorize?" + params.Encode()
}
// RunAuthFlow runs the complete authorization flow
func RunAuthFlow(config *Config) (*TokenStore, error) {
fmt.Println("Starting Xero authorization flow...")
fmt.Println("Preparing PKCE parameters...")
// Generate PKCE verifier and challenge
verifier, err := GenerateCodeVerifier()
if err != nil {
return nil, fmt.Errorf("failed to generate code verifier: %w", err)
}
challenge := GenerateCodeChallenge(verifier)
// Generate state parameter for CSRF protection
stateBytes := make([]byte, 16)
_, err = rand.Read(stateBytes)
if err != nil {
return nil, fmt.Errorf("failed to generate state: %w", err)
}
state := base64.RawURLEncoding.EncodeToString(stateBytes)
// Build authorization URL
authURL := BuildAuthorizeURL(config, challenge, state)
fmt.Println("\nOpening browser for authorization...")
fmt.Println("Please complete the authorization in your browser.")
// Open browser
err = openBrowser(authURL)
if err != nil {
fmt.Printf("Could not open browser automatically: %v\n", err)
fmt.Printf("Please visit this URL manually:\n%s\n", authURL)
} else {
fmt.Printf("Browser opened with authorization page\n")
}
fmt.Printf("\nWaiting for authorization... (will timeout after 2 minutes)\n")
// Start local listener to receive the callback
port := config.Port
code, err := StartLocalListenerWithState(port, state)
if err != nil {
return nil, fmt.Errorf("authorization failed: %w", err)
}
fmt.Printf("Received authorization code!\n")
// Exchange authorization code for tokens
tokenResponse, err := ExchangeToken(code, verifier, config.ClientID, config.RedirectURI)
if err != nil {
return nil, fmt.Errorf("failed to exchange token: %w", err)
}
// Calculate token expiry time
expiry := time.Now().Add(time.Duration(tokenResponse.ExpiresIn) * time.Second)
// Get tenant information from the token
tenantID, tenantName, err := GetTenantInfo(tokenResponse.AccessToken)
if err != nil {
fmt.Printf("Warning: failed to get tenant info: %v\n", err)
}
// Create token store
tokenStore := &TokenStore{
AccessToken: tokenResponse.AccessToken,
RefreshToken: tokenResponse.RefreshToken,
Expiry: expiry,
TenantID: tenantID,
TenantName: tenantName,
Scopes: tokenResponse.Scope,
UpdatedAt: time.Now(),
}
fmt.Println("Authorization successful!")
return tokenStore, nil
}
// openBrowser opens the default browser to the given URL
func openBrowser(url string) error {
var err error
switch runtime.GOOS {
case "linux":
err = exec.Command("xdg-open", url).Start()
case "windows":
err = exec.Command("rundll32", "url.dll,FileProtocolHandler", url).Start()
case "darwin":
err = exec.Command("open", url).Start()
default:
err = fmt.Errorf("unsupported platform")
}
return err
}
// GetTenantInfo gets tenant information from the access token using the /connections endpoint
func GetTenantInfo(accessToken string) (tenantID, tenantName string, err error) {
client := &http.Client{Timeout: 30 * time.Second}
req, err := http.NewRequest("GET", "https://api.xero.com/connections", nil)
if err != nil {
return "", "", fmt.Errorf("failed to create request: %w", err)
}
req.Header.Set("Authorization", "Bearer "+accessToken)
req.Header.Set("Accept", "application/json")
resp, err := client.Do(req)
if err != nil {
return "", "", fmt.Errorf("failed to send request: %w", err)
}
defer resp.Body.Close()
responseBody, err := io.ReadAll(resp.Body)
if err != nil {
return "", "", fmt.Errorf("failed to read response: %w", err)
}
if resp.StatusCode == http.StatusUnauthorized {
return "", "", fmt.Errorf("unauthorized - token may be invalid or expired")
}
if resp.StatusCode == http.StatusForbidden {
return "", "", fmt.Errorf("forbidden - check that your app has the required scopes")
}
if resp.StatusCode != http.StatusOK {
return "", "", fmt.Errorf("failed to get tenant info: HTTP %d: %s", resp.StatusCode, string(responseBody))
}
var connections []Connection
err = json.Unmarshal(responseBody, &connections)
if err != nil {
return "", "", fmt.Errorf("failed to parse connections: %w", err)
}
if len(connections) == 0 {
return "", "", fmt.Errorf("no connections found")
}
conn := connections[0]
return conn.TenantID, conn.TenantName, nil
}
// GetAllConnections gets all tenant connections from the access token
func GetAllConnections(accessToken string) ([]Connection, error) {
client := &http.Client{Timeout: 30 * time.Second}
req, err := http.NewRequest("GET", "https://api.xero.com/connections", nil)
if err != nil {
return nil, fmt.Errorf("failed to create request: %w", err)
}
req.Header.Set("Authorization", "Bearer "+accessToken)
req.Header.Set("Accept", "application/json")
resp, err := client.Do(req)
if err != nil {
return nil, fmt.Errorf("failed to send request: %w", err)
}
defer resp.Body.Close()
responseBody, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("failed to read response: %w", err)
}
if resp.StatusCode == http.StatusUnauthorized {
return nil, fmt.Errorf("unauthorized - token may be invalid or expired")
}
if resp.StatusCode == http.StatusForbidden {
return nil, fmt.Errorf("forbidden - check that your app has the required scopes")
}
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("failed to get connections: HTTP %d: %s", resp.StatusCode, string(responseBody))
}
var connections []Connection
err = json.Unmarshal(responseBody, &connections)
if err != nil {
return nil, fmt.Errorf("failed to parse connections: %w", err)
}
if len(connections) == 0 {
return nil, fmt.Errorf("no connections found")
}
return connections, nil
}