Repository navigation
Expand file tree
/
Copy pathplugin_test.go
More file actions
590 lines (462 loc) · 18.6 KB
/
Copy pathplugin_test.go
File metadata and controls
590 lines (462 loc) · 18.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
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
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
package magiclink_test
import (
"bytes"
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"sync"
"testing"
"time"
log "github.com/xraph/go-utils/log"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/xraph/forge"
"github.com/xraph/authsome/account"
"github.com/xraph/authsome/id"
"github.com/xraph/authsome/plugin"
"github.com/xraph/authsome/plugins/magiclink"
"github.com/xraph/authsome/store"
"github.com/xraph/authsome/store/memory"
"github.com/xraph/authsome/user"
)
const testAppIDStr = "aapp_01jf0000000000000000000000"
// mockMailer captures sent magic links for test assertions.
type mockMailer struct {
mu sync.Mutex
sent []sentLink
errVal error
}
type sentLink struct {
Email string
Token string
}
func (m *mockMailer) SendMagicLink(_ context.Context, email, token string) error {
m.mu.Lock()
defer m.mu.Unlock()
m.sent = append(m.sent, sentLink{Email: email, Token: token})
return m.errVal
}
func newTestPlugin(t *testing.T) (*magiclink.Plugin, *memory.Store, *mockMailer) {
t.Helper()
mailer := &mockMailer{}
p := magiclink.New(magiclink.Config{
Mailer: mailer,
TokenTTL: 5 * time.Minute,
SessionTokenTTL: 1 * time.Hour,
SessionRefreshTTL: 24 * time.Hour,
})
s := memory.New()
p.SetStore(s)
p.SetAppID(testAppIDStr)
return p, s, mailer
}
func createTestUser(t *testing.T, s *memory.Store) *user.User {
t.Helper()
appID, err := id.ParseAppID(testAppIDStr)
require.NoError(t, err)
u := &user.User{
ID: id.NewUserID(),
AppID: appID,
Email: "test@example.com",
FirstName: "Test User",
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
}
err = s.CreateUser(context.Background(), u)
require.NoError(t, err)
return u
}
func jsonBody(t *testing.T, v any) *bytes.Buffer {
t.Helper()
b, err := json.Marshal(v)
require.NoError(t, err)
return bytes.NewBuffer(b)
}
// ──────────────────────────────────────────────────
// Unit tests
// ──────────────────────────────────────────────────
func TestPlugin_Name(t *testing.T) {
p := magiclink.New(magiclink.Config{})
assert.Equal(t, "magiclink", p.Name())
}
func TestPlugin_ImplementsInterfaces(t *testing.T) { //nolint:revive // test function signature
p := magiclink.New(magiclink.Config{})
// Plugin should implement base Plugin interface
var _ plugin.Plugin = p
// Plugin should implement RouteProvider
var _ plugin.RouteProvider = p
// Plugin should implement OnInit
var _ plugin.OnInit = p
}
func TestPlugin_DefaultConfig(t *testing.T) {
p := magiclink.New(magiclink.Config{})
// Should not panic with zero config — defaults are applied internally
assert.Equal(t, "magiclink", p.Name())
}
func TestPlugin_RegisterInRegistry(t *testing.T) {
reg := plugin.NewRegistry(log.NewNoopLogger())
p := magiclink.New(magiclink.Config{})
reg.Register(p)
assert.Len(t, reg.Plugins(), 1)
assert.Equal(t, "magiclink", reg.Plugins()[0].Name())
// Should be discoverable as a RouteProvider
assert.Len(t, reg.RouteProviders(), 1)
}
// ──────────────────────────────────────────────────
// Send endpoint tests
// ──────────────────────────────────────────────────
func TestHandleSend_Success(t *testing.T) {
p, s, mailer := newTestPlugin(t)
u := createTestUser(t, s) // registers test@example.com
mux := forge.NewRouter()
err := p.RegisterRoutes(mux)
require.NoError(t, err)
body := jsonBody(t, map[string]string{
"email": u.Email,
})
req := httptest.NewRequestWithContext(context.Background(), "POST", "/v1/magic-link/send", body)
req.Header.Set("Content-Type", "application/json")
rec := httptest.NewRecorder()
mux.ServeHTTP(rec, req)
assert.Equal(t, http.StatusOK, rec.Code)
var resp map[string]any
err = json.NewDecoder(rec.Body).Decode(&resp)
require.NoError(t, err)
assert.Equal(t, "magic link sent", resp["status"])
assert.InDelta(t, 300, resp["expires_in"], 0, "expires_in is the link lifetime in seconds")
assert.NotContains(t, resp, "code_length", "no code is sent unless the email code is on")
// Mailer should have been called for the registered user.
mailer.mu.Lock()
defer mailer.mu.Unlock()
assert.Len(t, mailer.sent, 1)
assert.Equal(t, u.Email, mailer.sent[0].Email)
assert.NotEmpty(t, mailer.sent[0].Token)
}
func TestHandleSend_MissingEmail(t *testing.T) {
p, _, _ := newTestPlugin(t)
mux := forge.NewRouter()
err := p.RegisterRoutes(mux)
require.NoError(t, err)
body := jsonBody(t, map[string]string{})
req := httptest.NewRequestWithContext(context.Background(), "POST", "/v1/magic-link/send", body)
req.Header.Set("Content-Type", "application/json")
rec := httptest.NewRecorder()
mux.ServeHTTP(rec, req)
assert.Equal(t, http.StatusBadRequest, rec.Code)
}
func TestHandleSend_InvalidJSON(t *testing.T) {
p, _, _ := newTestPlugin(t)
mux := forge.NewRouter()
err := p.RegisterRoutes(mux)
require.NoError(t, err)
req := httptest.NewRequestWithContext(context.Background(), "POST", "/v1/magic-link/send", bytes.NewBufferString("not json"))
req.Header.Set("Content-Type", "application/json")
rec := httptest.NewRecorder()
mux.ServeHTTP(rec, req)
assert.Equal(t, http.StatusBadRequest, rec.Code)
}
func TestHandleSend_MailerError(t *testing.T) {
p, s, mailer := newTestPlugin(t)
u := createTestUser(t, s)
mailer.errVal = assert.AnError
mux := forge.NewRouter()
err := p.RegisterRoutes(mux)
require.NoError(t, err)
body := jsonBody(t, map[string]string{
"email": u.Email,
})
req := httptest.NewRequestWithContext(context.Background(), "POST", "/v1/magic-link/send", body)
req.Header.Set("Content-Type", "application/json")
rec := httptest.NewRecorder()
mux.ServeHTTP(rec, req)
assert.Equal(t, http.StatusInternalServerError, rec.Code)
}
func TestHandleSend_WithExplicitAppID(t *testing.T) {
p, s, mailer := newTestPlugin(t)
u := createTestUser(t, s)
mux := forge.NewRouter()
err := p.RegisterRoutes(mux)
require.NoError(t, err)
body := jsonBody(t, map[string]string{
"email": u.Email,
"app_id": testAppIDStr,
})
req := httptest.NewRequestWithContext(context.Background(), "POST", "/v1/magic-link/send", body)
req.Header.Set("Content-Type", "application/json")
rec := httptest.NewRecorder()
mux.ServeHTTP(rec, req)
assert.Equal(t, http.StatusOK, rec.Code)
mailer.mu.Lock()
defer mailer.mu.Unlock()
assert.Len(t, mailer.sent, 1)
}
// ──────────────────────────────────────────────────
// Verify endpoint tests
// ──────────────────────────────────────────────────
func TestHandleVerify_Success(t *testing.T) {
p, s, mailer := newTestPlugin(t)
u := createTestUser(t, s)
mux := forge.NewRouter()
err := p.RegisterRoutes(mux)
require.NoError(t, err)
// Create a verification via the store directly
appID, err := id.ParseAppID(testAppIDStr)
require.NoError(t, err)
v, err := account.NewVerification(context.Background(), appID, u.ID, magiclink.VerificationTypeMagicLink, 5*time.Minute)
require.NoError(t, err)
err = s.CreateVerification(context.Background(), v)
require.NoError(t, err)
_ = mailer // not used in verify
body := jsonBody(t, map[string]string{
"token": v.Token,
})
req := httptest.NewRequestWithContext(context.Background(), "POST", "/v1/magic-link/verify", body)
req.Header.Set("Content-Type", "application/json")
rec := httptest.NewRecorder()
mux.ServeHTTP(rec, req)
assert.Equal(t, http.StatusOK, rec.Code)
var resp map[string]any
err = json.NewDecoder(rec.Body).Decode(&resp)
require.NoError(t, err)
assert.NotNil(t, resp["user"])
assert.NotEmpty(t, resp["session_token"])
assert.NotEmpty(t, resp["refresh_token"])
assert.NotEmpty(t, resp["expires_at"])
}
func TestHandleVerify_MissingToken(t *testing.T) {
p, _, _ := newTestPlugin(t)
mux := forge.NewRouter()
err := p.RegisterRoutes(mux)
require.NoError(t, err)
body := jsonBody(t, map[string]string{})
req := httptest.NewRequestWithContext(context.Background(), "POST", "/v1/magic-link/verify", body)
req.Header.Set("Content-Type", "application/json")
rec := httptest.NewRecorder()
mux.ServeHTTP(rec, req)
assert.Equal(t, http.StatusBadRequest, rec.Code)
}
func TestHandleVerify_InvalidToken(t *testing.T) {
p, _, _ := newTestPlugin(t)
mux := forge.NewRouter()
err := p.RegisterRoutes(mux)
require.NoError(t, err)
body := jsonBody(t, map[string]string{
"token": "nonexistent-token",
})
req := httptest.NewRequestWithContext(context.Background(), "POST", "/v1/magic-link/verify", body)
req.Header.Set("Content-Type", "application/json")
rec := httptest.NewRecorder()
mux.ServeHTTP(rec, req)
assert.Equal(t, http.StatusUnauthorized, rec.Code)
}
func TestHandleVerify_ExpiredToken(t *testing.T) {
p, s, _ := newTestPlugin(t)
u := createTestUser(t, s)
mux := forge.NewRouter()
err := p.RegisterRoutes(mux)
require.NoError(t, err)
appID, err := id.ParseAppID(testAppIDStr)
require.NoError(t, err)
// Create an already-expired verification
v, err := account.NewVerification(context.Background(), appID, u.ID, magiclink.VerificationTypeMagicLink, 1*time.Millisecond)
require.NoError(t, err)
// Force it to be expired
v.ExpiresAt = time.Now().Add(-1 * time.Hour)
err = s.CreateVerification(context.Background(), v)
require.NoError(t, err)
body := jsonBody(t, map[string]string{
"token": v.Token,
})
req := httptest.NewRequestWithContext(context.Background(), "POST", "/v1/magic-link/verify", body)
req.Header.Set("Content-Type", "application/json")
rec := httptest.NewRecorder()
mux.ServeHTTP(rec, req)
assert.Equal(t, http.StatusUnauthorized, rec.Code)
var resp map[string]any
err = json.NewDecoder(rec.Body).Decode(&resp)
require.NoError(t, err)
assert.Contains(t, resp["error"], "expired")
}
func TestHandleVerify_AlreadyConsumed(t *testing.T) {
p, s, _ := newTestPlugin(t)
u := createTestUser(t, s)
mux := forge.NewRouter()
err := p.RegisterRoutes(mux)
require.NoError(t, err)
appID, err := id.ParseAppID(testAppIDStr)
require.NoError(t, err)
v, err := account.NewVerification(context.Background(), appID, u.ID, magiclink.VerificationTypeMagicLink, 5*time.Minute)
require.NoError(t, err)
err = s.CreateVerification(context.Background(), v)
require.NoError(t, err)
// Consume it
err = s.ConsumeVerification(context.Background(), v.Token)
require.NoError(t, err)
body := jsonBody(t, map[string]string{
"token": v.Token,
})
req := httptest.NewRequestWithContext(context.Background(), "POST", "/v1/magic-link/verify", body)
req.Header.Set("Content-Type", "application/json")
rec := httptest.NewRecorder()
mux.ServeHTTP(rec, req)
assert.Equal(t, http.StatusUnauthorized, rec.Code)
var resp map[string]any
err = json.NewDecoder(rec.Body).Decode(&resp)
require.NoError(t, err)
assert.Contains(t, resp["error"], "already used")
}
func TestHandleVerify_InvalidJSON(t *testing.T) {
p, _, _ := newTestPlugin(t)
mux := forge.NewRouter()
err := p.RegisterRoutes(mux)
require.NoError(t, err)
req := httptest.NewRequestWithContext(context.Background(), "POST", "/v1/magic-link/verify", bytes.NewBufferString("not json"))
req.Header.Set("Content-Type", "application/json")
rec := httptest.NewRecorder()
mux.ServeHTTP(rec, req)
assert.Equal(t, http.StatusBadRequest, rec.Code)
}
// ──────────────────────────────────────────────────
// Full flow: send + verify
// ──────────────────────────────────────────────────
func TestFullFlow_SendThenVerify(t *testing.T) {
p, s, mailer := newTestPlugin(t)
u := createTestUser(t, s)
mux := forge.NewRouter()
err := p.RegisterRoutes(mux)
require.NoError(t, err)
appID, err := id.ParseAppID(testAppIDStr)
require.NoError(t, err)
// The send endpoint creates a verification with a random userID (since it doesn't
// look up the user by email). For a proper E2E, we create the verification
// associated with the real user directly.
v, err := account.NewVerification(context.Background(), appID, u.ID, magiclink.VerificationTypeMagicLink, 5*time.Minute)
require.NoError(t, err)
err = s.CreateVerification(context.Background(), v)
require.NoError(t, err)
_ = mailer
// Step 2: Verify
body := jsonBody(t, map[string]string{
"token": v.Token,
})
req := httptest.NewRequestWithContext(context.Background(), "POST", "/v1/magic-link/verify", body)
req.Header.Set("Content-Type", "application/json")
rec := httptest.NewRecorder()
mux.ServeHTTP(rec, req)
assert.Equal(t, http.StatusOK, rec.Code)
var resp map[string]any
err = json.NewDecoder(rec.Body).Decode(&resp)
require.NoError(t, err)
assert.NotNil(t, resp["user"])
assert.NotEmpty(t, resp["session_token"])
assert.NotEmpty(t, resp["refresh_token"])
// Session should be stored
sessions, err := s.ListUserSessions(context.Background(), u.ID)
require.NoError(t, err)
assert.Len(t, sessions, 1)
}
// ──────────────────────────────────────────────────
// MailerFunc adapter
// ──────────────────────────────────────────────────
func TestMailerFunc(t *testing.T) {
var called bool
var capturedEmail, capturedToken string
f := magiclink.MailerFunc(func(_ context.Context, email, token string) error {
called = true
capturedEmail = email
capturedToken = token
return nil
})
err := f.SendMagicLink(context.Background(), "test@example.com", "abc123")
require.NoError(t, err)
assert.True(t, called)
assert.Equal(t, "test@example.com", capturedEmail)
assert.Equal(t, "abc123", capturedToken)
}
// ──────────────────────────────────────────────────
// Verification-type confinement
// ──────────────────────────────────────────────────
// Verifications of every type live in one table and GetVerification matches on
// token alone, so /verify must reject anything that isn't a magic link.
// Email-verification records carry a 6-digit OTP in the same Token column: if
// this endpoint honoured them, posting {"token":"123456"} would walk a 10^6
// keyspace and mint a full session on a hit — with none of the attempt
// accounting the email-verify path applies.
func TestHandleVerify_RejectsEmailVerificationOTP(t *testing.T) {
p, s, _ := newTestPlugin(t)
u := createTestUser(t, s)
mux := forge.NewRouter()
require.NoError(t, p.RegisterRoutes(mux))
appID, err := id.ParseAppID(testAppIDStr)
require.NoError(t, err)
// A genuine, unexpired email-verification OTP for a real user.
otp, err := account.NewEmailVerificationCode(appID, u.ID, 5*time.Minute)
require.NoError(t, err)
require.NoError(t, s.CreateVerification(context.Background(), otp))
require.Len(t, otp.Token, 6, "email verification should store a 6-digit code")
req := httptest.NewRequestWithContext(context.Background(), "POST",
"/v1/magic-link/verify", jsonBody(t, map[string]string{"token": otp.Token}))
req.Header.Set("Content-Type", "application/json")
rec := httptest.NewRecorder()
mux.ServeHTTP(rec, req)
assert.Equal(t, http.StatusUnauthorized, rec.Code,
"an email-verification OTP must not be redeemable as a magic link")
assert.NotContains(t, rec.Body.String(), "session_token",
"no session may be issued for a non-magic-link token")
// The OTP must survive so the real email-verify flow can still use it.
stored, err := s.GetVerification(context.Background(), otp.Token)
require.NoError(t, err)
assert.False(t, stored.Consumed, "rejected token must not be consumed")
}
// Guessing a 6-digit value must never produce a session, whether or not it
// happens to collide with a live verification of another type.
func TestHandleVerify_SixDigitGuessesNeverAuthenticate(t *testing.T) {
p, s, _ := newTestPlugin(t)
u := createTestUser(t, s)
mux := forge.NewRouter()
require.NoError(t, p.RegisterRoutes(mux))
appID, err := id.ParseAppID(testAppIDStr)
require.NoError(t, err)
otp, err := account.NewEmailVerificationCode(appID, u.ID, 5*time.Minute)
require.NoError(t, err)
require.NoError(t, s.CreateVerification(context.Background(), otp))
// Include the real code among the guesses — the attacker "wins" the
// lottery and must still be refused.
for _, guess := range []string{"000000", "123456", "999999", otp.Token} {
req := httptest.NewRequestWithContext(context.Background(), "POST",
"/v1/magic-link/verify", jsonBody(t, map[string]string{"token": guess}))
req.Header.Set("Content-Type", "application/json")
rec := httptest.NewRecorder()
mux.ServeHTTP(rec, req)
assert.Equal(t, http.StatusUnauthorized, rec.Code, "guess %q", guess)
}
}
// The Consumed check on the read and the write that sets it are two steps. The
// store consumes only if still unconsumed, so a second redemption is refused
// even if it read the record before the first one wrote — one link, one
// session.
func TestHandleVerify_ConsumeIsSingleUse(t *testing.T) {
p, s, _ := newTestPlugin(t)
u := createTestUser(t, s)
mux := forge.NewRouter()
require.NoError(t, p.RegisterRoutes(mux))
appID, err := id.ParseAppID(testAppIDStr)
require.NoError(t, err)
v, err := account.NewVerification(context.Background(), appID, u.ID,
magiclink.VerificationTypeMagicLink, 5*time.Minute)
require.NoError(t, err)
require.NoError(t, s.CreateVerification(context.Background(), v))
// The store must report a replay rather than silently succeeding.
require.NoError(t, s.ConsumeVerification(context.Background(), v.Token))
assert.ErrorIs(t, s.ConsumeVerification(context.Background(), v.Token), store.ErrNotFound,
"a second consume must be distinguishable from the first")
// And the endpoint must surface it as a refusal, not a 500.
req := httptest.NewRequestWithContext(context.Background(), "POST",
"/v1/magic-link/verify", jsonBody(t, map[string]string{"token": v.Token}))
req.Header.Set("Content-Type", "application/json")
rec := httptest.NewRecorder()
mux.ServeHTTP(rec, req)
assert.Equal(t, http.StatusUnauthorized, rec.Code, "body: %s", rec.Body.String())
assert.NotContains(t, rec.Body.String(), "session_token")
}