forked from go-pkgz/auth
-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth_test.go
506 lines (417 loc) · 14.5 KB
/
auth_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
package auth
import (
"context"
"encoding/json"
"io/ioutil"
"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.AddProvider("dev", "cid", "csecret")
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("battlenet", "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)
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, 8, len(pp))
ch, err := svc.Provider("telegramBotMySiteCom")
assert.NoError(t, err)
chp := ch.Provider
assert.Equal(t, "telegramBotMySiteCom", chp.Name())
}
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 := ioutil.TempDir(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 = ioutil.WriteFile(filePath, []byte(testValidKey), 0600); 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 := ioutil.ReadAll(resp.Body)
assert.Nil(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 = ioutil.ReadAll(resp.Body)
assert.Nil(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", nil)
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", nil)
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 := ioutil.ReadAll(resp.Body)
require.NoError(t, err)
assert.Equal(t, 569, len(b))
}
func TestIntegrationList(t *testing.T) {
_, teardown := prepService(t)
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 := ioutil.ReadAll(resp.Body)
require.NoError(t, err)
assert.Equal(t, `["dev","github","custom123","direct","email"]`+"\n", string(b))
}
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", nil)
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)
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 := ioutil.ReadAll(resp.Body)
require.NoError(t, err)
assert.Equal(t, "{\"error\":\"provides 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)
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 := ioutil.ReadAll(resp.Body)
assert.Nil(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 TestVerifProvider(t *testing.T) {
_, teardown := prepService(t)
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&[email protected]")
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 := ioutil.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 prepService(t *testing.T) (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(18084) // add dev provider on 18084
svc.AddProvider("github", "cid", "csec") // add github provider
// add go-oauth2/oauth2 provider
svc.AddCustomProvider("custom123", Client{"cid", "csecret"}, provider.CustomHandlerOpt{})
// add direct provider
svc.AddDirectProvider("direct", provider.CredCheckerFunc(func(user, password string) (ok bool, err error) {
return user == "dev_direct" && password == "password", nil
}))
svc.AddVerifProvider("email", "{{.Token}}", &sender)
// 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("open route, no token needed\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(w http.ResponseWriter, r *http.Request) {}
func (c customHandler) AuthHandler(w http.ResponseWriter, r *http.Request) {}
func (c customHandler) LogoutHandler(w http.ResponseWriter, r *http.Request) {}