-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
900 lines (775 loc) · 23.7 KB
/
main.go
File metadata and controls
900 lines (775 loc) · 23.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
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
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
package main
import (
"context"
"crypto/tls"
"encoding/json"
"errors"
"flag"
"fmt"
"io"
"net/http"
"net/url"
"os"
"os/signal"
"strings"
"sync"
"syscall"
"time"
retry "github.com/appleboy/go-httpretry"
"github.com/google/uuid"
"github.com/joho/godotenv"
"golang.org/x/oauth2"
tea "charm.land/bubbletea/v2"
"github.com/go-authgate/device-cli/tui"
"github.com/go-authgate/sdk-go/credstore"
)
var (
serverURL string
clientID string
tokenFile string
tokenStoreMode string
flagServerURL *string
flagClientID *string
flagTokenFile *string
flagTokenStore *string
configOnce sync.Once
retryClient *retry.Client
tokenStore credstore.Store[credstore.Token]
)
const defaultKeyringService = "authgate-device-cli"
// maxResponseBodySize limits HTTP response body reads to prevent memory exhaustion (DoS).
const maxResponseBodySize = 1 << 20 // 1 MB
// errResponseTooLarge indicates the server returned an oversized response body.
var errResponseTooLarge = errors.New("response body exceeds maximum allowed size")
// readResponseBody reads the response body up to maxResponseBodySize.
// Returns errResponseTooLarge if the body exceeds the limit.
func readResponseBody(body io.Reader) ([]byte, error) {
data, err := io.ReadAll(io.LimitReader(body, maxResponseBodySize+1))
if err != nil {
return nil, fmt.Errorf("failed to read response: %w", err)
}
if int64(len(data)) > maxResponseBodySize {
return nil, errResponseTooLarge
}
return data, nil
}
// Timeout configuration for different operations
const (
deviceCodeRequestTimeout = 10 * time.Second
tokenExchangeTimeout = 5 * time.Second
tokenVerificationTimeout = 10 * time.Second
refreshTokenTimeout = 10 * time.Second
)
// OAuth endpoint paths
const (
endpointDeviceCode = "/oauth/device/code"
endpointToken = "/oauth/token"
endpointTokenInfo = "/oauth/tokeninfo"
)
// Device authorization error codes per RFC 8628
const (
oauthErrAuthorizationPending = "authorization_pending"
oauthErrSlowDown = "slow_down"
oauthErrExpiredToken = "expired_token"
oauthErrAccessDenied = "access_denied"
)
// Common OAuth 2.0 token endpoint error codes (e.g., RFC 6749)
const (
oauthErrInvalidGrant = "invalid_grant"
oauthErrInvalidToken = "invalid_token"
)
// Token store backend modes for the -token-store flag
const (
tokenStoreModeAuto = "auto"
tokenStoreModeFile = "file"
tokenStoreModeKeyring = "keyring"
)
// tokenResponse is the common structure for OAuth token endpoint responses.
type tokenResponse struct {
AccessToken string `json:"access_token"`
RefreshToken string `json:"refresh_token"`
TokenType string `json:"token_type"`
ExpiresIn int `json:"expires_in"`
Scope string `json:"scope"`
}
func init() {
// Load .env file if exists (ignore error if not found)
_ = godotenv.Load()
// Define flags (but don't parse yet to avoid conflicts with test flags)
flagServerURL = flag.String(
"server-url",
"",
"OAuth server URL (default: http://localhost:8080 or SERVER_URL env)",
)
flagClientID = flag.String("client-id", "", "OAuth client ID (required, or set CLIENT_ID env)")
flagTokenFile = flag.String(
"token-file",
"",
"Token storage file (default: .authgate-tokens.json or TOKEN_FILE env)",
)
flagTokenStore = flag.String(
"token-store",
"",
"Token storage backend: auto, file, keyring (default: auto or TOKEN_STORE env)",
)
}
// initConfig parses flags and initializes configuration
// Separated from init() to avoid conflicts with test flag parsing
func initConfig() {
configOnce.Do(func() {
doInitConfig()
})
}
func doInitConfig() {
flag.Parse()
// Priority: flag > env > default
serverURL = getConfig(*flagServerURL, "SERVER_URL", "http://localhost:8080")
clientID = getConfig(*flagClientID, "CLIENT_ID", "")
tokenFile = getConfig(*flagTokenFile, "TOKEN_FILE", ".authgate-tokens.json")
tokenStoreMode = getConfig(*flagTokenStore, "TOKEN_STORE", "auto")
// Validate SERVER_URL format
if err := validateServerURL(serverURL); err != nil {
fmt.Fprintf(os.Stderr, "Error: Invalid SERVER_URL: %v\n", err)
os.Exit(1)
}
// Warn if using HTTP instead of HTTPS
if strings.HasPrefix(strings.ToLower(serverURL), "http://") {
fmt.Fprintln(
os.Stderr,
"⚠️ WARNING: Using HTTP instead of HTTPS. Tokens will be transmitted in plaintext!",
)
fmt.Fprintln(
os.Stderr,
"⚠️ This is only safe for local development. Use HTTPS in production.",
)
fmt.Fprintln(os.Stderr)
}
if clientID == "" {
fmt.Println("Error: CLIENT_ID not set. Please provide it via:")
fmt.Println(" 1. Command line flag: -client-id=<your-client-id>")
fmt.Println(" 2. Environment variable: CLIENT_ID=<your-client-id>")
fmt.Println(" 3. .env file: CLIENT_ID=<your-client-id>")
fmt.Println("\nYou can find the client_id in the server startup logs.")
os.Exit(1)
}
// Validate CLIENT_ID format (should be UUID)
if _, err := uuid.Parse(clientID); err != nil {
fmt.Fprintf(
os.Stderr,
"⚠️ Warning: CLIENT_ID doesn't appear to be a valid UUID: %s\n",
clientID,
)
fmt.Fprintln(
os.Stderr,
"⚠️ This may cause authentication issues if the server expects UUID format.",
)
fmt.Fprintln(os.Stderr)
}
// Initialize HTTP client with retry support
baseHTTPClient := &http.Client{
Transport: &http.Transport{
TLSClientConfig: &tls.Config{
MinVersion: tls.VersionTLS12,
},
MaxIdleConns: 10,
IdleConnTimeout: 90 * time.Second,
TLSHandshakeTimeout: 10 * time.Second,
DisableKeepAlives: false,
},
}
// Wrap with retry logic using go-httpretry
var err error
retryClient, err = retry.NewBackgroundClient(
retry.WithHTTPClient(baseHTTPClient),
)
if err != nil {
fmt.Fprintf(os.Stderr, "Error: failed to create retry client: %v\n", err)
os.Exit(1)
}
// Initialize token store based on mode
fileStore := credstore.NewTokenFileStore(tokenFile)
switch tokenStoreMode {
case tokenStoreModeFile:
tokenStore = fileStore
case tokenStoreModeKeyring:
tokenStore = credstore.NewTokenKeyringStore(defaultKeyringService)
case tokenStoreModeAuto:
kr := credstore.NewTokenKeyringStore(defaultKeyringService)
secureStore := credstore.NewSecureStore(kr, fileStore)
tokenStore = secureStore
if !secureStore.UseKeyring() {
fmt.Fprintln(
os.Stderr,
"⚠️ OS keyring unavailable, falling back to file-based token storage",
)
}
default:
fmt.Fprintf(
os.Stderr,
"Error: Invalid token-store value: %s (must be %s, %s, or %s)\n",
tokenStoreMode, tokenStoreModeAuto, tokenStoreModeFile, tokenStoreModeKeyring,
)
os.Exit(1)
}
}
// getConfig returns value with priority: flag > env > default
func getConfig(flagValue, envKey, defaultValue string) string {
if flagValue != "" {
return flagValue
}
return getEnv(envKey, defaultValue)
}
func getEnv(key, defaultValue string) string {
if value := os.Getenv(key); value != "" {
return value
}
return defaultValue
}
// validateServerURL validates that the server URL is properly formatted
func validateServerURL(rawURL string) error {
if rawURL == "" {
return errors.New("server URL cannot be empty")
}
u, err := url.Parse(rawURL)
if err != nil {
return fmt.Errorf("invalid URL format: %w", err)
}
if u.Scheme != "http" && u.Scheme != "https" {
return fmt.Errorf("URL scheme must be http or https, got: %s", u.Scheme)
}
if u.Host == "" {
return errors.New("URL must include a host")
}
return nil
}
type ErrorResponse struct {
Error string `json:"error"`
ErrorDescription string `json:"error_description"`
}
// ErrRefreshTokenExpired indicates that the refresh token has expired or is invalid
var ErrRefreshTokenExpired = errors.New("refresh token expired or invalid")
// validateTokenResponse validates the OAuth token response
func validateTokenResponse(accessToken, tokenType string, expiresIn int) error {
if accessToken == "" {
return errors.New("access_token is empty")
}
if len(accessToken) < 10 {
return fmt.Errorf("access_token is too short (length: %d)", len(accessToken))
}
if expiresIn <= 0 {
return fmt.Errorf("expires_in must be positive, got: %d", expiresIn)
}
// Token type is optional in OAuth 2.0, but if present, should be "Bearer"
if tokenType != "" && tokenType != "Bearer" {
return fmt.Errorf("unexpected token_type: %s (expected Bearer)", tokenType)
}
return nil
}
// isTTY reports whether stderr is a character device (interactive terminal).
// We check stderr because the TUI renders to stderr, allowing stdout to be piped.
func isTTY() bool {
fi, err := os.Stderr.Stat()
if err != nil {
return false
}
return (fi.Mode() & os.ModeCharDevice) != 0
}
func main() {
initConfig()
if isTTY() {
// Run TUI program on stderr so stdout pipes are not corrupted
m := tui.NewModel()
p := tea.NewProgram(m, tea.WithOutput(os.Stderr))
ctx, cancel := context.WithCancel(context.Background())
var wg sync.WaitGroup
wg.Go(func() {
if _, err := p.Run(); err != nil {
fmt.Fprintf(os.Stderr, "TUI error: %v\n", err)
}
cancel() // BubbleTea exited (Ctrl+C or normal quit) → cancel run context
})
d := tui.NewProgramDisplayer(p)
d.Banner()
runErr := run(ctx, d)
p.Quit()
wg.Wait()
if runErr != nil {
os.Exit(1)
}
} else {
d := tui.NewPlainDisplayer(os.Stderr)
d.Banner()
if err := run(context.Background(), d); err != nil {
os.Exit(1)
}
}
}
func run(ctx context.Context, d tui.Displayer) error {
ctx, stop := signal.NotifyContext(ctx, os.Interrupt, syscall.SIGTERM)
defer stop()
var (
storage credstore.Token
hasStorage bool
)
// Try to load existing tokens
loaded, err := tokenStore.Load(clientID)
switch {
case err != nil && !errors.Is(err, credstore.ErrNotFound):
d.Fatal(err)
return err
case err != nil:
d.TokensNotFound()
default:
storage = loaded
hasStorage = true
d.TokensFound()
// Check if access token is still valid
if time.Now().Before(storage.ExpiresAt) {
d.TokenValid()
} else {
d.TokenExpired()
d.Refreshing()
// Try to refresh
newStorage, err := refreshAccessToken(ctx, storage.RefreshToken, d)
if err != nil {
d.RefreshFailed(err)
hasStorage = false // Force device flow
} else {
storage = newStorage
d.RefreshOK()
}
}
}
// If no valid tokens, do device flow
if !hasStorage {
storage, err = performDeviceFlow(ctx, d)
if err != nil {
d.Fatal(err)
return err
}
}
// Display current token info
tokenPreview := storage.AccessToken
if len(tokenPreview) > 50 {
tokenPreview = tokenPreview[:50]
}
d.Done(tokenPreview, storage.TokenType, time.Until(storage.ExpiresAt).Round(time.Second))
// Verify token
d.Verifying()
if err := verifyToken(ctx, storage.AccessToken, d); err != nil {
d.VerifyFailed(err)
}
// Demonstrate automatic refresh on 401
if err := makeAPICallWithAutoRefresh(ctx, &storage, d); err != nil {
// Check if error is due to expired refresh token
if errors.Is(err, ErrRefreshTokenExpired) {
d.ReAuthRequired()
storage, err = performDeviceFlow(ctx, d)
if err != nil {
d.Fatal(err)
return err
}
// Retry API call with new tokens
d.TokenRefreshedRetrying()
if err := makeAPICallWithAutoRefresh(ctx, &storage, d); err != nil {
d.Fatal(err)
return err
}
} else {
d.APICallFailed(err)
}
}
return nil
}
// requestDeviceCode requests a device code from the OAuth server with retry logic
func requestDeviceCode(ctx context.Context) (*oauth2.DeviceAuthResponse, error) {
reqCtx, cancel := context.WithTimeout(ctx, deviceCodeRequestTimeout)
defer cancel()
data := url.Values{}
data.Set("client_id", clientID)
data.Set("scope", "read write")
req, err := http.NewRequestWithContext(
reqCtx,
http.MethodPost,
serverURL+endpointDeviceCode,
strings.NewReader(data.Encode()),
)
if err != nil {
return nil, fmt.Errorf("failed to create device code request: %w", err)
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
resp, err := retryClient.DoWithContext(reqCtx, req)
if err != nil {
return nil, fmt.Errorf("device code request failed: %w", err)
}
defer resp.Body.Close()
body, err := readResponseBody(resp.Body)
if err != nil {
return nil, err
}
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf(
"device code request failed with status %d: %s",
resp.StatusCode,
string(body),
)
}
var deviceResp struct {
DeviceCode string `json:"device_code"`
UserCode string `json:"user_code"`
VerificationURI string `json:"verification_uri"`
VerificationURIComplete string `json:"verification_uri_complete"`
ExpiresIn int `json:"expires_in"`
Interval int `json:"interval"`
}
if err := json.Unmarshal(body, &deviceResp); err != nil {
return nil, fmt.Errorf("failed to parse device code response: %w", err)
}
return &oauth2.DeviceAuthResponse{
DeviceCode: deviceResp.DeviceCode,
UserCode: deviceResp.UserCode,
VerificationURI: deviceResp.VerificationURI,
VerificationURIComplete: deviceResp.VerificationURIComplete,
Expiry: time.Now().Add(time.Duration(deviceResp.ExpiresIn) * time.Second),
Interval: int64(deviceResp.Interval),
}, nil
}
// performDeviceFlow performs the OAuth device authorization flow
func performDeviceFlow(ctx context.Context, d tui.Displayer) (credstore.Token, error) {
// Only TokenURL and ClientID are used downstream;
// requestDeviceCode() builds its own request directly.
config := &oauth2.Config{
ClientID: clientID,
Endpoint: oauth2.Endpoint{
TokenURL: serverURL + endpointToken,
},
}
// Step 1: Request device code (with retry logic)
deviceAuth, err := requestDeviceCode(ctx)
if err != nil {
return credstore.Token{}, fmt.Errorf("device code request failed: %w", err)
}
d.DeviceCodeReady(
deviceAuth.UserCode,
deviceAuth.VerificationURI,
deviceAuth.VerificationURIComplete,
deviceAuth.Expiry,
)
// Step 2: Poll for token
d.WaitingForAuth()
token, err := pollForTokenWithProgress(ctx, config, deviceAuth, d)
if err != nil {
return credstore.Token{}, fmt.Errorf("token poll failed: %w", err)
}
d.AuthSuccess()
// Convert to Token and save
storage := credstore.Token{
AccessToken: token.AccessToken,
RefreshToken: token.RefreshToken,
TokenType: token.Type(),
ExpiresAt: token.Expiry,
ClientID: clientID,
}
if err := tokenStore.Save(clientID, storage); err != nil {
d.TokenSaveFailed(err)
} else {
d.TokenSaved(tokenStore.String())
}
return storage, nil
}
// pollForTokenWithProgress polls for token while reporting progress via Displayer.
// Implements additive backoff (+5s) for slow_down errors per RFC 8628 §3.5.
func pollForTokenWithProgress(
ctx context.Context,
config *oauth2.Config,
deviceAuth *oauth2.DeviceAuthResponse,
d tui.Displayer,
) (*oauth2.Token, error) {
// Initial polling interval (from DeviceAuthResponse)
interval := deviceAuth.Interval
if interval == 0 {
interval = 5 // Default to 5 seconds per RFC 8628
}
// Backoff state
pollInterval := time.Duration(interval) * time.Second
pollTicker := time.NewTicker(pollInterval)
defer pollTicker.Stop()
for {
select {
case <-ctx.Done():
return nil, ctx.Err()
case <-pollTicker.C:
// Attempt to exchange device code for token
token, err := exchangeDeviceCode(
ctx,
config.Endpoint.TokenURL,
config.ClientID,
deviceAuth.DeviceCode,
)
if err != nil {
var oauthErr *oauth2.RetrieveError
if errors.As(err, &oauthErr) {
// Parse OAuth error response
var errResp ErrorResponse
if jsonErr := json.Unmarshal(oauthErr.Body, &errResp); jsonErr == nil {
switch errResp.Error {
case oauthErrAuthorizationPending:
// User hasn't authorized yet, continue polling
continue
case oauthErrSlowDown:
// Server requests slower polling - add 5s per RFC 8628 §3.5
pollInterval = min(pollInterval+5*time.Second, 60*time.Second)
pollTicker.Reset(pollInterval)
d.PollSlowDown(pollInterval)
continue
case oauthErrExpiredToken:
return nil, errors.New("device code expired, please restart the flow")
case oauthErrAccessDenied:
return nil, errors.New("user denied authorization")
default:
return nil, fmt.Errorf(
"authorization failed: %s - %s",
errResp.Error,
errResp.ErrorDescription,
)
}
}
}
// Unknown error
return nil, fmt.Errorf("token exchange failed: %w", err)
}
// Success!
return token, nil
}
}
}
// exchangeDeviceCode exchanges device code for access token
func exchangeDeviceCode(
ctx context.Context,
tokenURL, clientID, deviceCode string,
) (*oauth2.Token, error) {
reqCtx, cancel := context.WithTimeout(ctx, tokenExchangeTimeout)
defer cancel()
data := url.Values{}
data.Set("grant_type", "urn:ietf:params:oauth:grant-type:device_code")
data.Set("device_code", deviceCode)
data.Set("client_id", clientID)
req, err := http.NewRequestWithContext(
reqCtx,
http.MethodPost,
tokenURL,
strings.NewReader(data.Encode()),
)
if err != nil {
return nil, fmt.Errorf("failed to create request: %w", err)
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
resp, err := retryClient.DoWithContext(reqCtx, req)
if err != nil {
return nil, fmt.Errorf("token exchange request failed: %w", err)
}
defer resp.Body.Close()
body, err := readResponseBody(resp.Body)
if err != nil {
return nil, err
}
if resp.StatusCode != http.StatusOK {
return nil, &oauth2.RetrieveError{
Response: resp,
Body: body,
}
}
var tokenResp tokenResponse
if err := json.Unmarshal(body, &tokenResp); err != nil {
return nil, fmt.Errorf("failed to parse token response: %w", err)
}
// Validate token response
if err := validateTokenResponse(
tokenResp.AccessToken,
tokenResp.TokenType,
tokenResp.ExpiresIn,
); err != nil {
return nil, fmt.Errorf("invalid token response: %w", err)
}
token := &oauth2.Token{
AccessToken: tokenResp.AccessToken,
RefreshToken: tokenResp.RefreshToken,
TokenType: tokenResp.TokenType,
Expiry: time.Now().Add(time.Duration(tokenResp.ExpiresIn) * time.Second),
}
return token, nil
}
func verifyToken(ctx context.Context, accessToken string, d tui.Displayer) error {
reqCtx, cancel := context.WithTimeout(ctx, tokenVerificationTimeout)
defer cancel()
req, err := http.NewRequestWithContext(
reqCtx, http.MethodGet, serverURL+endpointTokenInfo, nil,
)
if err != nil {
return fmt.Errorf("failed to create request: %w", err)
}
req.Header.Set("Authorization", "Bearer "+accessToken)
resp, err := retryClient.DoWithContext(reqCtx, req)
if err != nil {
return fmt.Errorf("token verification request failed: %w", err)
}
defer resp.Body.Close()
body, err := readResponseBody(resp.Body)
if err != nil {
return err
}
if resp.StatusCode != http.StatusOK {
var errResp ErrorResponse
if err := json.Unmarshal(body, &errResp); err != nil {
return fmt.Errorf("server returned status %d: %s", resp.StatusCode, string(body))
}
return fmt.Errorf("%s: %s", errResp.Error, errResp.ErrorDescription)
}
d.VerifyOK(string(body))
return nil
}
// refreshAccessToken refreshes the access token using refresh token
func refreshAccessToken(
ctx context.Context,
refreshToken string,
d tui.Displayer,
) (credstore.Token, error) {
reqCtx, cancel := context.WithTimeout(ctx, refreshTokenTimeout)
defer cancel()
data := url.Values{}
data.Set("grant_type", "refresh_token")
data.Set("refresh_token", refreshToken)
data.Set("client_id", clientID)
req, err := http.NewRequestWithContext(
reqCtx,
http.MethodPost,
serverURL+endpointToken,
strings.NewReader(data.Encode()),
)
if err != nil {
return credstore.Token{}, fmt.Errorf("failed to create request: %w", err)
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
resp, err := retryClient.DoWithContext(reqCtx, req)
if err != nil {
return credstore.Token{}, fmt.Errorf("refresh request failed: %w", err)
}
defer resp.Body.Close()
body, err := readResponseBody(resp.Body)
if err != nil {
return credstore.Token{}, err
}
if resp.StatusCode != http.StatusOK {
var errResp ErrorResponse
if err := json.Unmarshal(body, &errResp); err == nil {
// Check if refresh token is expired or invalid
if errResp.Error == oauthErrInvalidGrant || errResp.Error == oauthErrInvalidToken {
return credstore.Token{}, ErrRefreshTokenExpired
}
return credstore.Token{}, fmt.Errorf("%s: %s", errResp.Error, errResp.ErrorDescription)
}
return credstore.Token{}, fmt.Errorf(
"refresh failed with status %d: %s",
resp.StatusCode,
string(body),
)
}
var tokenResp tokenResponse
if err := json.Unmarshal(body, &tokenResp); err != nil {
return credstore.Token{}, fmt.Errorf("failed to parse token response: %w", err)
}
// Validate token response
if err := validateTokenResponse(
tokenResp.AccessToken,
tokenResp.TokenType,
tokenResp.ExpiresIn,
); err != nil {
return credstore.Token{}, fmt.Errorf("invalid token response: %w", err)
}
// Handle refresh token rotation modes:
// - Rotation mode: Server returns new refresh_token (use it)
// - Fixed mode: Server doesn't return refresh_token (preserve old one)
newRefreshToken := tokenResp.RefreshToken
if newRefreshToken == "" {
// Server didn't return a new refresh token (fixed mode)
newRefreshToken = refreshToken
}
storage := credstore.Token{
AccessToken: tokenResp.AccessToken,
RefreshToken: newRefreshToken,
TokenType: tokenResp.TokenType,
ExpiresAt: time.Now().Add(time.Duration(tokenResp.ExpiresIn) * time.Second),
ClientID: clientID,
}
// Save updated tokens
if err := tokenStore.Save(clientID, storage); err != nil {
d.TokenSaveFailed(err)
}
return storage, nil
}
// makeAPICallWithAutoRefresh demonstrates automatic refresh on 401
func makeAPICallWithAutoRefresh(
ctx context.Context,
storage *credstore.Token,
d tui.Displayer,
) error {
// Try with current access token
reqCtx, cancel := context.WithTimeout(ctx, tokenVerificationTimeout)
defer cancel()
req, err := http.NewRequestWithContext(
reqCtx, http.MethodGet, serverURL+endpointTokenInfo, nil,
)
if err != nil {
return fmt.Errorf("failed to create request: %w", err)
}
req.Header.Set("Authorization", "Bearer "+storage.AccessToken)
resp, err := retryClient.DoWithContext(reqCtx, req)
if err != nil {
return fmt.Errorf("API request failed: %w", err)
}
// If 401, drain and close the first response body to allow connection reuse,
// then refresh the token and retry.
if resp.StatusCode == http.StatusUnauthorized {
_, _ = io.Copy(io.Discard, resp.Body)
resp.Body.Close()
d.AccessTokenRejected()
newStorage, err := refreshAccessToken(ctx, storage.RefreshToken, d)
if err != nil {
// If refresh token is expired, propagate the error to trigger device flow
if errors.Is(err, ErrRefreshTokenExpired) {
return ErrRefreshTokenExpired
}
return fmt.Errorf("refresh failed: %w", err)
}
// Update storage in memory
// Note: newStorage has already been saved to disk by refreshAccessToken()
*storage = newStorage
d.TokenRefreshedRetrying()
// Retry with new token
retryCtx, retryCancel := context.WithTimeout(ctx, tokenVerificationTimeout)
defer retryCancel()
req, err = http.NewRequestWithContext(
retryCtx, http.MethodGet, serverURL+endpointTokenInfo, nil,
)
if err != nil {
return fmt.Errorf("failed to create retry request: %w", err)
}
req.Header.Set("Authorization", "Bearer "+storage.AccessToken)
resp, err = retryClient.DoWithContext(retryCtx, req)
if err != nil {
return fmt.Errorf("retry failed: %w", err)
}
defer resp.Body.Close()
} else {
defer resp.Body.Close()
}
body, err := readResponseBody(resp.Body)
if err != nil {
return err
}
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("API call failed with status %d: %s", resp.StatusCode, string(body))
}
d.APICallOK()
return nil
}