-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbrowser_flow.go
More file actions
216 lines (194 loc) · 5.59 KB
/
browser_flow.go
File metadata and controls
216 lines (194 loc) · 5.59 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
package main
import (
"context"
"errors"
"fmt"
"net/url"
"time"
"github.com/go-authgate/cli/tui"
"github.com/go-authgate/sdk-go/credstore"
)
// buildAuthURL constructs the /oauth/authorize URL with all required parameters.
func buildAuthURL(cfg *AppConfig, state string, pkce *PKCEParams) string {
params := url.Values{}
params.Set("client_id", cfg.ClientID)
params.Set("redirect_uri", cfg.RedirectURI)
params.Set("response_type", "code")
params.Set("scope", cfg.Scope)
params.Set("state", state)
params.Set("code_challenge", pkce.Challenge)
params.Set("code_challenge_method", pkce.Method)
return cfg.Endpoints.AuthorizeURL + "?" + params.Encode()
}
// exchangeCode exchanges an authorization code for access + refresh tokens.
func exchangeCode(
ctx context.Context,
cfg *AppConfig,
code, codeVerifier string,
) (*credstore.Token, error) {
ctx, cancel := context.WithTimeout(ctx, cfg.TokenExchangeTimeout)
defer cancel()
data := url.Values{}
data.Set("grant_type", "authorization_code")
data.Set("code", code)
data.Set("redirect_uri", cfg.RedirectURI)
data.Set("client_id", cfg.ClientID)
data.Set("code_verifier", codeVerifier)
if !cfg.IsPublicClient() {
data.Set("client_secret", cfg.ClientSecret)
}
tokenResp, err := doTokenExchange(ctx, cfg, cfg.Endpoints.TokenURL, data, nil)
if err != nil {
return nil, err
}
return tokenResponseToCredstore(cfg, tokenResp), nil
}
// performBrowserFlowWithUpdates runs the Authorization Code Flow with PKCE
// and sends progress updates through the provided channel.
//
// Every exit path — success, soft error, and hard error — sends at least one
// update before returning, so the Bubble Tea TUI always receives a quit signal
// and never hangs.
//
// Returns:
// - (storage, true, nil) on success
// - (nil, false, nil) on a soft error (browser unavailable, timeout) —
// caller should fall back to Device Code Flow
// - (nil, false, err) on a hard error (CSRF mismatch, token exchange
// failure, OAuth server rejection, etc.)
func performBrowserFlowWithUpdates(
ctx context.Context,
cfg *AppConfig,
updates chan<- tui.FlowUpdate,
) (*tui.TokenStorage, bool, error) {
updates <- tui.FlowUpdate{
Type: tui.StepStart,
Step: 1,
TotalSteps: 3,
Message: "Generating PKCE parameters",
}
state, err := generateState()
if err != nil {
updates <- tui.FlowUpdate{
Type: tui.StepError,
Message: fmt.Sprintf("Failed to generate state: %v", err),
}
return nil, false, fmt.Errorf("failed to generate state: %w", err)
}
pkce, err := GeneratePKCE()
if err != nil {
updates <- tui.FlowUpdate{
Type: tui.StepError,
Message: fmt.Sprintf("Failed to generate PKCE parameters: %v", err),
}
return nil, false, fmt.Errorf("failed to generate PKCE: %w", err)
}
authURL := buildAuthURL(cfg, state, pkce)
updates <- tui.FlowUpdate{
Type: tui.StepStart,
Step: 1,
TotalSteps: 3,
Message: "Opening browser",
Data: map[string]any{
"url": authURL,
},
}
if err := openBrowser(ctx, authURL); err != nil {
// Browser failed to open — soft error, signal the caller to fall back.
updates <- tui.FlowUpdate{
Type: tui.StepError,
Fallback: true,
Message: fmt.Sprintf("Could not open browser: %v", err),
}
return nil, false, nil
}
updates <- tui.FlowUpdate{Type: tui.BrowserOpened}
updates <- tui.FlowUpdate{
Type: tui.StepStart,
Step: 2,
TotalSteps: 3,
Message: "Waiting for callback",
Data: map[string]any{
"port": cfg.CallbackPort,
},
}
// Start goroutine to send timer updates
done := make(chan struct{})
defer close(done)
go func() {
ticker := time.NewTicker(100 * time.Millisecond)
defer ticker.Stop()
startTime := time.Now()
for {
select {
case <-done:
return
case <-ctx.Done():
return
case <-ticker.C:
elapsed := time.Since(startTime)
progress := float64(elapsed) / float64(cfg.CallbackTimeout)
if progress > 1.0 {
progress = 1.0
}
update := tui.FlowUpdate{
Type: tui.TimerTick,
Progress: progress,
Data: map[string]any{
"elapsed": elapsed,
"timeout": cfg.CallbackTimeout,
},
}
select {
case updates <- update:
case <-done:
return
case <-ctx.Done():
return
}
}
}
}()
storage, err := startCallbackServer(ctx, cfg.CallbackPort, state, cfg.CallbackTimeout,
func(callbackCtx context.Context, code string) (*credstore.Token, error) {
updates <- tui.FlowUpdate{
Type: tui.StepStart,
Step: 3,
TotalSteps: 3,
Message: "Exchanging tokens",
}
return exchangeCode(callbackCtx, cfg, code, pkce.Verifier)
})
if err != nil {
if errors.Is(err, ErrCallbackTimeout) {
// Soft error — fall back to Device Code Flow silently.
updates <- tui.FlowUpdate{
Type: tui.StepError,
Fallback: true,
Message: "Browser authorization timed out",
}
return nil, false, nil
}
// Hard error (CSRF mismatch, token exchange failure, OAuth rejection,
// etc.) — surface it to the user.
updates <- tui.FlowUpdate{
Type: tui.StepError,
Step: 3,
Message: err.Error(),
}
return nil, false, fmt.Errorf("authentication failed: %w", err)
}
updates <- tui.FlowUpdate{Type: tui.CallbackReceived}
if err := cfg.Store.Save(storage.ClientID, *storage); err != nil {
updates <- tui.FlowUpdate{
Type: tui.StepError,
Message: fmt.Sprintf("Warning: Failed to save tokens: %v", err),
}
}
updates <- tui.FlowUpdate{
Type: tui.StepComplete,
Step: 3,
TotalSteps: 3,
}
return toTUITokenStorage(storage, "browser", cfg.Store.String()), true, nil
}