-
Notifications
You must be signed in to change notification settings - Fork 209
/
recover_test.go
523 lines (427 loc) · 12.8 KB
/
recover_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
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
package recover
import (
"bytes"
"crypto/sha512"
"encoding/base64"
"errors"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/volatiletech/authboss/v3"
"github.com/volatiletech/authboss/v3/mocks"
)
const (
testSelector = `rnaGE8TDilrINHPxq/2xNU1FUTzsUSX8FvN5YzooyyWKk88fw1DjjbKBRGFtGew9OeZ+xeCC4mslfvQQMYspIg==`
testVerifier = `W1Mz30QhavVM4d8jKaFtxGBfb4GX+fOn7V0Pc1WeftgtyOtY5OX7sY9gIeY5CIY4n8LvfWy14W7/6rs2KO9pgA==`
testToken = `w5OZ51E61Q6wsJOVr9o7KmyepP7Od5VBHQ1ADDUBkiGGMjKfnMFPjtvNpLjLKJqffw72KWZzNLj0Cs8wqywdEQ==`
)
func TestInit(t *testing.T) {
t.Parallel()
ab := authboss.New()
router := &mocks.Router{}
renderer := &mocks.Renderer{}
mailRenderer := &mocks.Renderer{}
errHandler := &mocks.ErrorHandler{}
ab.Config.Core.Router = router
ab.Config.Core.ViewRenderer = renderer
ab.Config.Core.MailRenderer = mailRenderer
ab.Config.Core.ErrorHandler = errHandler
r := &Recover{}
if err := r.Init(ab); err != nil {
t.Fatal(err)
}
if err := renderer.HasLoadedViews(PageRecoverStart, PageRecoverEnd); err != nil {
t.Error(err)
}
if err := mailRenderer.HasLoadedViews(EmailRecoverHTML, EmailRecoverTxt); err != nil {
t.Error(err)
}
if err := router.HasGets("/recover", "/recover/end"); err != nil {
t.Error(err)
}
if err := router.HasPosts("/recover", "/recover/end"); err != nil {
t.Error(err)
}
}
type testHarness struct {
recover *Recover
ab *authboss.Authboss
bodyReader *mocks.BodyReader
mailer *mocks.Emailer
redirector *mocks.Redirector
renderer *mocks.Renderer
responder *mocks.Responder
session *mocks.ClientStateRW
storer *mocks.ServerStorer
}
func testSetup() *testHarness {
harness := &testHarness{}
harness.ab = authboss.New()
harness.bodyReader = &mocks.BodyReader{}
harness.mailer = &mocks.Emailer{}
harness.redirector = &mocks.Redirector{}
harness.renderer = &mocks.Renderer{}
harness.responder = &mocks.Responder{}
harness.session = mocks.NewClientRW()
harness.storer = mocks.NewServerStorer()
harness.ab.Paths.RecoverOK = "/recover/ok"
harness.ab.Modules.MailNoGoroutine = true
harness.ab.Config.Core.BodyReader = harness.bodyReader
harness.ab.Config.Core.Logger = mocks.Logger{}
harness.ab.Config.Core.Hasher = mocks.Hasher{}
harness.ab.Config.Core.Mailer = harness.mailer
harness.ab.Config.Core.Redirector = harness.redirector
harness.ab.Config.Core.MailRenderer = harness.renderer
harness.ab.Config.Core.Responder = harness.responder
harness.ab.Config.Storage.SessionState = harness.session
harness.ab.Config.Storage.Server = harness.storer
harness.recover = &Recover{harness.ab}
return harness
}
func TestStartGet(t *testing.T) {
t.Parallel()
h := testSetup()
r := mocks.Request("GET")
w := httptest.NewRecorder()
if err := h.recover.StartGet(w, r); err != nil {
t.Error(err)
}
if w.Code != http.StatusOK {
t.Error("code was wrong:", w.Code)
}
if h.responder.Page != PageRecoverStart {
t.Error("page was wrong:", h.responder.Page)
}
if h.responder.Data != nil {
t.Error("expected no data:", h.responder.Data)
}
}
func TestStartPostSuccess(t *testing.T) {
t.Parallel()
h := testSetup()
h.bodyReader.Return = &mocks.Values{
PID: "test@test.com",
}
h.storer.Users["test@test.com"] = &mocks.User{
Email: "test@test.com",
Password: "i can't recall, doesn't seem like something bcrypted though",
}
r := mocks.Request("GET")
w := httptest.NewRecorder()
if err := h.recover.StartPost(w, r); err != nil {
t.Error(err)
}
if w.Code != http.StatusTemporaryRedirect {
t.Error("code was wrong:", w.Code)
}
if h.redirector.Options.RedirectPath != h.ab.Config.Paths.RecoverOK {
t.Error("page was wrong:", h.responder.Page)
}
if len(h.redirector.Options.Success) == 0 {
t.Error("expected a nice success message")
}
if h.mailer.Email.To[0] != "test@test.com" {
t.Error("e-mail to address is wrong:", h.mailer.Email.To)
}
if !strings.HasSuffix(h.mailer.Email.Subject, "Password Reset") {
t.Error("e-mail subject line is wrong:", h.mailer.Email.Subject)
}
if len(h.renderer.Data[DataRecoverURL].(string)) == 0 {
t.Errorf("the renderer's url in data was missing: %#v", h.renderer.Data)
}
}
func TestStartPostFailure(t *testing.T) {
t.Parallel()
h := testSetup()
h.bodyReader.Return = &mocks.Values{
PID: "test@test.com",
}
r := mocks.Request("GET")
w := httptest.NewRecorder()
if err := h.recover.StartPost(w, r); err != nil {
t.Error(err)
}
if w.Code != http.StatusTemporaryRedirect {
t.Error("code was wrong:", w.Code)
}
if h.redirector.Options.RedirectPath != h.ab.Config.Paths.RecoverOK {
t.Error("page was wrong:", h.responder.Page)
}
if len(h.redirector.Options.Success) == 0 {
t.Error("expected a nice success message")
}
if len(h.mailer.Email.To) != 0 {
t.Error("should not have sent an e-mail out!")
}
}
func TestEndGet(t *testing.T) {
t.Parallel()
h := testSetup()
h.bodyReader.Return = &mocks.Values{
Token: "abcd",
}
r := mocks.Request("GET")
w := httptest.NewRecorder()
if err := h.recover.EndGet(w, r); err != nil {
t.Error(err)
}
if w.Code != http.StatusOK {
t.Error("code was wrong:", w.Code)
}
if h.responder.Page != PageRecoverEnd {
t.Error("page was wrong:", h.responder.Page)
}
if h.responder.Data[DataRecoverToken].(string) != "abcd" {
t.Errorf("recovery token is wrong: %#v", h.responder.Data)
}
}
func TestEndPostSuccess(t *testing.T) {
t.Parallel()
h := testSetup()
h.bodyReader.Return = &mocks.Values{
Token: testToken,
}
h.storer.Users["test@test.com"] = &mocks.User{
Email: "test@test.com",
Password: "to-overwrite",
RecoverSelector: testSelector,
RecoverVerifier: testVerifier,
RecoverTokenExpiry: time.Now().UTC().AddDate(0, 0, 1),
}
r := mocks.Request("POST")
w := httptest.NewRecorder()
if err := h.recover.EndPost(w, r); err != nil {
t.Error(err)
}
if w.Code != http.StatusTemporaryRedirect {
t.Error("code was wrong:", w.Code)
}
if p := h.redirector.Options.RedirectPath; p != h.ab.Paths.RecoverOK {
t.Error("path was wrong:", p)
}
if len(h.session.ClientValues[authboss.SessionKey]) != 0 {
t.Error("should not have logged in the user")
}
if !strings.Contains(h.redirector.Options.Success, "updated password") {
t.Error("should talk about recovering the password")
}
if strings.Contains(h.redirector.Options.Success, "logged in") {
t.Error("should not talk about logging in")
}
}
func TestEndPostSuccessLogin(t *testing.T) {
t.Parallel()
h := testSetup()
h.ab.Config.Modules.RecoverLoginAfterRecovery = true
h.bodyReader.Return = &mocks.Values{
Token: testToken,
}
h.storer.Users["test@test.com"] = &mocks.User{
Email: "test@test.com",
Password: "to-overwrite",
RecoverSelector: testSelector,
RecoverVerifier: testVerifier,
RecoverTokenExpiry: time.Now().UTC().AddDate(0, 0, 1),
}
callbacks := 0
h.ab.Events.After(authboss.EventRecoverEnd, func(w http.ResponseWriter, r *http.Request, handled bool) (bool, error) {
if callbacks != 0 {
t.Error("after recover end was not called 1st")
}
callbacks += 1
return false, nil
})
h.ab.Events.Before(authboss.EventAuth, func(w http.ResponseWriter, r *http.Request, handled bool) (bool, error) {
if callbacks != 1 {
t.Error("before auth was not called 2nd")
}
callbacks += 1
return false, nil
})
h.ab.Events.Before(authboss.EventAuthHijack, func(w http.ResponseWriter, r *http.Request, handled bool) (bool, error) {
if callbacks != 2 {
t.Error("before auth hijack was not called 3rd")
}
callbacks += 1
return false, nil
})
h.ab.Events.After(authboss.EventAuth, func(w http.ResponseWriter, r *http.Request, handled bool) (bool, error) {
if callbacks != 3 {
t.Error("after auth was not called 4th")
}
callbacks += 1
return false, nil
})
r := mocks.Request("POST")
w := httptest.NewRecorder()
if err := h.recover.EndPost(h.ab.NewResponse(w), r); err != nil {
t.Error(err)
}
if w.Code != http.StatusTemporaryRedirect {
t.Error("code was wrong:", w.Code)
}
if p := h.redirector.Options.RedirectPath; p != h.ab.Paths.RecoverOK {
t.Error("path was wrong:", p)
}
if len(h.session.ClientValues[authboss.SessionKey]) == 0 {
t.Error("it should have logged in the user")
}
if !strings.Contains(h.redirector.Options.Success, "logged in") {
t.Error("should talk about logging in")
}
if callbacks != 4 {
t.Error("all 4 callbacks were not called")
}
}
func TestEndPostValidationFailure(t *testing.T) {
t.Parallel()
h := testSetup()
h.bodyReader.Return = &mocks.Values{
Errors: []error{errors.New("password is not sufficiently complex")},
}
h.storer.Users["test@test.com"] = &mocks.User{
Email: "test@test.com",
Password: "to-overwrite",
RecoverSelector: testSelector,
RecoverVerifier: testVerifier,
RecoverTokenExpiry: time.Now().UTC().AddDate(0, 0, 1),
}
r := mocks.Request("POST")
w := httptest.NewRecorder()
if err := h.recover.EndPost(w, r); err != nil {
t.Error(err)
}
if w.Code != http.StatusOK {
t.Error("code was wrong:", w.Code)
}
if h.responder.Page != PageRecoverEnd {
t.Error("rendered the wrong page")
}
if m, ok := h.responder.Data[authboss.DataValidation].(map[string][]string); !ok {
t.Error("expected validation errors")
} else if m[""][0] != "password is not sufficiently complex" {
t.Error("error message data was not correct:", m[""])
}
if len(h.session.ClientValues[authboss.SessionKey]) != 0 {
t.Error("should not have logged in the user")
}
}
func TestEndPostInvalidBase64(t *testing.T) {
t.Parallel()
h := testSetup()
h.bodyReader.Return = &mocks.Values{
Token: "a",
}
r := mocks.Request("GET")
w := httptest.NewRecorder()
if err := h.recover.EndPost(w, r); err != nil {
t.Error(err)
}
invalidCheck(t, h, w)
}
func TestEndPostExpiredToken(t *testing.T) {
t.Parallel()
h := testSetup()
h.bodyReader.Return = &mocks.Values{
Token: testToken,
}
h.storer.Users["test@test.com"] = &mocks.User{
Email: "test@test.com",
Password: "to-overwrite",
RecoverSelector: testSelector,
RecoverVerifier: testVerifier,
RecoverTokenExpiry: time.Now().UTC().AddDate(0, 0, -1),
}
r := mocks.Request("GET")
w := httptest.NewRecorder()
if err := h.recover.EndPost(w, r); err != nil {
t.Error(err)
}
invalidCheck(t, h, w)
}
func TestEndPostUserNotExist(t *testing.T) {
t.Parallel()
h := testSetup()
h.bodyReader.Return = &mocks.Values{
Token: testToken,
}
r := mocks.Request("GET")
w := httptest.NewRecorder()
if err := h.recover.EndPost(w, r); err != nil {
t.Error(err)
}
invalidCheck(t, h, w)
}
func TestMailURL(t *testing.T) {
t.Parallel()
h := testSetup()
h.ab.Config.Paths.RootURL = "https://api.test.com:6343"
h.ab.Config.Paths.Mount = "/v1/auth"
want := "https://api.test.com:6343/v1/auth/recover/end?token=abc"
if got := h.recover.mailURL("abc"); got != want {
t.Error("want:", want, "got:", got)
}
h.ab.Config.Mail.RootURL = "https://test.com:3333/testauth"
want = "https://test.com:3333/testauth/recover/end?token=abc"
if got := h.recover.mailURL("abc"); got != want {
t.Error("want:", want, "got:", got)
}
}
func invalidCheck(t *testing.T, h *testHarness, w *httptest.ResponseRecorder) {
t.Helper()
if w.Code != http.StatusOK {
t.Error("code was wrong:", w.Code)
}
if h.responder.Page != PageRecoverEnd {
t.Error("page was wrong:", h.responder.Page)
}
if h.responder.Data[authboss.DataValidation].(map[string][]string)[""][0] != "recovery token is invalid" {
t.Error("expected a vague error to mislead")
}
}
func TestGenerateRecoverCreds(t *testing.T) {
t.Parallel()
credsGenerator := authboss.NewSha512TokenGenerator()
selector, verifier, token, err := credsGenerator.GenerateToken()
if err != nil {
t.Error(err)
}
recoverTokenSplit := credsGenerator.TokenSize() / 2
if verifier == selector {
t.Error("the verifier and selector should be different")
}
// base64 length: n = 64; 4*(64/3) = 85.3; round to nearest 4: 88
if len(verifier) != 88 {
t.Errorf("verifier length was wrong (%d): %s", len(verifier), verifier)
}
// base64 length: n = 64; 4*(64/3) = 85.3; round to nearest 4: 88
if len(selector) != 88 {
t.Errorf("selector length was wrong (%d): %s", len(selector), selector)
}
// base64 length: n = 64; 4*(64/3) = 85.33; round to nearest 4: 88
if len(token) != 88 {
t.Errorf("token length was wrong (%d): %s", len(token), token)
}
rawToken, err := base64.URLEncoding.DecodeString(token)
if err != nil {
t.Error(err)
}
rawSelector, err := base64.StdEncoding.DecodeString(selector)
if err != nil {
t.Error(err)
}
rawVerifier, err := base64.StdEncoding.DecodeString(verifier)
if err != nil {
t.Error(err)
}
checkSelector := sha512.Sum512(rawToken[:recoverTokenSplit])
if 0 != bytes.Compare(checkSelector[:], rawSelector) {
t.Error("expected selector to match")
}
checkVerifier := sha512.Sum512(rawToken[recoverTokenSplit:])
if 0 != bytes.Compare(checkVerifier[:], rawVerifier) {
t.Error("expected verifier to match")
}
}