-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauth.go
More file actions
180 lines (154 loc) · 5.32 KB
/
auth.go
File metadata and controls
180 lines (154 loc) · 5.32 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
package main
import (
"context"
"errors"
"fmt"
"net/http"
"net/url"
"os"
retry "github.com/appleboy/go-httpretry"
"github.com/go-authgate/cli/tui"
"github.com/go-authgate/sdk-go/credstore"
)
// authenticate selects and runs the appropriate OAuth flow:
//
// 1. --device flag → Device Code Flow (forced)
// 2. Environment signals (SSH, no display, port busy) → Device Code Flow
// 3. Browser available → Authorization Code Flow with PKCE
// - openBrowser() error → immediate fallback to Device Code Flow
func authenticate(
ctx context.Context,
ui tui.Manager,
cfg *AppConfig,
) (*credstore.Token, string, error) {
deviceFlow := func(ctx context.Context, updates chan<- tui.FlowUpdate) (*tui.TokenStorage, error) {
return performDeviceFlowWithUpdates(ctx, cfg, updates)
}
browserFlow := func(ctx context.Context, updates chan<- tui.FlowUpdate) (*tui.TokenStorage, bool, error) {
return performBrowserFlowWithUpdates(ctx, cfg, updates)
}
if cfg.ForceDevice {
ui.ShowFlowSelection("Device Code Flow (forced via flag)")
tuiStorage, err := ui.RunDeviceFlow(ctx, deviceFlow)
return fromTUITokenStorage(tuiStorage), flowFromTUI(tuiStorage), err
}
avail := checkBrowserAvailability(ctx, cfg.CallbackPort)
if !avail.Available {
ui.ShowFlowSelection(fmt.Sprintf("Device Code Flow (%s)", avail.Reason))
tuiStorage, err := ui.RunDeviceFlow(ctx, deviceFlow)
return fromTUITokenStorage(tuiStorage), flowFromTUI(tuiStorage), err
}
ui.ShowFlowSelection("Authorization Code Flow (browser)")
tuiStorage, ok, err := ui.RunBrowserFlow(ctx, browserFlow)
if err != nil {
return nil, "", err
}
if !ok {
// openBrowser() failed; fall back to Device Code Flow immediately.
ui.ShowFlowSelection("Device Code Flow (browser unavailable)")
tuiStorage, err := ui.RunDeviceFlow(ctx, deviceFlow)
return fromTUITokenStorage(tuiStorage), flowFromTUI(tuiStorage), err
}
return fromTUITokenStorage(tuiStorage), flowFromTUI(tuiStorage), nil
}
// refreshAccessToken exchanges a refresh token for a new access token.
func refreshAccessToken(
ctx context.Context,
cfg *AppConfig,
refreshToken string,
) (*credstore.Token, error) {
ctx, cancel := context.WithTimeout(ctx, cfg.RefreshTokenTimeout)
defer cancel()
data := url.Values{}
data.Set("grant_type", "refresh_token")
data.Set("refresh_token", refreshToken)
data.Set("client_id", cfg.ClientID)
if !cfg.IsPublicClient() {
data.Set("client_secret", cfg.ClientSecret)
}
tokenResp, err := doTokenExchange(ctx, cfg, cfg.Endpoints.TokenURL, data,
func(errResp ErrorResponse, _ []byte) error {
if errResp.Error == "invalid_grant" || errResp.Error == "invalid_token" {
return ErrRefreshTokenExpired
}
return nil // fall through to default error formatting
},
)
if err != nil {
return nil, err
}
storage := tokenResponseToCredstore(cfg, tokenResp)
// Preserve the old refresh token in fixed-mode (server may not return a new one).
if storage.RefreshToken == "" {
storage.RefreshToken = refreshToken
}
if err := cfg.Store.Save(cfg.ClientID, *storage); err != nil {
fmt.Fprintf(os.Stderr, "Warning: Failed to save refreshed tokens: %v\n", err)
}
return storage, nil
}
// verifyToken verifies an access token with the OAuth server.
func verifyToken(ctx context.Context, cfg *AppConfig, accessToken string) (string, error) {
ctx, cancel := context.WithTimeout(ctx, cfg.TokenVerificationTimeout)
defer cancel()
resp, err := cfg.RetryClient.Get(ctx, cfg.Endpoints.TokenInfoURL,
retry.WithHeader("Authorization", "Bearer "+accessToken),
)
if err != nil {
return "", fmt.Errorf("request failed: %w", err)
}
defer resp.Body.Close()
body, err := readResponseBody(resp, cfg.MaxResponseBodySize)
if err != nil {
return "", err
}
if resp.StatusCode != http.StatusOK {
return "", formatHTTPError(body, resp.StatusCode)
}
return string(body), nil
}
// makeAPICallWithAutoRefresh demonstrates the 401 → refresh → retry pattern.
func makeAPICallWithAutoRefresh(
ctx context.Context,
cfg *AppConfig,
storage *credstore.Token,
ui tui.Manager,
) error {
resp, err := cfg.RetryClient.Get(ctx, cfg.Endpoints.TokenInfoURL,
retry.WithHeader("Authorization", "Bearer "+storage.AccessToken),
)
if err != nil {
return fmt.Errorf("API request failed: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusUnauthorized {
ui.ShowStatus(tui.StatusUpdate{Event: tui.EventAccessTokenRejected})
newStorage, err := refreshAccessToken(ctx, cfg, storage.RefreshToken)
if err != nil {
if errors.Is(err, ErrRefreshTokenExpired) {
return ErrRefreshTokenExpired
}
return fmt.Errorf("refresh failed: %w", err)
}
storage.AccessToken = newStorage.AccessToken
storage.RefreshToken = newStorage.RefreshToken
storage.ExpiresAt = newStorage.ExpiresAt
ui.ShowStatus(tui.StatusUpdate{Event: tui.EventTokenRefreshedRetrying})
resp, err = cfg.RetryClient.Get(ctx, cfg.Endpoints.TokenInfoURL,
retry.WithHeader("Authorization", "Bearer "+storage.AccessToken),
)
if err != nil {
return fmt.Errorf("retry failed: %w", err)
}
defer resp.Body.Close()
}
body, err := readResponseBody(resp, cfg.MaxResponseBodySize)
if err != nil {
return err
}
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("API call failed with status %d: %s", resp.StatusCode, string(body))
}
ui.ShowStatus(tui.StatusUpdate{Event: tui.EventAPICallSuccess})
return nil
}