-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpolling_test.go
More file actions
305 lines (265 loc) · 8.6 KB
/
polling_test.go
File metadata and controls
305 lines (265 loc) · 8.6 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
package main
import (
"context"
"encoding/json"
"errors"
"net/http"
"net/http/httptest"
"sync/atomic"
"testing"
"time"
"github.com/go-authgate/cli/tui"
"golang.org/x/oauth2"
)
const testAccessToken = "test-access-token"
// drainUpdates consumes FlowUpdate messages in the background so the producer
// never blocks. It signals the goroutine to stop via a done channel on
// cleanup, without closing the producer-owned updates channel.
func drainUpdates(t *testing.T, ch <-chan tui.FlowUpdate) {
t.Helper()
done := make(chan struct{})
t.Cleanup(func() { close(done) })
go func() {
for {
select {
case <-ch:
case <-done:
return
}
}
}()
}
func TestPollForToken_AuthorizationPending(t *testing.T) {
attempts := atomic.Int32{}
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
attempts.Add(1)
if attempts.Load() < 3 {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusBadRequest)
if err := json.NewEncoder(w).Encode(map[string]string{
"error": "authorization_pending",
"error_description": "User has not yet authorized",
}); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
return
}
w.Header().Set("Content-Type", "application/json")
if err := json.NewEncoder(w).Encode(map[string]any{
"access_token": testAccessToken,
"refresh_token": "test-refresh-token",
"token_type": "Bearer",
"expires_in": 3600,
}); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}))
defer server.Close()
cfg := testConfig(t)
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(), 10*time.Second)
defer cancel()
updates := make(chan tui.FlowUpdate, 100)
drainUpdates(t, updates)
token, err := pollForTokenWithUpdates(ctx, cfg, config, deviceAuth, updates)
if err != nil {
t.Fatalf("expected success, got error: %v", err)
}
if token.AccessToken != testAccessToken {
t.Errorf("access token = %q, want %q", token.AccessToken, testAccessToken)
}
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) {
attempts.Add(1)
if attempts.Load() <= 2 {
slowDownCount.Add(1)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusBadRequest)
if err := json.NewEncoder(w).Encode(map[string]string{
"error": "slow_down",
"error_description": "Polling too frequently",
}); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
return
}
if attempts.Load() < 5 {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusBadRequest)
if err := json.NewEncoder(w).Encode(map[string]string{
"error": "authorization_pending",
"error_description": "User has not yet authorized",
}); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
return
}
w.Header().Set("Content-Type", "application/json")
if err := json.NewEncoder(w).Encode(map[string]any{
"access_token": testAccessToken,
"refresh_token": "test-refresh-token",
"token_type": "Bearer",
"expires_in": 3600,
}); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}))
defer server.Close()
cfg := testConfig(t)
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(), 15*time.Second)
defer cancel()
updates := make(chan tui.FlowUpdate, 100)
drainUpdates(t, updates)
token, err := pollForTokenWithUpdates(ctx, cfg, config, deviceAuth, updates)
if err != nil {
t.Fatalf("expected success, got error: %v", err)
}
if token.AccessToken != testAccessToken {
t.Errorf("access token = %q, want %q", token.AccessToken, testAccessToken)
}
if slowDownCount.Load() < 2 {
t.Errorf("expected at least 2 slow_down responses, got %d", slowDownCount.Load())
}
}
// pollForTokenErrorTest is a shared helper for tests that expect pollForTokenWithUpdates
// to return a specific error when the server responds with a terminal OAuth error code.
func pollForTokenErrorTest(t *testing.T, errCode, errDesc, expectedMsg string) {
t.Helper()
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusBadRequest)
if err := json.NewEncoder(w).Encode(map[string]string{
"error": errCode,
"error_description": errDesc,
}); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}))
defer server.Close()
cfg := testConfig(t)
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()
updates := make(chan tui.FlowUpdate, 100)
drainUpdates(t, updates)
_, err := pollForTokenWithUpdates(ctx, cfg, config, deviceAuth, updates)
if err == nil {
t.Fatal("expected error, got nil")
}
if err.Error() != expectedMsg {
t.Errorf("unexpected error message: %v", err)
}
}
func TestPollForToken_ExpiredToken(t *testing.T) {
pollForTokenErrorTest(t,
"expired_token",
"Device code has expired",
"device code expired, please restart the flow",
)
}
func TestPollForToken_AccessDenied(t *testing.T) {
pollForTokenErrorTest(t,
"access_denied",
"User denied the authorization request",
"user denied authorization",
)
}
func TestPollForToken_ContextTimeout(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)
if err := json.NewEncoder(w).Encode(map[string]string{
"error": "authorization_pending",
"error_description": "User has not yet authorized",
}); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}))
defer server.Close()
cfg := testConfig(t)
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(), 2*time.Second)
defer cancel()
updates := make(chan tui.FlowUpdate, 100)
drainUpdates(t, updates)
_, err := pollForTokenWithUpdates(ctx, cfg, config, deviceAuth, updates)
if err == nil {
t.Fatal("expected context timeout error, got nil")
}
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("unexpected grant_type: %s", r.FormValue("grant_type"))
}
if r.FormValue("device_code") != "test-device-code" {
t.Errorf("unexpected device_code: %s", r.FormValue("device_code"))
}
w.Header().Set("Content-Type", "application/json")
if err := json.NewEncoder(w).Encode(map[string]any{
"access_token": testAccessToken,
"refresh_token": "test-refresh-token",
"token_type": "Bearer",
"expires_in": 3600,
}); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}))
defer server.Close()
cfg := testConfig(t)
ctx := context.Background()
token, err := exchangeDeviceCode(ctx, cfg, server.URL, "test-client", "test-device-code")
if err != nil {
t.Fatalf("expected success, got error: %v", err)
}
if token.AccessToken != testAccessToken {
t.Errorf("access token = %q, want %q", token.AccessToken, testAccessToken)
}
if token.RefreshToken != "test-refresh-token" {
t.Errorf("refresh token = %q, want %q", token.RefreshToken, "test-refresh-token")
}
}