-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdevice_flow.go
More file actions
363 lines (315 loc) · 9.49 KB
/
device_flow.go
File metadata and controls
363 lines (315 loc) · 9.49 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
package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"net/url"
"strings"
"time"
retry "github.com/appleboy/go-httpretry"
"github.com/go-authgate/cli/tui"
"github.com/go-authgate/sdk-go/credstore"
"golang.org/x/oauth2"
)
// deviceCodeResponse holds the device authorization response (RFC 8628 §3.2).
type deviceCodeResponse 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"`
}
const (
defaultPollInterval = 5 // seconds, RFC 8628 §3.5 recommended minimum
maxPollInterval = 60 * time.Second // RFC 8628 §3.5 cap for slow_down backoff
)
// requestDeviceCode requests a device code from the OAuth server.
func requestDeviceCode(ctx context.Context, cfg *AppConfig) (*oauth2.DeviceAuthResponse, error) {
reqCtx, cancel := context.WithTimeout(ctx, cfg.DeviceCodeRequestTimeout)
defer cancel()
data := url.Values{}
data.Set("client_id", cfg.ClientID)
data.Set("scope", cfg.Scope)
resp, err := cfg.RetryClient.Post(reqCtx, cfg.Endpoints.DeviceAuthorizationURL,
retry.WithBody("application/x-www-form-urlencoded", strings.NewReader(data.Encode())),
)
if err != nil {
return nil, fmt.Errorf("device code request failed: %w", err)
}
defer resp.Body.Close()
body, err := readResponseBody(resp, cfg.MaxResponseBodySize)
if err != nil {
return nil, err
}
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf(
"device code request failed: %w",
formatHTTPError(body, resp.StatusCode),
)
}
var deviceResp deviceCodeResponse
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
}
// pollErrorAction represents the action to take after handling a poll error.
type pollErrorAction int
const (
pollContinue pollErrorAction = iota // authorization_pending — keep polling
pollBackoff // slow_down — increase interval and continue
pollFail // terminal error
)
// pollErrorResult holds the outcome of handling a device poll error.
type pollErrorResult struct {
action pollErrorAction
err error
}
// handleDevicePollError parses an error from exchangeDeviceCode and determines
// the appropriate action. For slow_down, it updates the interval and resets the ticker.
func handleDevicePollError(
err error,
pollInterval *time.Duration,
backoffMultiplier *float64,
pollTicker *time.Ticker,
) pollErrorResult {
var oauthErr *oauth2.RetrieveError
if !errors.As(err, &oauthErr) {
return pollErrorResult{pollFail, fmt.Errorf("token exchange failed: %w", err)}
}
errResp, ok := parseOAuthError(oauthErr.Body)
if !ok {
return pollErrorResult{
pollFail,
fmt.Errorf("token exchange failed (body: %s): %w", oauthErr.Body, err),
}
}
switch errResp.Error {
case "authorization_pending":
return pollErrorResult{action: pollContinue}
case "slow_down":
*backoffMultiplier *= 1.5
newInterval := min(
time.Duration(float64(*pollInterval)*(*backoffMultiplier)),
maxPollInterval,
)
*pollInterval = newInterval
pollTicker.Reset(*pollInterval)
return pollErrorResult{action: pollBackoff}
case "expired_token":
return pollErrorResult{pollFail, errors.New("device code expired, please restart the flow")}
case "access_denied":
return pollErrorResult{pollFail, errors.New("user denied authorization")}
default:
return pollErrorResult{
pollFail,
fmt.Errorf("authorization failed: %s - %s", errResp.Error, errResp.ErrorDescription),
}
}
}
// exchangeDeviceCode exchanges a device code for an access token.
func exchangeDeviceCode(
ctx context.Context,
cfg *AppConfig,
tokenURL, cID, deviceCode string,
) (*oauth2.Token, error) {
reqCtx, cancel := context.WithTimeout(ctx, cfg.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", cID)
resp, err := cfg.RetryClient.Post(reqCtx, tokenURL,
retry.WithBody("application/x-www-form-urlencoded", strings.NewReader(data.Encode())),
)
if err != nil {
return nil, fmt.Errorf("request failed: %w", err)
}
defer resp.Body.Close()
body, err := readResponseBody(resp, cfg.MaxResponseBodySize)
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)
}
if err := validateTokenResponse(
tokenResp.AccessToken,
tokenResp.TokenType,
tokenResp.ExpiresIn,
); err != nil {
return nil, fmt.Errorf("invalid token response: %w", err)
}
return &oauth2.Token{
AccessToken: tokenResp.AccessToken,
RefreshToken: tokenResp.RefreshToken,
TokenType: tokenResp.TokenType,
Expiry: time.Now().Add(time.Duration(tokenResp.ExpiresIn) * time.Second),
}, nil
}
// performDeviceFlowWithUpdates runs the OAuth 2.0 Device Authorization Grant
// and sends progress updates through the provided channel.
func performDeviceFlowWithUpdates(
ctx context.Context,
cfg *AppConfig,
updates chan<- tui.FlowUpdate,
) (*tui.TokenStorage, error) {
config := &oauth2.Config{
ClientID: cfg.ClientID,
Endpoint: oauth2.Endpoint{
DeviceAuthURL: cfg.Endpoints.DeviceAuthorizationURL,
TokenURL: cfg.Endpoints.TokenURL,
},
Scopes: strings.Fields(cfg.Scope),
}
updates <- tui.FlowUpdate{
Type: tui.StepStart,
Step: 1,
TotalSteps: 2,
Message: "Requesting device code",
}
deviceAuth, err := requestDeviceCode(ctx, cfg)
if err != nil {
updates <- tui.FlowUpdate{
Type: tui.StepError,
Step: 1,
Message: err.Error(),
}
return nil, err
}
updates <- tui.FlowUpdate{
Type: tui.DeviceCodeReceived,
Step: 1,
TotalSteps: 2,
Data: map[string]any{
"user_code": deviceAuth.UserCode,
"verification_uri": deviceAuth.VerificationURI,
"verification_uri_complete": deviceAuth.VerificationURIComplete,
},
}
updates <- tui.FlowUpdate{
Type: tui.StepStart,
Step: 2,
TotalSteps: 2,
Message: "Waiting for authorization",
}
token, err := pollForTokenWithUpdates(ctx, cfg, config, deviceAuth, updates)
if err != nil {
updates <- tui.FlowUpdate{
Type: tui.StepError,
Step: 2,
Message: fmt.Sprintf("Authorization failed: %v", err),
}
return nil, fmt.Errorf("token poll failed: %w", err)
}
updates <- tui.FlowUpdate{
Type: tui.StepComplete,
Step: 2,
TotalSteps: 2,
}
storage := &credstore.Token{
AccessToken: token.AccessToken,
RefreshToken: token.RefreshToken,
TokenType: token.Type(),
ExpiresAt: token.Expiry,
ClientID: cfg.ClientID,
}
if err := cfg.Store.Save(cfg.ClientID, *storage); err != nil {
updates <- tui.FlowUpdate{
Type: tui.StepError,
Message: fmt.Sprintf("Warning: Failed to save tokens: %v", err),
}
}
return toTUITokenStorage(storage, "device", cfg.Store.String()), nil
}
// pollForTokenWithUpdates polls for a token while sending progress updates.
// Implements exponential backoff for slow_down errors per RFC 8628.
func pollForTokenWithUpdates(
ctx context.Context,
cfg *AppConfig,
config *oauth2.Config,
deviceAuth *oauth2.DeviceAuthResponse,
updates chan<- tui.FlowUpdate,
) (*oauth2.Token, error) {
interval := deviceAuth.Interval
if interval == 0 {
interval = defaultPollInterval
}
pollInterval := time.Duration(interval) * time.Second
backoffMultiplier := 1.0
pollCount := 0
startTime := time.Now()
pollTicker := time.NewTicker(pollInterval)
defer pollTicker.Stop()
uiTicker := time.NewTicker(500 * time.Millisecond)
defer uiTicker.Stop()
for {
select {
case <-ctx.Done():
return nil, ctx.Err()
case <-pollTicker.C:
pollCount++
updates <- tui.FlowUpdate{
Type: tui.PollingUpdate,
Message: "Polling authorization server",
Data: map[string]any{
"poll_count": pollCount,
"interval": pollInterval,
"elapsed": time.Since(startTime),
},
}
token, err := exchangeDeviceCode(
ctx,
cfg,
config.Endpoint.TokenURL,
config.ClientID,
deviceAuth.DeviceCode,
)
if err != nil {
oldInterval := pollInterval
result := handleDevicePollError(err, &pollInterval, &backoffMultiplier, pollTicker)
switch result.action {
case pollContinue:
continue
case pollBackoff:
updates <- tui.FlowUpdate{
Type: tui.BackoffChanged,
Message: "Server requested slower polling",
Data: map[string]any{
"old_interval": oldInterval,
"new_interval": pollInterval,
},
}
continue
default:
return nil, result.err
}
}
return token, nil
case <-uiTicker.C:
updates <- tui.FlowUpdate{
Type: tui.TimerTick,
Data: map[string]any{
"elapsed": time.Since(startTime),
},
}
}
}
}