-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathservice_session_test.go
More file actions
564 lines (525 loc) · 15.6 KB
/
Copy pathservice_session_test.go
File metadata and controls
564 lines (525 loc) · 15.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
package theauth_test
import (
"context"
"sync"
"testing"
"time"
"github.com/glincker/theauth-go"
"github.com/glincker/theauth-go/internal/ulid"
"github.com/glincker/theauth-go/storage/memory"
)
func newTestAuth(t *testing.T) (*theauth.TheAuth, *memory.Store) {
t.Helper()
store := memory.New()
a, err := theauth.New(theauth.Config{
Storage: store,
BaseURL: "http://localhost",
SessionTTL: time.Hour,
MagicLinkTTL: 15 * time.Minute,
// Test defaults: keep production-realistic ratios but raise headroom
// so multi-step e2e flows don't trip the per-email limit while still
// letting dedicated tests assert the 429 boundary.
RateLimitPerIP: 100,
RateLimitPerEmail: 100,
})
if err != nil {
t.Fatal(err)
}
return a, store
}
func TestIssueAndValidateSession(t *testing.T) {
a, store := newTestAuth(t)
ctx := context.Background()
user, _ := store.CreateUser(ctx, theauth.User{ID: ulid.New(), Email: "i@v.com", CreatedAt: time.Now(), UpdatedAt: time.Now()})
token, sess, err := theauth.IssueSessionForTest(a, ctx, user, "ua", "")
if err != nil {
t.Fatal(err)
}
if token == "" || sess.ID.String() == "" {
t.Fatal("issueSession returned empty")
}
gotSess, gotUser, err := theauth.ValidateSessionForTest(a, ctx, token)
if err != nil {
t.Fatal(err)
}
if gotSess.ID != sess.ID {
t.Fatal("session ID mismatch")
}
if gotUser.Email != "i@v.com" {
t.Fatal("user email mismatch")
}
}
func TestValidateSessionInvalidToken(t *testing.T) {
a, _ := newTestAuth(t)
_, _, err := theauth.ValidateSessionForTest(a, context.Background(), "bogus")
if err == nil {
t.Fatal("expected error for bogus token")
}
}
func TestValidateSessionRevoked(t *testing.T) {
a, store := newTestAuth(t)
ctx := context.Background()
user, _ := store.CreateUser(ctx, theauth.User{ID: ulid.New(), Email: "r@r.com", CreatedAt: time.Now(), UpdatedAt: time.Now()})
token, sess, _ := theauth.IssueSessionForTest(a, ctx, user, "", "")
_ = store.RevokeSession(ctx, sess.ID)
_, _, err := theauth.ValidateSessionForTest(a, ctx, token)
if err == nil {
t.Fatal("expected error for revoked session")
}
}
// ---------- race tests (originally service_session_race_test.go) ----------
func newRaceAuth(t *testing.T) (*theauth.TheAuth, theauth.Storage) {
t.Helper()
store := memory.New()
a, err := theauth.New(theauth.Config{
Storage: store,
BaseURL: "http://localhost",
SecureCookie: false,
})
if err != nil {
t.Fatal(err)
}
t.Cleanup(a.Close)
return a, store
}
// TestSessionCreationRaceSameUser issues two concurrent session creations
// for the same user and asserts both succeed with distinct IDs. The
// in-memory adapter must not deadlock and must not produce a primary key
// collision.
func TestSessionCreationRaceSameUser(t *testing.T) {
t.Parallel()
a, store := newRaceAuth(t)
ctx := context.Background()
user := theauth.User{
ID: ulid.New(),
Email: "race@example.com",
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
}
if _, err := store.CreateUser(ctx, user); err != nil {
t.Fatal(err)
}
var (
t1, t2 string
s1, s2 theauth.Session
e1, e2 error
wg sync.WaitGroup
)
wg.Add(2)
go func() {
defer wg.Done()
t1, s1, e1 = theauth.IssueSessionForTest(a, ctx, user, "ua", "ip")
}()
go func() {
defer wg.Done()
t2, s2, e2 = theauth.IssueSessionForTest(a, ctx, user, "ua", "ip")
}()
wg.Wait()
if e1 != nil || e2 != nil {
t.Fatalf("issueSession errors: e1=%v e2=%v", e1, e2)
}
if t1 == "" || t2 == "" {
t.Fatalf("blank tokens: t1=%q t2=%q", t1, t2)
}
if t1 == t2 {
t.Fatalf("tokens collided: %q", t1)
}
if s1.ID == s2.ID {
t.Fatalf("session IDs collided: %s", s1.ID)
}
}
// TestSessionLookupUnderWrites runs concurrent session creators against
// concurrent lookups. Lookups must never observe a zero-value or
// partially-initialized session struct.
func TestSessionLookupUnderWrites(t *testing.T) {
t.Parallel()
a, store := newRaceAuth(t)
ctx := context.Background()
const users = 100
created := make([]theauth.User, users)
tokens := make([]string, users)
for i := 0; i < users; i++ {
u := theauth.User{
ID: ulid.New(),
Email: "u" + ulid.New().String() + "@example.com",
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
}
created[i], _ = store.CreateUser(ctx, u)
tok, _, err := theauth.IssueSessionForTest(a, ctx, created[i], "", "")
if err != nil {
t.Fatal(err)
}
tokens[i] = tok
}
var wg sync.WaitGroup
stop := make(chan struct{})
// Writers: keep issuing new sessions.
for i := 0; i < 100; i++ {
wg.Add(1)
go func(i int) {
defer wg.Done()
for {
select {
case <-stop:
return
default:
_, _, _ = theauth.IssueSessionForTest(a, ctx, created[i%users], "ua", "ip")
}
}
}(i)
}
// Readers: validate the known tokens; must always find a fully
// populated session.
for i := 0; i < 100; i++ {
wg.Add(1)
go func(i int) {
defer wg.Done()
for j := 0; j < 50; j++ {
sess, user, err := theauth.ValidateSessionForTest(a, ctx, tokens[i%users])
if err != nil {
t.Errorf("validate err: %v", err)
return
}
if sess == nil || user == nil {
t.Errorf("nil sess or user")
return
}
if sess.UserID != user.ID {
t.Errorf("session userID mismatch")
return
}
}
}(i)
}
// Let the workers churn briefly then stop.
time.Sleep(50 * time.Millisecond)
close(stop)
wg.Wait()
}
// ---------- magic-link tests (originally service_magiclink_test.go) ----------
func TestRequestMagicLinkCreatesAndEmails(t *testing.T) {
a, _ := newTestAuth(t)
ctx := context.Background()
if _, err := theauth.RequestMagicLinkForTest(a, ctx, "x@y.com"); err != nil {
t.Fatal(err)
}
}
func TestConsumeMagicLinkCreatesUserAndSession(t *testing.T) {
a, _ := newTestAuth(t)
ctx := context.Background()
token, err := theauth.RequestMagicLinkForTest(a, ctx, "consume@y.com")
if err != nil {
t.Fatal(err)
}
sessToken, user, err := theauth.ConsumeMagicLinkForTest(a, ctx, token)
if err != nil {
t.Fatal(err)
}
if sessToken == "" {
t.Fatal("expected session token")
}
if user.Email != "consume@y.com" {
t.Fatalf("got user email %q", user.Email)
}
}
func TestConsumeMagicLinkTwiceFails(t *testing.T) {
a, _ := newTestAuth(t)
ctx := context.Background()
token, _ := theauth.RequestMagicLinkForTest(a, ctx, "twice@y.com")
if _, _, err := theauth.ConsumeMagicLinkForTest(a, ctx, token); err != nil {
t.Fatal(err)
}
if _, _, err := theauth.ConsumeMagicLinkForTest(a, ctx, token); err == nil {
t.Fatal("expected error on second consume")
}
}
// TestLifecycleHooks_PasswordSignupAndSignin proves the v2.5 LifecycleHooks
// surface fires OnSignup once at password signup and OnSignin once at the
// subsequent signin. Covers issue #76. Uses the HTTP surface end-to-end so
// the assertion exercises the wiring at the same boundary consumers do.
func TestLifecycleHooks_PasswordSignupAndSignin(t *testing.T) {
store := memory.New()
var (
mu sync.Mutex
signupCount int
signinCount int
signupMethod theauth.SignupMethod
signupUserID theauth.ULID
signinUserID theauth.ULID
seenSessionID theauth.ULID
)
a, err := theauth.New(theauth.Config{
Storage: store,
BaseURL: "http://localhost",
SessionTTL: time.Hour,
MagicLinkTTL: 15 * time.Minute,
RateLimitPerIP: 100,
RateLimitPerEmail: 100,
LifecycleHooks: &theauth.LifecycleHooks{
OnSignup: func(ctx context.Context, user *theauth.User, method theauth.SignupMethod) error {
mu.Lock()
signupCount++
signupMethod = method
signupUserID = user.ID
mu.Unlock()
return nil
},
OnSignin: func(ctx context.Context, user *theauth.User, sess *theauth.Session) error {
mu.Lock()
signinCount++
signinUserID = user.ID
seenSessionID = sess.ID
mu.Unlock()
return nil
},
},
})
if err != nil {
t.Fatal(err)
}
ctx := context.Background()
user, _, err := theauth.SignupWithPasswordForTest(a, ctx, "hooks@y.com", "correct-horse-battery-staple")
if err != nil {
t.Fatalf("signup: %v", err)
}
mu.Lock()
if signupCount != 1 || signinCount != 0 {
t.Fatalf("after signup: want signup=1 signin=0; got signup=%d signin=%d", signupCount, signinCount)
}
if signupMethod != theauth.SignupMethodPassword {
t.Fatalf("OnSignup method: want %q; got %q", theauth.SignupMethodPassword, signupMethod)
}
if signupUserID != user.ID {
t.Fatalf("OnSignup user id mismatch: want %v; got %v", user.ID, signupUserID)
}
mu.Unlock()
if _, _, err := theauth.SigninWithPasswordForTest(a, ctx, "hooks@y.com", "correct-horse-battery-staple", "ua", ""); err != nil {
t.Fatalf("signin: %v", err)
}
mu.Lock()
defer mu.Unlock()
if signinCount != 1 {
t.Fatalf("after signin: want signin=1; got %d", signinCount)
}
if signinUserID != user.ID {
t.Fatalf("OnSignin user id mismatch: want %v; got %v", user.ID, signinUserID)
}
if seenSessionID == (theauth.ULID{}) {
t.Fatal("OnSignin session was zero ULID")
}
}
// TestLifecycleHooks_PanicRecovery proves a panicking hook does not bring
// down the request that triggered it. Validates the runLifecycleHook
// recovery semantic documented on LifecycleHooks.
func TestLifecycleHooks_PanicRecovery(t *testing.T) {
store := memory.New()
a, err := theauth.New(theauth.Config{
Storage: store,
BaseURL: "http://localhost",
SessionTTL: time.Hour,
MagicLinkTTL: 15 * time.Minute,
RateLimitPerIP: 100,
RateLimitPerEmail: 100,
LifecycleHooks: &theauth.LifecycleHooks{
OnSignup: func(ctx context.Context, user *theauth.User, method theauth.SignupMethod) error {
panic("intentional test panic")
},
},
})
if err != nil {
t.Fatal(err)
}
if _, _, err := theauth.SignupWithPasswordForTest(a, context.Background(), "panic@y.com", "correct-horse-battery-staple"); err != nil {
t.Fatalf("signup must succeed despite hook panic; got %v", err)
}
}
// TestLifecycleHooks_MagicLinkConsumeFiresHooks proves OnSignup fires once
// on the first magic-link consume (user just created) and only OnSignin
// fires on subsequent consumes for the same user. Covers issue #76 magic-
// link wiring.
func TestLifecycleHooks_MagicLinkConsumeFiresHooks(t *testing.T) {
store := memory.New()
var (
mu sync.Mutex
signupCount int
signinCount int
lastMethod theauth.SignupMethod
)
a, err := theauth.New(theauth.Config{
Storage: store,
BaseURL: "http://localhost",
SessionTTL: time.Hour,
MagicLinkTTL: 15 * time.Minute,
RateLimitPerIP: 100,
RateLimitPerEmail: 100,
LifecycleHooks: &theauth.LifecycleHooks{
OnSignup: func(ctx context.Context, u *theauth.User, m theauth.SignupMethod) error {
mu.Lock()
signupCount++
lastMethod = m
mu.Unlock()
return nil
},
OnSignin: func(ctx context.Context, u *theauth.User, s *theauth.Session) error {
mu.Lock()
signinCount++
mu.Unlock()
return nil
},
},
})
if err != nil {
t.Fatal(err)
}
ctx := context.Background()
// First consume: brand-new user. Expect OnSignup + OnSignin.
tok1, err := theauth.RequestMagicLinkForTest(a, ctx, "ml@y.com")
if err != nil {
t.Fatal(err)
}
if _, _, err := theauth.ConsumeMagicLinkForTest(a, ctx, tok1); err != nil {
t.Fatal(err)
}
mu.Lock()
if signupCount != 1 || signinCount != 1 {
t.Fatalf("first consume: want signup=1 signin=1; got signup=%d signin=%d", signupCount, signinCount)
}
if lastMethod != theauth.SignupMethodMagicLink {
t.Fatalf("OnSignup method on magic-link consume: want %q; got %q", theauth.SignupMethodMagicLink, lastMethod)
}
mu.Unlock()
// Second consume: existing user. Expect only OnSignin.
tok2, err := theauth.RequestMagicLinkForTest(a, ctx, "ml@y.com")
if err != nil {
t.Fatal(err)
}
if _, _, err := theauth.ConsumeMagicLinkForTest(a, ctx, tok2); err != nil {
t.Fatal(err)
}
mu.Lock()
defer mu.Unlock()
if signupCount != 1 {
t.Fatalf("returning-user consume must NOT fire OnSignup; got signupCount=%d", signupCount)
}
if signinCount != 2 {
t.Fatalf("returning-user consume must fire OnSignin; got signinCount=%d", signinCount)
}
}
// TestTenancy_AutoCreatePersonalOrg proves the v2.5 TenancyConfig auto-
// provisions a personal organization on signup, adds the user as owner,
// and sets the session's active organization. Covers issue #77 auto-org.
func TestTenancy_AutoCreatePersonalOrg(t *testing.T) {
store := memory.New()
a, err := theauth.New(theauth.Config{
Storage: store,
BaseURL: "http://localhost",
SessionTTL: time.Hour,
MagicLinkTTL: 15 * time.Minute,
RateLimitPerIP: 100,
RateLimitPerEmail: 100,
Organizations: &theauth.OrganizationsConfig{},
Tenancy: &theauth.TenancyConfig{
AutoCreatePersonalOrg: true,
},
})
if err != nil {
t.Fatal(err)
}
ctx := context.Background()
user, _, err := theauth.SignupWithPasswordForTest(a, ctx, "tenant@y.com", "correct-horse-battery-staple")
if err != nil {
t.Fatalf("signup: %v", err)
}
orgs, err := a.ListUserOrganizations(ctx, user.ID)
if err != nil {
t.Fatalf("ListUserOrganizations: %v", err)
}
if len(orgs) != 1 {
t.Fatalf("want 1 auto-provisioned org; got %d", len(orgs))
}
if orgs[0].Name != "tenant@y.com" {
t.Fatalf("want default org name = email; got %q", orgs[0].Name)
}
members, err := a.ListOrganizationMembers(ctx, orgs[0].ID)
if err != nil {
t.Fatalf("ListOrganizationMembers: %v", err)
}
if len(members) != 1 || members[0].UserID != user.ID || members[0].Role != "owner" {
t.Fatalf("want single owner member; got %+v", members)
}
}
// TestTenancy_CustomNamerAndSlugger proves the Fn customization knobs are
// respected.
func TestTenancy_CustomNamerAndSlugger(t *testing.T) {
store := memory.New()
a, err := theauth.New(theauth.Config{
Storage: store,
BaseURL: "http://localhost",
SessionTTL: time.Hour,
MagicLinkTTL: 15 * time.Minute,
RateLimitPerIP: 100,
RateLimitPerEmail: 100,
Organizations: &theauth.OrganizationsConfig{},
Tenancy: &theauth.TenancyConfig{
AutoCreatePersonalOrg: true,
PersonalOrgNameFn: func(u *theauth.User) string {
return "Workspace for " + u.Email
},
PersonalOrgSlugFn: func(u *theauth.User) string {
return "ws-" + u.ID.String()[:8]
},
},
})
if err != nil {
t.Fatal(err)
}
ctx := context.Background()
user, _, err := theauth.SignupWithPasswordForTest(a, ctx, "custom@y.com", "correct-horse-battery-staple")
if err != nil {
t.Fatal(err)
}
orgs, _ := a.ListUserOrganizations(ctx, user.ID)
if len(orgs) != 1 {
t.Fatalf("want 1 org; got %d", len(orgs))
}
if orgs[0].Name != "Workspace for custom@y.com" {
t.Fatalf("custom name: %q", orgs[0].Name)
}
}
// TestTenancy_DisabledByDefault proves the library does NOT auto-create
// any organization when Tenancy is nil (back-compat guarantee).
func TestTenancy_DisabledByDefault(t *testing.T) {
a, _ := newTestAuth(t)
ctx := context.Background()
user, _, err := theauth.SignupWithPasswordForTest(a, ctx, "noauto@y.com", "correct-horse-battery-staple")
if err != nil {
t.Fatal(err)
}
orgs, err := a.ListUserOrganizations(ctx, user.ID)
if err != nil {
t.Fatalf("ListUserOrganizations: %v", err)
}
if len(orgs) != 0 {
t.Fatalf("Tenancy off: want 0 orgs; got %d", len(orgs))
}
}
// TestUserByID covers the v2.5 public lookup that previously forced
// consumers to reach into storage directly.
func TestUserByID(t *testing.T) {
a, store := newTestAuth(t)
ctx := context.Background()
created, _ := store.CreateUser(ctx, theauth.User{
ID: ulid.New(),
Email: "lookup@y.com",
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
})
got, err := a.UserByID(ctx, created.ID)
if err != nil {
t.Fatalf("UserByID: %v", err)
}
if got == nil || got.Email != "lookup@y.com" {
t.Fatalf("UserByID returned %+v", got)
}
}