-
-
Notifications
You must be signed in to change notification settings - Fork 93
Expand file tree
/
Copy pathauth_test.go
More file actions
719 lines (602 loc) · 22.3 KB
/
auth_test.go
File metadata and controls
719 lines (602 loc) · 22.3 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
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
package auth
import (
"context"
"encoding/json"
"io"
"net"
"net/http"
"net/http/cookiejar"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/go-pkgz/auth/avatar"
"github.com/go-pkgz/auth/logger"
"github.com/go-pkgz/auth/provider"
"github.com/go-pkgz/auth/token"
)
func TestNewService(t *testing.T) {
options := Opts{
SecretReader: token.SecretFunc(func(string) (string, error) { return "secret", nil }),
TokenDuration: time.Hour,
CookieDuration: time.Hour * 24,
Issuer: "my-test-app",
URL: "http://127.0.0.1:8089",
AvatarStore: avatar.NewLocalFS("/tmp"),
Logger: logger.Std,
}
svc := NewService(options)
assert.NotNil(t, svc)
assert.NotNil(t, svc.TokenService())
assert.NotNil(t, svc.AvatarProxy())
}
func TestProvider(t *testing.T) {
options := Opts{
SecretReader: token.SecretFunc(func(string) (string, error) { return "secret", nil }),
URL: "http://127.0.0.1:8089",
Logger: logger.Std,
}
svc := NewService(options)
_, err := svc.Provider("some provider")
assert.EqualError(t, err, "provider some provider not found")
svc.AddProviderWithUserAttributes("dev", "cid", "csecret", provider.UserAttributes{"attrName": "attrValue"})
svc.AddProvider("github", "cid", "csecret")
svc.AddProvider("google", "cid", "csecret")
svc.AddProvider("facebook", "cid", "csecret")
svc.AddProvider("yandex", "cid", "csecret")
svc.AddProvider("microsoft", "cid", "csecret")
svc.AddProvider("twitter", "cid", "csecret")
svc.AddProvider("battlenet", "cid", "csecret")
svc.AddProvider("patreon", "cid", "csecret")
svc.AddProvider("discord", "cid", "csecret")
svc.AddProvider("bad", "cid", "csecret")
c := customHandler{}
svc.AddCustomHandler(c)
p, err := svc.Provider("dev")
assert.NoError(t, err)
op := p.Provider.(provider.Oauth2Handler)
assert.Equal(t, "dev", op.Name())
assert.Equal(t, "cid", op.Cid)
assert.Equal(t, "csecret", op.Csecret)
assert.Equal(t, "go-pkgz/auth", op.Issuer)
assert.Equal(t, provider.UserAttributes{"attrName": "attrValue"}, op.UserAttributes)
p, err = svc.Provider("github")
assert.NoError(t, err)
op = p.Provider.(provider.Oauth2Handler)
assert.Equal(t, "github", op.Name())
pp := svc.Providers()
assert.Equal(t, 11, len(pp))
ch, err := svc.Provider("telegramBotMySiteCom")
assert.NoError(t, err)
chp := ch.Provider
assert.Equal(t, "telegramBotMySiteCom", chp.Name())
}
func TestService_AddMicrosoftProvider(t *testing.T) {
options := Opts{
SecretReader: token.SecretFunc(func(string) (string, error) { return "secret", nil }),
URL: "http://127.0.0.1:8089",
Logger: logger.Std,
}
t.Run("with custom tenant", func(t *testing.T) {
svc := NewService(options)
svc.AddMicrosoftProvider("cid", "csecret", "my-tenant-id")
p, err := svc.Provider("microsoft")
assert.NoError(t, err)
op := p.Provider.(provider.Oauth2Handler)
assert.Equal(t, "microsoft", op.Name())
assert.Equal(t, "my-tenant-id", op.MicrosoftTenant)
})
t.Run("with empty tenant defaults to common", func(t *testing.T) {
svc := NewService(options)
svc.AddMicrosoftProvider("cid", "csecret", "")
p, err := svc.Provider("microsoft")
assert.NoError(t, err)
op := p.Provider.(provider.Oauth2Handler)
assert.Equal(t, "microsoft", op.Name())
})
}
func TestService_AddVerifProvider_UsesCustomConfirmationStore(t *testing.T) {
custom := &countingVerifStore{}
svc := NewService(Opts{
SecretReader: token.SecretFunc(func(string) (string, error) { return "secret", nil }),
URL: "http://127.0.0.1",
Logger: logger.Std,
VerifConfirmationStore: custom,
})
svc.AddVerifProvider("email", "{{.Token}}", provider.SenderFunc(func(string, string) error { return nil }))
assert.Same(t, custom, svc.verifConfirmStore, "custom store from Opts must be used, not the in-memory default")
}
func TestService_AddVerifProvider_TypedNilStoreFuncFallsBackToDefault(t *testing.T) {
// Opts.VerifConfirmationStore set to a typed-nil VerifConfirmationStoreFunc
// is a non-nil interface wrapping a nil func. Without a service-level
// guard the != nil check at AddVerifProvider succeeds, NewInMemoryVerifStore
// is skipped, and the handler-level guard then normalizes the typed-nil to
// nil at redemption -- net result is replay protection silently disabled.
var nilFn provider.VerifConfirmationStoreFunc
svc := NewService(Opts{
SecretReader: token.SecretFunc(func(string) (string, error) { return "secret", nil }),
URL: "http://127.0.0.1",
Logger: logger.Std,
VerifConfirmationStore: nilFn,
})
svc.AddVerifProvider("email", "{{.Token}}", provider.SenderFunc(func(string, string) error { return nil }))
require.NotNil(t, svc.verifConfirmStore, "typed-nil func must fall back to in-memory default, not silently disable protection")
_, ok := svc.verifConfirmStore.(provider.VerifConfirmationStoreFunc)
assert.False(t, ok, "fallback must be the in-memory default, not the typed-nil func itself")
}
func TestService_AddVerifProvider_DefaultsToInMemory(t *testing.T) {
svc := NewService(Opts{
SecretReader: token.SecretFunc(func(string) (string, error) { return "secret", nil }),
URL: "http://127.0.0.1",
Logger: logger.Std,
})
svc.AddVerifProvider("email", "{{.Token}}", provider.SenderFunc(func(string, string) error { return nil }))
require.NotNil(t, svc.verifConfirmStore, "default store must be installed when Opts.VerifConfirmationStore is nil")
// second call must reuse the same store (sync.Once guards against re-init)
first := svc.verifConfirmStore
svc.AddVerifProvider("email2", "{{.Token}}", provider.SenderFunc(func(string, string) error { return nil }))
assert.Same(t, first, svc.verifConfirmStore, "subsequent AddVerifProvider calls must reuse the same store")
}
type countingVerifStore struct{ calls int }
func (s *countingVerifStore) MarkUsed(string, time.Duration) (bool, error) {
s.calls++
return false, nil
}
func TestService_AddAppleProvider(t *testing.T) {
options := Opts{
SecretReader: token.SecretFunc(func(string) (string, error) { return "secret", nil }),
URL: "http://127.0.0.1:8089",
Logger: logger.Std,
}
svc := NewService(options)
testValidKey := `-----BEGIN PRIVATE KEY-----
MIGTAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBHkwdwIBAQQgTxaHXzyuM85Znw7y
SJ9XeeC8gqcpE/VLhZHGsnPPiPagCgYIKoZIzj0DAQehRANCAATnwlOv7I6eC3Ec
/+GeYXT+hbcmhEVveDqLmNcHiXCR9XxJZXtpMRlcRfY8eaJpUdig27dfsbvpnfX5
Ivx5tHkv
-----END PRIVATE KEY-----`
testPrivKeyFileName := "privKeyTest.tmp"
dir, err := os.MkdirTemp(os.TempDir(), testPrivKeyFileName)
assert.NoError(t, err)
assert.NotNil(t, dir)
if err != nil {
require.NoError(t, err)
return
}
defer func() {
err = os.RemoveAll(dir)
require.NoError(t, err)
}()
filePath := filepath.Join(dir, testPrivKeyFileName)
if err = os.WriteFile(filePath, []byte(testValidKey), 0o600); err != nil {
require.NoError(t, err)
return
}
assert.NoError(t, err)
appleCfg := provider.AppleConfig{
ClientID: "111222",
TeamID: "3334445556",
KeyID: "0011002200",
}
err = svc.AddAppleProvider(appleCfg, provider.LoadApplePrivateKeyFromFile(filePath))
require.NoError(t, err)
p, err := svc.Provider("apple")
assert.NoError(t, err)
assert.Equal(t, p.Name(), "apple")
err = svc.AddAppleProvider(appleCfg, nil)
require.Error(t, err)
}
func TestIntegrationProtected(t *testing.T) {
_, teardown := prepService(t)
defer teardown()
jar, err := cookiejar.New(nil)
require.Nil(t, err)
client := &http.Client{Jar: jar, Timeout: 5 * time.Second}
resp, err := client.Get("http://127.0.0.1:8089/private")
require.Nil(t, err)
assert.Equal(t, 401, resp.StatusCode)
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
assert.NoError(t, err)
assert.Equal(t, "Unauthorized\n", string(body))
// check non-admin, permanent
resp, err = client.Get("http://127.0.0.1:8089/auth/dev/login?site=my-test-site")
require.Nil(t, err)
assert.Equal(t, 200, resp.StatusCode)
defer resp.Body.Close()
body, err = io.ReadAll(resp.Body)
assert.NoError(t, err)
t.Logf("resp %s", string(body))
t.Logf("headers: %+v", resp.Header)
require.Equal(t, 2, len(resp.Cookies()))
assert.Equal(t, "JWT", resp.Cookies()[0].Name)
assert.NotEqual(t, "", resp.Cookies()[0].Value, "token set")
assert.Equal(t, 86400, resp.Cookies()[0].MaxAge)
assert.Equal(t, "XSRF-TOKEN", resp.Cookies()[1].Name)
assert.NotEqual(t, "", resp.Cookies()[1].Value, "xsrf cookie set")
resp, err = client.Get("http://127.0.0.1:8089/private")
require.Nil(t, err)
assert.Equal(t, 200, resp.StatusCode)
assert.NoError(t, resp.Body.Close())
}
func TestIntegrationBasicAuth(t *testing.T) {
_, teardown := prepService(t)
defer teardown()
client := &http.Client{Timeout: 5 * time.Second}
req, err := http.NewRequest("GET", "http://127.0.0.1:8089/private", http.NoBody)
require.Nil(t, err)
resp, err := client.Do(req)
require.Nil(t, err)
assert.Equal(t, 401, resp.StatusCode)
defer resp.Body.Close()
req, err = http.NewRequest("GET", "http://127.0.0.1:8089/private", http.NoBody)
require.Nil(t, err)
req.SetBasicAuth("admin", "password")
resp, err = client.Do(req)
require.Nil(t, err)
assert.Equal(t, 200, resp.StatusCode)
assert.NoError(t, resp.Body.Close())
}
func TestIntegrationAvatar(t *testing.T) {
_, teardown := prepService(t)
defer teardown()
// login
jar, err := cookiejar.New(nil)
require.Nil(t, err)
client := &http.Client{Jar: jar, Timeout: 5 * time.Second}
resp, err := client.Get("http://127.0.0.1:8089/auth/dev/login?site=my-test-site")
require.Nil(t, err)
assert.Equal(t, 200, resp.StatusCode)
resp, err = http.Get("http://127.0.0.1:8089/api/v1/avatar/ccfa2abd01667605b4e1fc4fcb91b1e1af323240.image")
require.NoError(t, err)
defer resp.Body.Close()
require.Equal(t, 200, resp.StatusCode)
b, err := io.ReadAll(resp.Body)
require.NoError(t, err)
assert.Equal(t, 569, len(b))
}
func TestIntegrationList(t *testing.T) {
_, teardown := prepService(t, func(svc *Service) {
svc.AddProvider("github", "cid", "csec")
// add go-oauth2/oauth2 provider
svc.AddCustomProvider("custom123", Client{"cid", "csecret"}, provider.CustomHandlerOpt{})
})
defer teardown()
resp, err := http.Get("http://127.0.0.1:8089/auth/list")
require.NoError(t, err)
defer resp.Body.Close()
assert.Equal(t, 200, resp.StatusCode)
b, err := io.ReadAll(resp.Body)
require.NoError(t, err)
assert.Equal(t, `["dev","github","custom123"]`+"\n", string(b))
}
func TestIntegrationInvalidProviderNames(t *testing.T) {
invalidNames := []string{
"provider/with/slashes",
"provider with spaces",
" providerWithSpacesAround\t",
"providerWithReserved-$-Char",
"providerWithReserved-&-Char",
"providerWithReserved-+-Char",
"providerWithReserved-,-Char",
"providerWithReserved-:-Char",
"providerWithReserved-;-Char",
"providerWithReserved-=-Char",
"providerWithReserved-?-Char",
"providerWithReserved-@-Char",
"providerWith%2F-EscapedSequence",
"",
}
svc, teardown := prepService(t, func(svc *Service) {
for _, name := range invalidNames {
svc.AddCustomProvider(name, Client{"cid", "csecret"}, provider.CustomHandlerOpt{})
}
})
defer teardown()
require.Equal(t, 1, len(svc.Providers()))
require.Equal(t, "dev", svc.Providers()[0].Name())
}
func TestIntegrationUserInfo(t *testing.T) {
_, teardown := prepService(t)
defer teardown()
resp, err := http.Get("http://127.0.0.1:8089/auth/user")
require.NoError(t, err)
defer resp.Body.Close()
assert.Equal(t, 401, resp.StatusCode)
jar, err := cookiejar.New(nil)
require.Nil(t, err)
client := &http.Client{Jar: jar, Timeout: 5 * time.Second}
// login
resp, err = client.Get("http://127.0.0.1:8089/auth/dev/login?site=my-test-site")
require.Nil(t, err)
assert.Equal(t, 200, resp.StatusCode)
defer resp.Body.Close()
// get user info
req, err := http.NewRequest("GET", "http://127.0.0.1:8089/auth/user", http.NoBody)
require.NoError(t, err)
t.Log(resp.Cookies())
resp, err = client.Do(req)
require.NoError(t, err)
defer resp.Body.Close()
require.Equal(t, 200, resp.StatusCode)
u := token.User{}
err = json.NewDecoder(resp.Body).Decode(&u)
require.NoError(t, err)
assert.Equal(t, token.User{Name: "dev_user", ID: "dev_user", Audience: "my-test-site",
Picture: "http://127.0.0.1:8089/api/v1/avatar/ccfa2abd01667605b4e1fc4fcb91b1e1af323240.image"}, u)
}
func TestLogout(t *testing.T) {
_, teardown := prepService(t)
defer teardown()
// login
jar, err := cookiejar.New(nil)
require.Nil(t, err)
client := &http.Client{Jar: jar, Timeout: 5 * time.Second}
resp, err := client.Get("http://127.0.0.1:8089/auth/dev/login?site=my-test-site")
require.Nil(t, err)
assert.Equal(t, 200, resp.StatusCode)
// logout
resp, err = client.Get("http://127.0.0.1:8089/auth/logout")
require.Nil(t, err)
assert.Equal(t, 200, resp.StatusCode)
assert.Equal(t, "text/plain; charset=utf-8", resp.Header.Get("Content-Type"))
defer resp.Body.Close()
resp, err = client.Get("http://127.0.0.1:8089/private")
require.Nil(t, err)
assert.Equal(t, 401, resp.StatusCode)
assert.NoError(t, resp.Body.Close())
}
func TestLogoutNoProviders(t *testing.T) {
svc := NewService(Opts{Logger: logger.Std})
authRoute, _ := svc.Handlers()
mux := http.NewServeMux()
mux.Handle("/auth/", authRoute)
ts := httptest.NewServer(mux)
defer ts.Close()
resp, err := http.Get(ts.URL + "/auth/logout")
require.NoError(t, err)
defer resp.Body.Close()
assert.Equal(t, 400, resp.StatusCode)
b, err := io.ReadAll(resp.Body)
require.NoError(t, err)
assert.Equal(t, "{\"error\":\"providers not defined\"}\n", string(b))
}
func TestBadRequests(t *testing.T) {
_, teardown := prepService(t)
defer teardown()
client := &http.Client{Timeout: 5 * time.Second}
resp, err := client.Get("http://127.0.0.1:8089/auth/bad/login")
require.Nil(t, err)
assert.Equal(t, 400, resp.StatusCode)
defer resp.Body.Close()
resp, err = client.Get("http://127.0.0.1:8089/auth")
require.Nil(t, err)
assert.Equal(t, 400, resp.StatusCode)
assert.NoError(t, resp.Body.Close())
}
func TestDirectProvider(t *testing.T) {
_, teardown := prepService(t, func(svc *Service) {
svc.AddDirectProvider("direct", provider.CredCheckerFunc(func(user, password string) (ok bool, err error) {
return user == "dev_direct" && password == "password", nil
}))
})
defer teardown()
// login
jar, err := cookiejar.New(nil)
require.Nil(t, err)
client := &http.Client{Jar: jar, Timeout: 5 * time.Second}
resp, err := client.Get("http://127.0.0.1:8089/auth/direct/login?user=dev_direct&passwd=bad")
require.Nil(t, err)
defer resp.Body.Close()
assert.Equal(t, 403, resp.StatusCode)
resp, err = client.Get("http://127.0.0.1:8089/auth/direct/login?user=dev_direct&passwd=password")
require.Nil(t, err)
defer resp.Body.Close()
assert.Equal(t, 200, resp.StatusCode)
body, err := io.ReadAll(resp.Body)
assert.NoError(t, err)
t.Logf("resp %s", string(body))
t.Logf("headers: %+v", resp.Header)
assert.Contains(t, string(body), `"name":"dev_direct","id":"direct_38773b45e3a477434abb6d08668358a2b0ddd2f5"`)
require.Equal(t, 2, len(resp.Cookies()))
assert.Equal(t, "JWT", resp.Cookies()[0].Name)
assert.NotEqual(t, "", resp.Cookies()[0].Value, "token set")
assert.Equal(t, 86400, resp.Cookies()[0].MaxAge)
assert.Equal(t, "XSRF-TOKEN", resp.Cookies()[1].Name)
assert.NotEqual(t, "", resp.Cookies()[1].Value, "xsrf cookie set")
resp, err = client.Get("http://127.0.0.1:8089/private")
require.Nil(t, err)
assert.Equal(t, 200, resp.StatusCode)
assert.NoError(t, resp.Body.Close())
}
func TestDirectProvider_WithCustomUserIDFunc(t *testing.T) {
_, teardown := prepService(t, func(svc *Service) {
svc.AddDirectProviderWithUserIDFunc("direct_custom",
provider.CredCheckerFunc(func(user, password string) (ok bool, err error) {
return user == "dev_direct" && password == "password", nil
}),
func(user string, r *http.Request) string {
return "blah"
},
)
})
defer teardown()
// login
jar, err := cookiejar.New(nil)
require.Nil(t, err)
client := &http.Client{Jar: jar, Timeout: 5 * time.Second}
resp, err := client.Get("http://127.0.0.1:8089/auth/direct_custom/login?user=dev_direct&passwd=bad")
require.Nil(t, err)
defer resp.Body.Close()
assert.Equal(t, 403, resp.StatusCode)
resp, err = client.Get("http://127.0.0.1:8089/auth/direct_custom/login?user=dev_direct&passwd=password")
require.Nil(t, err)
defer resp.Body.Close()
assert.Equal(t, 200, resp.StatusCode)
body, err := io.ReadAll(resp.Body)
assert.NoError(t, err)
t.Logf("resp %s", string(body))
t.Logf("headers: %+v", resp.Header)
assert.Contains(t, string(body), `"name":"dev_direct","id":"direct_custom_5bf1fd927dfb8679496a2e6cf00cbe50c1c87145"`)
require.Equal(t, 2, len(resp.Cookies()))
assert.Equal(t, "JWT", resp.Cookies()[0].Name)
assert.NotEqual(t, "", resp.Cookies()[0].Value, "token set")
assert.Equal(t, 86400, resp.Cookies()[0].MaxAge)
assert.Equal(t, "XSRF-TOKEN", resp.Cookies()[1].Name)
assert.NotEqual(t, "", resp.Cookies()[1].Value, "xsrf cookie set")
resp, err = client.Get("http://127.0.0.1:8089/private")
require.Nil(t, err)
assert.Equal(t, 200, resp.StatusCode)
assert.NoError(t, resp.Body.Close())
}
func TestVerifProvider(t *testing.T) {
_, teardown := prepService(t, func(svc *Service) {
svc.AddVerifProvider("email", "{{.Token}}", &sender)
})
defer teardown()
// login
client := &http.Client{Timeout: 5 * time.Second}
resp, err := client.Get("http://127.0.0.1:8089/auth/email/login?user=dev&address=xyz@gmail.com")
require.Nil(t, err)
defer resp.Body.Close()
assert.Equal(t, 200, resp.StatusCode)
tkn := sender.text
jar, err := cookiejar.New(nil)
require.NoError(t, err)
client = &http.Client{Jar: jar, Timeout: 5 * time.Second}
resp, err = client.Get("http://127.0.0.1:8089/auth/email/login?token=" + tkn)
require.NoError(t, err)
defer resp.Body.Close()
assert.Equal(t, 200, resp.StatusCode)
body, err := io.ReadAll(resp.Body)
require.NoError(t, err)
t.Logf("resp %s", string(body))
t.Logf("headers: %+v", resp.Header)
u := token.User{}
err = json.Unmarshal(body, &u)
require.NoError(t, err)
assert.Equal(t, token.User{Name: "dev", ID: "email_84714ea398a960df03e2619d1b850dfac25f585e",
Picture: "http://127.0.0.1:8089/api/v1/avatar/e8eb81cc51b1123059ab29575296cbfd8a6a1b6e.image"}, u)
require.Equal(t, 2, len(resp.Cookies()))
assert.Equal(t, "JWT", resp.Cookies()[0].Name)
assert.NotEqual(t, "", resp.Cookies()[0].Value, "token set")
assert.Equal(t, 86400, resp.Cookies()[0].MaxAge)
assert.Equal(t, "XSRF-TOKEN", resp.Cookies()[1].Name)
assert.NotEqual(t, "", resp.Cookies()[1].Value, "xsrf cookie set")
}
func TestStatus(t *testing.T) {
svc, teardown := prepService(t)
defer teardown()
authRoute, _ := svc.Handlers()
mux := http.NewServeMux()
mux.Handle("/auth/", authRoute)
ts := httptest.NewServer(mux)
defer ts.Close()
resp, err := http.Get(ts.URL + "/auth/status")
require.NoError(t, err)
defer resp.Body.Close()
assert.Equal(t, http.StatusOK, resp.StatusCode)
b, err := io.ReadAll(resp.Body)
require.NoError(t, err)
assert.Equal(t, "{\"status\":\"not logged in\"}\n", string(b))
// login
jar, err := cookiejar.New(nil)
require.Nil(t, err)
client := &http.Client{Jar: jar, Timeout: 5 * time.Second}
resp, err = client.Get("http://127.0.0.1:8089/auth/dev/login?site=my-test-site")
require.Nil(t, err)
assert.Equal(t, 200, resp.StatusCode)
resp, err = client.Get(ts.URL + "/auth/status")
require.NoError(t, err)
defer resp.Body.Close()
assert.Equal(t, http.StatusOK, resp.StatusCode)
b, err = io.ReadAll(resp.Body)
require.NoError(t, err)
assert.Equal(t, "{\"status\":\"logged in\",\"user\":\"dev_user\"}\n", string(b))
}
func TestDevAuthServerWithoutDevProvider(t *testing.T) {
svc := NewService(Opts{})
assert.NotNil(t, svc)
_, err := svc.DevAuth()
require.NotNil(t, err)
assert.EqualError(t, err, "dev provider not registered: provider dev not found")
}
func prepService(t *testing.T, providerConfigFunctions ...func(svc *Service)) (svc *Service, teardown func()) { //nolint unparam
options := Opts{
SecretReader: token.SecretFunc(func(string) (string, error) { return "secret", nil }),
TokenDuration: time.Hour,
CookieDuration: time.Hour * 24,
Issuer: "my-test-app",
URL: "http://127.0.0.1:8089",
DisableXSRF: true,
DisableIAT: true,
Validator: token.ValidatorFunc(func(_ string, claims token.Claims) bool {
return claims.User != nil && strings.HasPrefix(claims.User.Name, "dev_") // allow only dev_ names
}),
AvatarStore: avatar.NewLocalFS("/tmp/auth-pkgz"),
AvatarResizeLimit: 120,
AvatarRoutePath: "/api/v1/avatar",
AdminPasswd: "password",
Logger: logger.Std,
}
svc = NewService(options)
svc.AddDevProvider("localhost", 18084) // add dev provider on 18084
for _, f := range providerConfigFunctions {
f(svc)
}
// run dev/test oauth2 server on :18084
devAuth, err := svc.DevAuth()
require.NoError(t, err)
devAuth.Automatic = true // eliminate form
go devAuth.Run(context.TODO())
time.Sleep(time.Millisecond * 50)
// setup http server
m := svc.Middleware()
mux := http.NewServeMux()
mux.Handle("/open", http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { // no token required
_, _ = w.Write([]byte("open route, no token needed\n"))
}))
mux.Handle("/private", m.Auth(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { // token required
_, _ = w.Write([]byte("protected route, authenticated with token\n"))
})))
// setup auth routes
authRoute, avaRoutes := svc.Handlers()
mux.Handle("/auth/", authRoute) // add token handlers
mux.Handle("/api/v1/avatar/", http.StripPrefix("/api/v1/avatar", avaRoutes)) // add avatar handler
l, err := net.Listen("tcp", "127.0.0.1:8089")
require.Nil(t, err)
ts := httptest.NewUnstartedServer(mux)
assert.NoError(t, ts.Listener.Close())
ts.Listener = l
ts.Start()
return svc, func() {
ts.Close()
devAuth.Shutdown()
_ = os.RemoveAll("/tmp/auth-pkgz")
}
}
var sender = mockSender{}
type mockSender struct {
err error
to string
text string
}
func (m *mockSender) Send(to, text string) error {
if m.err != nil {
return m.err
}
m.to = to
m.text = text
return nil
}
type customHandler struct{}
func (c customHandler) Name() string {
return "telegramBotMySiteCom"
}
func (c customHandler) LoginHandler(http.ResponseWriter, *http.Request) {}
func (c customHandler) AuthHandler(http.ResponseWriter, *http.Request) {}
func (c customHandler) LogoutHandler(http.ResponseWriter, *http.Request) {}