-
Notifications
You must be signed in to change notification settings - Fork 4
/
main_test.go
468 lines (387 loc) · 13 KB
/
main_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
package main
import (
"bytes"
"context"
"crypto/sha256"
"encoding/base64"
"encoding/json"
"flag"
"github.com/stretchr/testify/assert"
"github.com/xlzd/gotp"
"io/ioutil"
"log"
"net/http"
"net/url"
"os"
"strconv"
"strings"
"testing"
"time"
)
const (
testDBPath = "/tmp/fa.db"
testDBDriver = "sqlite3"
testDBScripts = "rmdb.sql:init.sql"
testDomain = "localhost"
testPort = 8082
testUrl = "http://" + testDomain + ":8082"
)
var (
testParams = []string{"-issuer=FFFS",
"-port=" + strconv.Itoa(testPort),
"-db-path=" + testDBPath,
"-db-driver=" + testDBDriver,
"-db-scripts=" + testDBScripts,
"-email-url=" + testUrl + "/send/email/{email}/{token}",
"-dev=true"}
)
/*
curl -v "http://localhost:8080/signup" -X POST -d "{\"email\":\"tom\",\"password\":\"test\"}" -H "Content-Type: application/json"
*/
func TestSignup(t *testing.T) {
shutdown := mainTest(testParams...)
resp := doSignup("[email protected]", "testtest")
assert.Equal(t, http.StatusOK, resp.StatusCode)
resp.Body.Close()
shutdown()
}
func TestSignupWrongEmail(t *testing.T) {
shutdown := mainTest(testParams...)
resp := doSignup("tomtest.ch", "testtest")
assert.Equal(t, http.StatusBadRequest, resp.StatusCode)
bodyBytes, _ := ioutil.ReadAll(resp.Body)
bodyString := string(bodyBytes)
assert.True(t, strings.Index(bodyString, "ERR-signup-02") > 0)
resp.Body.Close()
shutdown()
}
func TestSignupTwiceWorking(t *testing.T) {
shutdown := mainTest(testParams...)
resp := doSignup("[email protected]", "testtest")
resp = doSignup("[email protected]", "testtest")
assert.Equal(t, http.StatusOK, resp.StatusCode)
resp.Body.Close()
shutdown()
}
func TestSignupTwiceNotWorking(t *testing.T) {
shutdown := mainTest(testParams...)
resp := doSignup("[email protected]", "testtest")
token := token("[email protected]")
resp = doConfirm("[email protected]", token)
resp = doSignup("[email protected]", "testtest")
bodyBytes, _ := ioutil.ReadAll(resp.Body)
bodyString := string(bodyBytes)
assert.Equal(t, http.StatusBadRequest, resp.StatusCode)
log.Println(bodyString)
assert.True(t, strings.Index(bodyString, "ERR-signup-07") > 0)
resp.Body.Close()
shutdown()
}
func TestConfirm(t *testing.T) {
shutdown := mainTest(testParams...)
resp := doSignup("[email protected]", "testtest")
assert.Equal(t, 200, resp.StatusCode)
token := token("[email protected]")
resp = doConfirm("[email protected]", token)
assert.Equal(t, http.StatusOK, resp.StatusCode)
resp.Body.Close()
shutdown()
}
func TestLogin(t *testing.T) {
shutdown := mainTest(testParams...)
resp := doSignup("[email protected]", "testtest")
assert.Equal(t, http.StatusOK, resp.StatusCode)
token := token("[email protected]")
resp = doConfirm("[email protected]", token)
assert.Equal(t, http.StatusOK, resp.StatusCode)
resp = doLogin("[email protected]", "testtest", "", "")
assert.Equal(t, http.StatusSeeOther, resp.StatusCode)
resp.Body.Close()
shutdown()
}
func TestLoginFalse(t *testing.T) {
shutdown := mainTest(testParams...)
resp := doAll("[email protected]", "testtest", "0123456789012345678901234567890123456789012")
assert.Equal(t, http.StatusOK, resp.StatusCode)
resp = doLogin("[email protected]", "testtest", "", "0123456789012345678901234567890123456789012")
assert.Equal(t, http.StatusSeeOther, resp.StatusCode)
resp = doLogin("[email protected]", "testtest2", "", "0123456789012345678901234567890123456789012")
bodyBytes, _ := ioutil.ReadAll(resp.Body)
assert.Equal(t, http.StatusBadRequest, resp.StatusCode)
assert.True(t, strings.Index(string(bodyBytes), "ERR-checkEmail-06, user [email protected] password mismatch") > 0)
resp = doLogin("[email protected]", "testtest", "", "0123456789012345678901234567890123456789012")
bodyBytes, _ = ioutil.ReadAll(resp.Body)
assert.Equal(t, http.StatusBadRequest, resp.StatusCode)
assert.True(t, strings.Index(string(bodyBytes), "ERR-checkEmail-01, DB select, [email protected] err sql: no rows in result set") > 0)
resp.Body.Close()
shutdown()
}
func TestRefresh(t *testing.T) {
tmp := append(testParams, "-expire-refresh=10")
shutdown := mainTest(tmp...)
resp := doAll("[email protected]", "testtest", "0123456789012345678901234567890123456789012")
assert.Equal(t, http.StatusOK, resp.StatusCode)
oauth := OAuth{}
json.NewDecoder(resp.Body).Decode(&oauth)
assert.NotEqual(t, "", oauth.AccessToken)
shutdown()
}
func TestReset(t *testing.T) {
tmp := append(testParams, "-expire-refresh=1")
shutdown := mainTest(tmp...)
resp := doAll("[email protected]", "testtest", "0123456789012345678901234567890123456789012")
assert.Equal(t, http.StatusOK, resp.StatusCode)
resp = doReset("[email protected]")
assert.Equal(t, http.StatusOK, resp.StatusCode)
token, _ := getForgotEmailToken("[email protected]")
resp = doConfirmReset("[email protected]", token, "testtest2")
assert.Equal(t, http.StatusOK, resp.StatusCode)
resp = doLogin("[email protected]", "testtest2", "", "0123456789012345678901234567890123456789012")
assert.Equal(t, http.StatusSeeOther, resp.StatusCode)
resp.Body.Close()
shutdown()
}
func TestResetFailed(t *testing.T) {
tmp := append(testParams, "-expire-refresh=1")
shutdown := mainTest(tmp...)
resp := doAll("[email protected]", "testtest", "0123456789012345678901234567890123456789012")
assert.Equal(t, http.StatusOK, resp.StatusCode)
resp = doReset("[email protected]")
assert.Equal(t, http.StatusOK, resp.StatusCode)
token, _ := getForgotEmailToken("[email protected]")
resp = doConfirmReset("[email protected]", token, "testtest2")
assert.Equal(t, http.StatusOK, resp.StatusCode)
resp = doLogin("[email protected]", "testtest", "", "0123456789012345678901234567890123456789012")
assert.Equal(t, http.StatusBadRequest, resp.StatusCode)
resp.Body.Close()
shutdown()
}
func TestTOTP(t *testing.T) {
shutdown := mainTest(testParams...)
resp := doAll("[email protected]", "testtest", "0123456789012345678901234567890123456789012")
assert.Equal(t, http.StatusOK, resp.StatusCode)
oauth := OAuth{}
json.NewDecoder(resp.Body).Decode(&oauth)
resp = doTOTP(oauth.AccessToken)
p := ProvisioningUri{}
bodyBytes, _ := ioutil.ReadAll(resp.Body)
json.Unmarshal(bodyBytes, &p)
secret := strings.SplitN(p.Uri, "=", 2)
secret = strings.SplitN(secret[1], "&", 2)
totp := newTOTP(secret[0])
conf := totp.Now()
resp = doTOTPConfirm(conf, oauth.AccessToken)
assert.Equal(t, http.StatusOK, resp.StatusCode)
resp.Body.Close()
shutdown()
}
func TestLoginTOTP(t *testing.T) {
shutdown := mainTest(testParams...)
resp := doAll("[email protected]", "testtest", "0123456789012345678901234567890123456789012")
assert.Equal(t, http.StatusOK, resp.StatusCode)
oauth := OAuth{}
json.NewDecoder(resp.Body).Decode(&oauth)
totp := doAllTOTP(oauth.AccessToken)
resp = doLogin("[email protected]", "testtest", totp.Now(), "0123456789012345678901234567890123456789012")
assert.Equal(t, http.StatusSeeOther, resp.StatusCode)
resp = doLogin("[email protected]", "testtest", "", "0123456789012345678901234567890123456789012")
assert.Equal(t, http.StatusForbidden, resp.StatusCode)
resp.Body.Close()
shutdown()
}
func doTOTP(token string) *http.Response {
req, _ := http.NewRequest("POST", testUrl+"/setup/totp", nil)
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+token)
resp, _ := http.DefaultClient.Do(req)
return resp
}
func doTOTPConfirm(conf string, token string) *http.Response {
req, _ := http.NewRequest("POST", testUrl+"/confirm/totp/"+conf, nil)
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+token)
resp, _ := http.DefaultClient.Do(req)
return resp
}
func doAllTOTP(token string) *gotp.TOTP {
resp := doTOTP(token)
p := ProvisioningUri{}
bodyBytes, _ := ioutil.ReadAll(resp.Body)
json.Unmarshal(bodyBytes, &p)
secret := strings.SplitN(p.Uri, "=", 2)
secret = strings.SplitN(secret[1], "&", 2)
totp := newTOTP(secret[0])
conf := totp.Now()
resp = doTOTPConfirm(conf, token)
return totp
}
func doConfirmReset(email string, token string, password string) *http.Response {
data := Credentials{
Email: email,
Password: password,
EmailToken: token,
}
payloadBytes, _ := json.Marshal(data)
body := bytes.NewReader(payloadBytes)
req, _ := http.NewRequest("POST", testUrl+"/confirm/reset", body)
req.Header.Set("Content-Type", "application/json")
resp, _ := http.DefaultClient.Do(req)
return resp
}
func doReset(email string) *http.Response {
req, _ := http.NewRequest("POST", testUrl+"/reset/"+email, nil)
resp, _ := http.DefaultClient.Do(req)
return resp
}
func doAll(email string, pass string, secret string) *http.Response {
resp := doSignup(email, pass)
token := token(email)
resp = doConfirm(email, token)
resp = doLogin(email, pass, "", secret)
code := resp.Header.Get("Location")[6:]
resp = doCode(code, secret)
return resp
}
func doCode(codeToken string, codeVerifier string) *http.Response {
data := url.Values{}
data.Set("grant_type", "authorization_code")
data.Set("code", codeToken)
data.Set("code_verifier", codeVerifier)
req, _ := http.NewRequest("POST", testUrl+"/oauth/token", strings.NewReader(data.Encode()))
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
resp, _ := http.DefaultClient.Do(req)
return resp
}
func doRefresh(refreshToken string) *http.Response {
data := url.Values{}
data.Set("grant_type", "refresh_token")
data.Set("refresh_token", refreshToken)
req, _ := http.NewRequest("POST", testUrl+"/oauth/token", strings.NewReader(data.Encode()))
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
resp, _ := http.DefaultClient.Do(req)
return resp
}
func doLogin(email string, pass string, totp string, secret string) *http.Response {
h := sha256.Sum256([]byte(secret))
data := Credentials{
Email: email,
Password: pass,
TOTP: totp,
CodeChallenge: base64.RawURLEncoding.EncodeToString(h[:]),
CodeCodeChallengeMethod: "S256",
}
//do not follow redirects: https://stackoverflow.com/questions/23297520/how-can-i-make-the-go-http-client-not-follow-redirects-automatically
client := &http.Client{
CheckRedirect: func(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse
},
}
payloadBytes, _ := json.Marshal(data)
body := bytes.NewReader(payloadBytes)
req, _ := http.NewRequest(http.MethodPost, testUrl+"/login", body)
req.Header.Set("Content-Type", "application/json")
resp, _ := client.Do(req)
return resp
}
func doSignup(email string, pass string) *http.Response {
data := Credentials{
Email: email,
Password: pass,
}
payloadBytes, _ := json.Marshal(data)
body := bytes.NewReader(payloadBytes)
req, err := http.NewRequest("POST", testUrl+"/signup", body)
if err != nil {
log.Printf("request failed %v", err)
}
req.Header.Set("Content-Type", "application/json")
resp, err := http.DefaultClient.Do(req)
if err != nil {
log.Printf("request failed %v", err)
}
return resp
}
func doConfirm(email string, token string) *http.Response {
c := &http.Client{
Timeout: 15 * time.Second,
}
resp, _ := c.Get(testUrl + "/confirm/signup/" + email + "/" + token)
return resp
}
func token(email string) string {
r, _ := getEmailToken(email)
return string(r)
}
func getEmailToken(email string) (string, error) {
var emailToken string
err := db.QueryRow("SELECT email_token from auth where email = $1", email).Scan(&emailToken)
if err != nil {
return "", err
}
return emailToken, nil
}
func getForgotEmailToken(email string) (string, error) {
var forgetEmailToken string
err := db.QueryRow("SELECT forget_email_token from auth where email = $1", email).Scan(&forgetEmailToken)
if err != nil {
return "", err
}
return forgetEmailToken, nil
}
func TestSecret(t *testing.T) {
h := sha256.Sum256([]byte("test"))
s := base64.RawURLEncoding.EncodeToString(h[:])
assert.Equal(t, "n4bQgYhMfWWaL-qgxVrQFaO_TxsrC4Is0V1sFbDwCgg", s)
}
func TestGetAttrDN(t *testing.T) {
assert.Equal(t,
getAttrDN("CN=tom,OU=P_Internal,OU=P_Users,DC=test,DC=ch", "cn"),
"tom")
assert.Equal(t,
getAttrDN("CN=tom,OU=P_Internal,OU=P_Users,DC=test,DC=ch", "cn"),
getAttrDN("cn=tom,ou=P_Internal,ou=P_Users,dc=test,dc=ch", "CN"))
}
func mainTest(args ...string) func() {
oldArgs := os.Args
os.Args = []string{oldArgs[0]}
os.Args = append(os.Args, args...)
opts = NewOpts()
var err error
db, err = initDB()
if err != nil {
log.Fatal(err)
}
setupDB()
serverRest, doneChannelRest, err := serverRest(false)
if err != nil {
log.Fatal(err)
}
serverLdap, doneChannelLdap := serverLdap()
return func() {
defer timeTrack(time.Now(), "shutdown")
os.Args = oldArgs
flag.CommandLine = flag.NewFlagSet(os.Args[0], flag.ExitOnError)
serverRest.Shutdown(context.Background())
serverLdap.Stop()
if serverLdap.Listener != nil {
serverLdap.Listener.Close()
}
err := db.Close()
if err != nil {
log.Printf("could not close DB %v", err)
}
//for testing, the DB needs to be wiped after each run
if opts.DBDriver == "sqlite3" {
err = os.Remove(opts.DBPath)
if err != nil {
log.Printf("could not remove DB file %v", err)
}
}
<-doneChannelRest
<-doneChannelLdap
}
}
func timeTrack(start time.Time, name string) {
elapsed := time.Since(start)
log.Printf("%s took %s", name, elapsed)
}