-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpolling_test.go
More file actions
304 lines (258 loc) · 8.2 KB
/
polling_test.go
File metadata and controls
304 lines (258 loc) · 8.2 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
package main
import (
"context"
"encoding/json"
"errors"
"net/http"
"net/http/httptest"
"sync/atomic"
"testing"
"time"
"github.com/go-authgate/device-cli/tui"
"golang.org/x/oauth2"
)
const testAccessToken = "test-access-token"
func TestPollForToken_AuthorizationPending(t *testing.T) {
attempts := atomic.Int32{}
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
attempts.Add(1)
// Return authorization_pending for first 2 attempts, then success
if attempts.Load() < 3 {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusBadRequest)
_ = json.NewEncoder(w).Encode(map[string]string{
"error": "authorization_pending",
"error_description": "User has not yet authorized",
})
return
}
// Success on 3rd attempt
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(map[string]any{
"access_token": testAccessToken,
"refresh_token": "test-refresh-token",
"token_type": "Bearer",
"expires_in": 3600,
})
}))
defer server.Close()
config := &oauth2.Config{
ClientID: "test-client",
Endpoint: oauth2.Endpoint{
TokenURL: server.URL,
},
}
deviceAuth := &oauth2.DeviceAuthResponse{
DeviceCode: "test-device-code",
Interval: 1, // 1 second for testing
}
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
token, err := pollForTokenWithProgress(ctx, config, deviceAuth, tui.NoopDisplayer{})
if err != nil {
t.Fatalf("Expected success, got error: %v", err)
}
if token.AccessToken != testAccessToken {
t.Errorf("Expected access token 'test-access-token', got '%s'", token.AccessToken)
}
if attempts.Load() < 3 {
t.Errorf("Expected at least 3 attempts, got %d", attempts.Load())
}
}
func TestPollForToken_SlowDown(t *testing.T) {
attempts := atomic.Int32{}
slowDownCount := atomic.Int32{}
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
n := attempts.Add(1)
// Return slow_down on the first attempt
if n == 1 {
slowDownCount.Add(1)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusBadRequest)
_ = json.NewEncoder(w).Encode(map[string]string{
"error": "slow_down",
"error_description": "Polling too frequently",
})
return
}
// Return authorization_pending on second attempt
if n == 2 {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusBadRequest)
_ = json.NewEncoder(w).Encode(map[string]string{
"error": "authorization_pending",
"error_description": "User has not yet authorized",
})
return
}
// Success on third attempt
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(map[string]any{
"access_token": testAccessToken,
"refresh_token": "test-refresh-token",
"token_type": "Bearer",
"expires_in": 3600,
})
}))
defer server.Close()
config := &oauth2.Config{
ClientID: "test-client",
Endpoint: oauth2.Endpoint{
TokenURL: server.URL,
},
}
deviceAuth := &oauth2.DeviceAuthResponse{
DeviceCode: "test-device-code",
Interval: 1, // 1 second for testing
}
// After 1 slow_down the interval becomes 1+5=6s; with an additional authorization_pending
// before success, the third attempt occurs after ~1s + 6s + 6s ≈ 13s, so use a generous timeout.
ctx, cancel := context.WithTimeout(context.Background(), 25*time.Second)
defer cancel()
token, err := pollForTokenWithProgress(ctx, config, deviceAuth, tui.NoopDisplayer{})
if err != nil {
t.Fatalf("Expected success, got error: %v", err)
}
if token.AccessToken != testAccessToken {
t.Errorf("Expected access token 'test-access-token', got '%s'", token.AccessToken)
}
if slowDownCount.Load() < 1 {
t.Errorf("Expected at least 1 slow_down response, got %d", slowDownCount.Load())
}
// Verify that polling continued after slow_down
if attempts.Load() < 3 {
t.Errorf(
"Expected at least 3 attempts (1 slow_down + 1 pending + 1 success), got %d",
attempts.Load(),
)
}
}
func TestPollForToken_ErrorCases(t *testing.T) {
tests := []struct {
name string
errorCode string
errorDesc string
expectedErr string
}{
{
name: "ExpiredToken",
errorCode: "expired_token",
errorDesc: "Device code has expired",
expectedErr: "device code expired, please restart the flow",
},
{
name: "AccessDenied",
errorCode: "access_denied",
errorDesc: "User denied the authorization request",
expectedErr: "user denied authorization",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
server := httptest.NewServer(
http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusBadRequest)
_ = json.NewEncoder(w).Encode(map[string]string{
"error": tt.errorCode,
"error_description": tt.errorDesc,
})
}),
)
defer server.Close()
config := &oauth2.Config{
ClientID: "test-client",
Endpoint: oauth2.Endpoint{
TokenURL: server.URL,
},
}
deviceAuth := &oauth2.DeviceAuthResponse{
DeviceCode: "test-device-code",
Interval: 1,
}
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
_, err := pollForTokenWithProgress(ctx, config, deviceAuth, tui.NoopDisplayer{})
if err == nil {
t.Fatalf("Expected error for %s, got nil", tt.name)
}
if err.Error() != tt.expectedErr {
t.Errorf("Expected %q error, got: %v", tt.expectedErr, err)
}
})
}
}
func TestPollForToken_ContextTimeout(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Always return pending
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusBadRequest)
_ = json.NewEncoder(w).Encode(map[string]string{
"error": "authorization_pending",
"error_description": "User has not yet authorized",
})
}))
defer server.Close()
config := &oauth2.Config{
ClientID: "test-client",
Endpoint: oauth2.Endpoint{
TokenURL: server.URL,
},
}
deviceAuth := &oauth2.DeviceAuthResponse{
DeviceCode: "test-device-code",
Interval: 1,
}
// Very short timeout to trigger context cancellation
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
_, err := pollForTokenWithProgress(ctx, config, deviceAuth, tui.NoopDisplayer{})
if err == nil {
t.Fatal("Expected context timeout error, got nil")
}
// Context error should be wrapped in the error chain
if !errors.Is(err, context.DeadlineExceeded) {
t.Errorf("Expected context.DeadlineExceeded in error chain, got: %v", err)
}
}
func TestExchangeDeviceCode_Success(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
t.Errorf("Expected POST request, got %s", r.Method)
}
if err := r.ParseForm(); err != nil {
t.Fatalf("Failed to parse form: %v", err)
}
if r.FormValue("grant_type") != "urn:ietf:params:oauth:grant-type:device_code" {
t.Errorf("Expected device_code grant type, got %s", r.FormValue("grant_type"))
}
if r.FormValue("device_code") != "test-device-code" {
t.Errorf(
"Expected device_code 'test-device-code', got '%s'",
r.FormValue("device_code"),
)
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(map[string]any{
"access_token": testAccessToken,
"refresh_token": "test-refresh-token",
"token_type": "Bearer",
"expires_in": 3600,
})
}))
defer server.Close()
ctx := context.Background()
token, err := exchangeDeviceCode(ctx, server.URL, "test-client", "test-device-code")
if err != nil {
t.Fatalf("Expected success, got error: %v", err)
}
if token.AccessToken != testAccessToken {
t.Errorf("Expected access token 'test-access-token', got '%s'", token.AccessToken)
}
if token.RefreshToken != "test-refresh-token" {
t.Errorf("Expected refresh token 'test-refresh-token', got '%s'", token.RefreshToken)
}
if token.TokenType != "Bearer" {
t.Errorf("Expected token type 'Bearer', got '%s'", token.TokenType)
}
}