-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathauth_test.go
416 lines (323 loc) · 12 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
package webauth
/*
Test the package at a high level (client HTTP requests).
This tester will connect to a test database and DROP THE USER TABLE before running the actual tests.
Available environment variables to set before testing:
AUTHTEST_DEBUG=1 // Turn on debugging: util.Debug(true)
AUTHTEST_SQL_DRIVER=postgres // Switch driver to postgres (sqlite is the default)
Examples:
// Set driver to postgres
AUTHTEST_SQL_DRIVER=postgres go test
// Set driver to postgres and turn on debugging
AUTHTEST_DEBUG=1 AUTHTEST_SQL_DRIVER=postgres go test
*/
import (
"bytes"
"database/sql"
"encoding/json"
"errors"
"fmt"
"github.com/gorilla/mux"
_ "github.com/lib/pq"
//sqlite "github.com/mattn/go-sqlite3"
sqlite "github.com/rhomel/go-sqlite3" // Has Version func
"github.com/rhomel/webauth/util"
//_ "github.com/mxk/go-sqlite/sqlite3"
"io/ioutil"
"log"
"net/http"
"os"
"testing"
)
const ServerHost = "localhost:7777"
const DbFile = "./testcase.db"
const ProtectedResource = "/api/secretsauce"
const ProtectedResourceContent = "top-secret"
func init() {
paths := RedirectPaths{}
paths.SuccessfulLogin = "/test/success/login"
paths.LoginForm = "/test/login"
paths.ForgotPasswordForm = "/test/forgot"
paths.ResetPasswordForm = "/test/reset"
paths.NewAccountForm = "/test/newaccount"
http.HandleFunc("/test/login", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "test")
})
apiMux := mux.NewRouter()
apiMux.HandleFunc(ProtectedResource, func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, ProtectedResourceContent)
})
setupServer(apiMux, paths)
}
func testHttpRequest(t *testing.T, httpVerb string, resourcePath string, inputJson string, cookies []*http.Cookie, wantError bool, outputVerifier func(*testing.T, *http.Response)) {
client := new(http.Client)
client.CheckRedirect = func(req *http.Request, via []*http.Request) error {
return errors.New("redirect received")
}
body := bytes.NewReader([]byte(inputJson))
resource := "http://" + ServerHost + resourcePath
log.Println("[http client] Requesting: " + resource)
req, err := http.NewRequest(httpVerb, resource, body)
req.Header.Add("Content-Type", "application/json")
if cookies != nil {
for _, cookie := range cookies {
req.AddCookie(cookie)
}
}
resp, err := client.Do(req)
if err != nil && !wantError {
log.Fatalf("Client request returned an error: %v", err)
}
if resp.StatusCode != 200 && !wantError {
log.Fatalf("Server returned not-ok HTTP response code. Received code: %d", resp.StatusCode)
}
outputVerifier(t, resp)
}
func testJsonHttpRequest(t *testing.T, httpVerb string, resourcePath string, inputJson string, cookies []*http.Cookie, outputJsonVerifier func(*testing.T, map[string]interface{}, *http.Response)) {
testHttpRequest(t, httpVerb, resourcePath, inputJson, cookies, false, func(t *testing.T, resp *http.Response) {
var rjson map[string]interface{}
rbody, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Fatalf("Error occurred during reading response Body")
}
json.Unmarshal(rbody, &rjson)
// close body
resp.Body.Close()
outputJsonVerifier(t, rjson, resp)
})
}
func testCreateNewAccount(t *testing.T, inputJson string, outputJsonVerifier func(*testing.T, map[string]interface{}, *http.Response)) {
testJsonHttpRequest(t, "POST", "/auth/internal/json/new", inputJson, nil, outputJsonVerifier)
}
func testLogin(t *testing.T, inputJson string, outputJsonVerifier func(*testing.T, map[string]interface{}, *http.Response)) {
testJsonHttpRequest(t, "POST", "/auth/internal/json/authenticate", inputJson, nil, outputJsonVerifier)
}
func verifyBasicErrorFunc(t *testing.T, rjson map[string]interface{}, response *http.Response) {
if rjson == nil {
t.Errorf("Received no response body")
return
}
successCode := rjson["Success"].(float64)
if successCode != 0 {
t.Errorf("Received successful account creation code when expecting 0. Received: %v", successCode)
return
}
errorMessage := rjson["Error"].(string)
if errorMessage == "" {
t.Errorf("Received empty error message.")
return
}
}
func verifyBasicSuccessFunc(t *testing.T, rjson map[string]interface{}, response *http.Response) {
if rjson == nil {
t.Errorf("Received no response body")
return
}
if rjson["Success"].(float64) != 1 || rjson["Error"] != "" {
t.Errorf("Didn't create the new user account correctly. Received: %v", rjson)
return
}
}
func TestNewAccountBasic(t *testing.T) {
var json string
json = `{"User":"bob","Password":"marley","Email":"deputy@example.com"}`
testCreateNewAccount(t, json, verifyBasicSuccessFunc)
}
func TestNewAccountDuplicates(t *testing.T) {
var json string
// create an account
json = `{"User":"joe","Password":"SuperSecret","Email":"joe@example.com"}`
testCreateNewAccount(t, json, verifyBasicSuccessFunc)
// try to create it again expecting an error
testCreateNewAccount(t, json, verifyBasicErrorFunc)
// try same username but different email
json = `{"User":"joe","Password":"SuperSecret","Email":"joeblow@example.com"}`
testCreateNewAccount(t, json, verifyBasicErrorFunc)
// try different username but same email
json = `{"User":"joeblow","Password":"SuperSecret","Email":"joe@example.com"}`
testCreateNewAccount(t, json, verifyBasicErrorFunc)
}
func TestNewAccountMissingParametersNoUser(t *testing.T) {
// no username
json := `{"User":"","Password":"Such Forgettable","Email":"jane@example.com"}`
testCreateNewAccount(t, json, verifyBasicErrorFunc)
}
func TestNewAccountMissingParametersNoPassword(t *testing.T) {
// no password
json := `{"User":"jane","Password":"","Email":"jane@example.com"}`
testCreateNewAccount(t, json, verifyBasicErrorFunc)
}
func TestNewAccountMissingParametersNoEmail(t *testing.T) {
// no email
json := `{"User":"jane","Password":"Such Forgettable","Email":""}`
testCreateNewAccount(t, json, verifyBasicErrorFunc)
}
func TestNewAccountMissingParametersWhiteSpaceUserName(t *testing.T) {
// note: middle space is a non-breakable unicode space
json := `{"User":" ","Password":"Such Forgettable","Email":"jane@example.com"}`
testCreateNewAccount(t, json, verifyBasicErrorFunc)
}
func verifyLoginSuccess(t *testing.T, rjson map[string]interface{}, response *http.Response) {
if rjson == nil {
t.Errorf("Received no response body")
t.FailNow()
}
if rjson["Success"].(float64) != 1 || rjson["Error"] != "" {
t.Errorf("Didn't create the new user account correctly. Received: %v", rjson)
t.FailNow()
}
cookies := response.Cookies()
found := false
// look for the login cookie
for _, cookie := range cookies {
if cookie.Name == "login" {
found = true
}
}
if !found {
t.Errorf("Didn't receive a login cookie.")
t.FailNow()
}
}
func verifyLoginFailure(t *testing.T, rjson map[string]interface{}, response *http.Response) {
if rjson == nil {
t.Errorf("Received no response body")
t.FailNow()
}
if rjson["Success"].(float64) != 0 || rjson["Error"] == "" {
t.Errorf("Didn't report expected failed login. Received: %v", rjson)
}
cookies := response.Cookies()
found := false
// look for the login cookie
for _, cookie := range cookies {
if cookie.Name == "login" {
found = true
}
}
if found {
t.Errorf("Received login cookie when shouldn't have due to incorrect login.")
t.FailNow()
}
}
func TestLoginBasic(t *testing.T) {
var json string
json = `{"User":"alice","Password":"WONDerful","Email":"alice@example.com"}`
testCreateNewAccount(t, json, verifyBasicSuccessFunc)
var cookies []*http.Cookie
// try logging in
json = `{"User":"alice","Password":"WONDerful"}`
testLogin(t, json, func(t *testing.T, rjson map[string]interface{}, response *http.Response) {
verifyLoginSuccess(t, rjson, response)
cookies = response.Cookies()
})
// try accessing a protected resource that requires login
testHttpRequest(t, "GET", ProtectedResource, "", cookies, false, func(t *testing.T, response *http.Response) {
rbody, err := ioutil.ReadAll(response.Body)
if err != nil {
log.Fatalf("Error occurred during reading response Body")
}
if ProtectedResourceContent != string(rbody) {
t.Errorf("Didn't get expected resource body. Expect `%v`. Received `%v`.", ProtectedResourceContent, string(rbody))
}
})
// try accessing a protected resource without a cookie
testHttpRequest(t, "GET", ProtectedResource, "", nil, true, func(t *testing.T, response *http.Response) {
if response.StatusCode != 301 && response.StatusCode != 307 {
t.Errorf("Didn't get a redirect for requesting a protected resource without a valid login cookie.")
}
})
}
func TestLoginIncorrectCreds(t *testing.T) {
var json string
json = `{"User":"daveh","Password":"p0wnnnd!","Email":"daveh@example.com"}`
testCreateNewAccount(t, json, verifyBasicSuccessFunc)
// try logging in (correctly)
json = `{"User":"daveh","Password":"p0wnnnd!"}`
testLogin(t, json, verifyLoginSuccess)
// try logging in (incorrectly)
json = `{"User":"daveh","Password":"p0wnnd!"}`
testLogin(t, json, verifyLoginFailure)
// try logging in (incorrectly again, this time with different user name)
json = `{"User":"davehh","Password":"p0wnnnd!"}`
testLogin(t, json, verifyLoginFailure)
}
func testChangePassword(t *testing.T, inputJson string, outputJsonVerifier func(*testing.T, map[string]interface{}, *http.Response)) {
testJsonHttpRequest(t, "POST", "/auth/internal/json/password/change", inputJson, nil, outputJsonVerifier)
}
func TestChangePassword(t *testing.T) {
startPass := "oopsIforgot!"
changePass := "oh no you didn't!"
var json string
json = `{"User":"forgetful","Password":"` + startPass + `","Email":"forgetful@example.com"}`
testCreateNewAccount(t, json, verifyBasicSuccessFunc)
json = `{"User":"forgetful","Password":"` + startPass + `","NewPassword":"` + changePass + `"}`
testChangePassword(t, json, verifyBasicSuccessFunc)
// try old password
json = `{"User":"forgetful","Password":"` + startPass + `"}`
testLogin(t, json, verifyLoginFailure)
// try new password
json = `{"User":"forgetful","Password":"` + changePass + `"}`
testLogin(t, json, verifyLoginSuccess)
}
func setupServer(outputHandler http.Handler, paths RedirectPaths) {
hashKey := "89408df15babfd94d259a508721e7cadf67cee8f731d8bba54c6426540e1e13de7c73ceed0c9d66571d5be8de19486431a0ac32307a6e3523a20f40a5e8f8d46"
blockKey := "8ce6d0be2d7def9a73849748ea3ba6a21e4b82920282ee50d70f685d3e04ca92"
var dbDriver string
var db *sql.DB
var err error
// Turn on driver debugging if AUTHTEST_DEBUG is 1 or true
switch os.Getenv("AUTHTEST_DEBUG") {
case "1", "true":
util.Debug(true)
default:
}
// Select Database Type
// Set the environment variable AUTHTEST_SQL_DRIVER to "postgres" or "sqlite3" (default sqlite3)
switch os.Getenv("AUTHTEST_SQL_DRIVER") {
case "postgres":
dbDriver = "postgres"
default:
dbDriver = "sqlite3"
}
log.Printf("Using database driver: %v", dbDriver)
cleanup := func() {
log.Println("Cleaning up test data (dropping user table).")
_, err = db.Exec("DROP TABLE users")
if err != nil {
log.Fatalln("Couldn't cleanup test data.")
}
}
var authDriver *DriverSql
switch dbDriver {
case "sqlite3":
sqliteVersion, _, sqliteSourceId := sqlite.Version()
log.Printf("SQLite version: %v, source id: %v\n", sqliteVersion, sqliteSourceId)
/*
authDriver = NewDriverSqlNoConnectionCache(dbDriver, func() (*sql.DB, error) {
//return sql.Open(dbDriver, "testcase.db:locked.sqlite?cache=shared&mode=rwc")
return sql.Open(dbDriver, DbFile)
})
*/
db, err = sql.Open(dbDriver, DbFile)
authDriver = NewDriverSql(dbDriver, db)
case "postgres":
pgConnectionString := fmt.Sprintf("user=%v dbname=test sslmode=disable", os.Getenv("USER"))
log.Printf("Postgres Connection String: %v\n", pgConnectionString)
db, err = sql.Open(dbDriver, pgConnectionString)
authDriver = NewDriverSql(dbDriver, db)
}
if err != nil {
log.Fatal(err)
return
}
// cleanup test data from previous runs
cleanup()
authHandler := NewAuthenticationHandler(hashKey, blockKey, paths)
authHandler.SetInternalDriver(authDriver)
authHandler.RegisterHandlers(nil, outputHandler) // in = nil : defaults to http.Handle/http.HandleFunc
log.Println("Starting webserver...")
go func() {
http.ListenAndServe(ServerHost, nil)
}()
}