/
token_api_test.go
408 lines (354 loc) · 10.9 KB
/
token_api_test.go
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
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
package n26api
import (
"context"
"errors"
"fmt"
"testing"
"time"
"github.com/google/uuid"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/mock"
clock "go.nhat.io/clock/mock"
"github.com/nhatthm/n26api/pkg/auth"
"github.com/nhatthm/n26api/pkg/testkit"
authMock "github.com/nhatthm/n26api/pkg/testkit/auth"
)
func TestApiTokenProvider_GetToken(t *testing.T) {
t.Parallel()
username := "john.doe"
password := "jane.doe"
cred := Credentials(username, password)
deviceID := uuid.New()
storageKey := fmt.Sprintf("%s:%s", username, deviceID.String())
configureTimeout := func(_ *testing.T, p *apiTokenProvider) {
// Timeout: 175ms.
// Wait time: 50ms.
// Max calls: 3.
p.WithMFATimeout(175 * time.Millisecond).
WithMFAWait(50 * time.Millisecond)
}
testCases := []struct {
scenario string
mockServer testkit.ServerMocker
configure func(t *testing.T, p *apiTokenProvider)
expectedError string
}{
{
scenario: "could not get token from storage",
mockServer: testkit.MockEmptyServer(),
configure: func(t *testing.T, p *apiTokenProvider) { // nolint: thelper
s := authMock.MockTokenStorage(func(s *authMock.TokenStorage) {
s.On("Get", context.Background(), storageKey).
Return(auth.OAuthToken{}, errors.New("get token error"))
})(t)
p.WithStorage(s)
},
expectedError: "could not get token from storage: get token error",
},
{
scenario: "unexpected response",
mockServer: testkit.MockEmptyServer(
testkit.WithAuthPasswordLoginUnexpectedResponse(username, password, deviceID),
),
expectedError: "unexpected response: EOF",
},
{
scenario: "wrong credentials",
mockServer: testkit.MockEmptyServer(
testkit.WithAuthPasswordLoginFailureWrongCredentials(username, password, deviceID),
),
expectedError: "wrong credentials",
},
{
scenario: "too many login attempts",
mockServer: testkit.MockEmptyServer(
testkit.WithAuthPasswordLoginFailureTooManyAttempts(username, password, deviceID),
),
expectedError: "too many login attempts",
},
{
scenario: "internal error",
mockServer: testkit.MockEmptyServer(
testkit.WithAuthPasswordLoginFailure(username, password, deviceID),
),
expectedError: "unexpected response: unexpected response status: 500 Internal Server Error",
},
{
scenario: "mfa challenge with invalid token",
mockServer: testkit.MockEmptyServer(
testkit.WithAuthPasswordLoginSuccess(username, password, deviceID),
testkit.WithAuthMFAChallengeFailureInvalidToken(),
),
expectedError: "could not challenge mfa",
},
{
scenario: "mfa challenge failure",
mockServer: testkit.MockEmptyServer(
testkit.WithAuthPasswordLoginSuccess(username, password, deviceID),
testkit.WithAuthMFAChallengeFailure(),
),
expectedError: "failed to challenge mfa: unexpected response status: 500 Internal Server Error",
},
{
scenario: "mfa timeout",
mockServer: testkit.MockEmptyServer(
testkit.WithAuthPasswordLoginSuccess(username, password, deviceID),
testkit.WithAuthMFAChallengeSuccess(),
testkit.WithAuthConfirmLoginFailure(),
testkit.WithAuthConfirmLoginFailureInvalidToken(2),
),
configure: configureTimeout,
expectedError: "could not confirm login",
},
{
scenario: "could not set token",
mockServer: testkit.MockEmptyServer(
testkit.WithAuthPasswordLoginSuccess(username, password, deviceID),
testkit.WithAuthMFAChallengeSuccess(),
testkit.WithAuthConfirmLoginFailureInvalidToken(2),
testkit.WithAuthConfirmLoginSuccess(),
),
configure: func(t *testing.T, p *apiTokenProvider) { // nolint: thelper
configureTimeout(t, p)
s := authMock.MockTokenStorage(func(s *authMock.TokenStorage) {
s.On("Get", context.Background(), storageKey).
Return(auth.OAuthToken{}, nil)
s.On("Set", context.Background(), storageKey, mock.Anything).
Return(errors.New("set token error"))
})(t)
p.WithStorage(s)
},
expectedError: "could not persist token to storage: set token error",
},
{
scenario: "success",
mockServer: testkit.MockEmptyServer(
testkit.WithAuthPasswordLoginSuccess(username, password, deviceID),
testkit.WithAuthMFAChallengeSuccess(),
testkit.WithAuthConfirmLoginFailureInvalidToken(2),
testkit.WithAuthConfirmLoginSuccess(),
),
configure: configureTimeout,
},
}
for _, tc := range testCases {
tc := tc
t.Run(tc.scenario, func(t *testing.T) {
t.Parallel()
s := tc.mockServer(t)
p := newAPITokenProvider(cred, deviceID).
WithBaseURL(s.URL()).
WithTimeout(time.Second)
if tc.configure != nil {
tc.configure(t, p)
}
token, err := p.Token(context.Background())
if tc.expectedError == "" {
assert.Equal(t, s.AccessToken(), token)
assert.NoError(t, err)
} else {
assert.Empty(t, token)
assert.EqualError(t, err, tc.expectedError)
}
})
}
}
func TestApiTokenProvider_GetToken_MissingCredentials(t *testing.T) {
t.Parallel()
deviceID := uuid.New()
testCases := []struct {
scenario string
credentials CredentialsProvider
expectedError string
}{
{
scenario: "missing username",
credentials: Credentials("", "password"),
expectedError: "could not get token: missing username",
},
{
scenario: "missing password",
credentials: Credentials("username", ""),
expectedError: "could not get token: missing password",
},
}
for _, tc := range testCases {
tc := tc
t.Run(tc.scenario, func(t *testing.T) {
t.Parallel()
p := newAPITokenProvider(tc.credentials, deviceID)
token, err := p.Token(context.Background())
assert.Empty(t, token)
assert.EqualError(t, err, tc.expectedError)
})
}
}
func TestApiTokenProvider_GetTokenFromCache(t *testing.T) {
t.Parallel()
username := "john.doe"
password := "jane.doe"
cred := Credentials(username, password)
deviceID := uuid.New()
timestamp := time.Now()
s := testkit.MockEmptyServer(
testkit.WithAuthSuccess(username, password, deviceID),
)(t)
c := clock.Mock(func(c *clock.Clock) {
c.On("Now").Return(timestamp).Once()
// 2nd is after 4 minutes to check TTL.
c.On("Now").Return(timestamp.Add(4 * time.Minute)).Once()
})(t)
p := newAPITokenProvider(cred, deviceID).
WithBaseURL(s.URL()).
WithTimeout(time.Second).
WithMFAWait(time.Millisecond).
WithClock(c)
// 1st try.
token, err := p.Token(context.Background())
assert.Equal(t, s.AccessToken(), token)
assert.NotEmpty(t, string(token))
assert.NoError(t, err)
// 2nd try.
token, err = p.Token(context.Background())
assert.Equal(t, s.AccessToken(), token)
assert.NotEmpty(t, string(token))
assert.NoError(t, err)
}
func TestApiTokenProvider_RefreshToken(t *testing.T) {
t.Parallel()
username := "john.doe"
password := "jane.doe"
cred := Credentials(username, password)
deviceID := uuid.New()
timestamp := time.Now()
refreshTTL := time.Hour
storageKey := fmt.Sprintf("%s:%s", username, deviceID.String())
mockClock := clock.Mock(func(c *clock.Clock) {
// 1st step: Get token.
c.On("Now").Return(timestamp).Once()
// 2nd step: Refresh token.
c.On("Now").Return(timestamp.Add(refreshTTL - time.Minute)).Once()
})
testCases := []struct {
scenario string
mockServer testkit.ServerMocker
configureStep2 func(t *testing.T, p *apiTokenProvider, s *testkit.Server)
expectedError string
}{
{
scenario: "failed to refresh token",
mockServer: testkit.MockEmptyServer(
testkit.WithAuthSuccess(username, password, deviceID),
testkit.WithAuthRefreshTokenFailure(),
),
expectedError: "failed to refresh token: unexpected response status: 500 Internal Server Error",
},
{
scenario: "invalid token",
mockServer: testkit.MockEmptyServer(
testkit.WithAuthSuccess(username, password, deviceID),
testkit.WithAuthRefreshTokenFailureInvalidToken(),
testkit.WithAuthSuccess(username, password, deviceID),
),
},
{
scenario: "could not persist token",
mockServer: testkit.MockEmptyServer(
testkit.WithAuthSuccess(username, password, deviceID),
testkit.WithAuthRefreshTokenSuccess(),
),
configureStep2: func(t *testing.T, p *apiTokenProvider, svr *testkit.Server) { // nolint: thelper
s := authMock.MockTokenStorage(func(s *authMock.TokenStorage) {
s.On("Get", context.Background(), storageKey).
Return(
auth.OAuthToken{
AccessToken: svr.AccessToken(),
RefreshToken: svr.RefreshToken(),
ExpiresAt: timestamp.Add(time.Minute),
RefreshExpiresAt: timestamp.Add(time.Hour),
},
nil,
)
s.On("Set", context.Background(), storageKey, mock.Anything).
Return(errors.New("set token error"))
})(t)
p.WithStorage(s)
},
expectedError: "could not persist token to storage: set token error",
},
{
scenario: "success",
mockServer: testkit.MockEmptyServer(
testkit.WithAuthSuccess(username, password, deviceID),
testkit.WithAuthRefreshTokenSuccess(),
),
},
}
for _, tc := range testCases {
tc := tc
t.Run(tc.scenario, func(t *testing.T) {
t.Parallel()
s := tc.mockServer(t)
p := newAPITokenProvider(cred, deviceID).
WithBaseURL(s.URL()).
WithTimeout(time.Second).
WithMFAWait(time.Millisecond).
WithRefreshTTL(refreshTTL).
WithClock(mockClock(t))
// 1st step: get the token.
token1, err := p.Token(context.Background())
assert.Equal(t, s.AccessToken(), token1)
assert.NotEmpty(t, string(token1))
assert.NoError(t, err)
// 2nd step: refresh the token.
if tc.configureStep2 != nil {
tc.configureStep2(t, p, s)
}
token2, err := p.Token(context.Background())
if tc.expectedError == "" {
assert.NoError(t, err)
assert.Equal(t, s.AccessToken(), token2)
assert.NotEqual(t, token1, token2)
} else {
assert.Empty(t, string(token2))
assert.EqualError(t, err, tc.expectedError)
}
})
}
}
func TestApiTokenProvider_TokenExpired(t *testing.T) {
t.Parallel()
username := "john.doe"
password := "jane.doe"
cred := Credentials(username, password)
deviceID := uuid.New()
timestamp := time.Now()
refreshTTL := time.Hour
s := testkit.MockEmptyServer(
testkit.WithAuthSuccess(username, password, deviceID),
testkit.WithAuthSuccess(username, password, deviceID),
)(t)
c := clock.Mock(func(c *clock.Clock) {
// 1st step: Get token.
c.On("Now").Return(timestamp).Once()
// 2nd step: Refresh token.
c.On("Now").Return(timestamp.Add(refreshTTL + time.Minute)).Once()
})(t)
p := newAPITokenProvider(cred, deviceID).
WithBaseURL(s.URL()).
WithTimeout(time.Second).
WithMFAWait(time.Millisecond).
WithRefreshTTL(refreshTTL).
WithClock(c)
// 1st try.
token1, err := p.Token(context.Background())
assert.Equal(t, s.AccessToken(), token1)
assert.NotEmpty(t, string(token1))
assert.NoError(t, err)
// 2nd try.
token2, err := p.Token(context.Background())
assert.Equal(t, s.AccessToken(), token2)
assert.NotEqual(t, token1, token2)
assert.NotEmpty(t, string(token2))
assert.NoError(t, err)
}