-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauth_test.go
More file actions
378 lines (337 loc) · 11.2 KB
/
Copy pathauth_test.go
File metadata and controls
378 lines (337 loc) · 11.2 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
package main
import (
"bytes"
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
)
func setupTestServer(t *testing.T) *httptest.Server {
t.Helper()
initDB(":memory:")
cfg = &Config{
AccessSecret: "test-access-secret-that-is-32-chars!!",
RefreshSecret: "test-refresh-secret-that-is-32-chars!",
CookieSecure: false,
}
mux := http.NewServeMux()
mux.HandleFunc("GET /auth/status", handleAuthStatus)
mux.Handle("POST /auth/register", http.HandlerFunc(handleRegister))
mux.Handle("POST /auth/login", http.HandlerFunc(handleLogin))
mux.Handle("POST /auth/logout", requireAuthMiddleware(http.HandlerFunc(handleLogout)))
mux.Handle("POST /account/password", requireAuthMiddleware(http.HandlerFunc(handlePasswordChange)))
mux.Handle("GET /account/me", requireAuthMiddleware(http.HandlerFunc(handleMe)))
mux.HandleFunc("GET /health", handleHealth)
return httptest.NewServer(mux)
}
func jsonPost(url string, body any, cookies []*http.Cookie) (*http.Response, map[string]any) {
data, _ := json.Marshal(body)
req, _ := http.NewRequest(http.MethodPost, url, bytes.NewReader(data))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Accept", "application/json")
for _, c := range cookies {
req.AddCookie(c)
}
client := &http.Client{
CheckRedirect: func(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse
},
}
resp, err := client.Do(req)
if err != nil {
return nil, nil
}
defer resp.Body.Close()
var result map[string]any
json.NewDecoder(resp.Body).Decode(&result)
return resp, result
}
func jsonGet(url string, cookies []*http.Cookie) (*http.Response, map[string]any) {
req, _ := http.NewRequest(http.MethodGet, url, nil)
req.Header.Set("Accept", "application/json")
for _, c := range cookies {
req.AddCookie(c)
}
client := &http.Client{
CheckRedirect: func(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse
},
}
resp, err := client.Do(req)
if err != nil {
return nil, nil
}
defer resp.Body.Close()
var result map[string]any
json.NewDecoder(resp.Body).Decode(&result)
return resp, result
}
func TestRegisterAndLogin(t *testing.T) {
ts := setupTestServer(t)
defer ts.Close()
// Register
resp, body := jsonPost(ts.URL+"/auth/register", map[string]any{
"email": "user@example.com",
"password": "securepassword123",
}, nil)
if resp.StatusCode != http.StatusCreated {
t.Fatalf("register: status = %d, want %d", resp.StatusCode, http.StatusCreated)
}
if body["success"] != true {
t.Fatalf("register: success = %v, want true", body["success"])
}
// Login
resp, body = jsonPost(ts.URL+"/auth/login", map[string]any{
"email": "user@example.com",
"password": "securepassword123",
}, nil)
if resp.StatusCode != http.StatusOK {
t.Fatalf("login: status = %d, want %d", resp.StatusCode, http.StatusOK)
}
if body["success"] != true {
t.Fatalf("login: success = %v, want true", body["success"])
}
cookies := resp.Cookies()
if len(cookies) == 0 {
t.Fatal("login: no cookies set")
}
// GET /account/me with cookies
resp, body = jsonGet(ts.URL+"/account/me", cookies)
if resp.StatusCode != http.StatusOK {
t.Fatalf("me: status = %d, want %d", resp.StatusCode, http.StatusOK)
}
email, _ := body["email"].(string)
if email != "user@example.com" {
t.Errorf("me: email = %q, want %q", email, "user@example.com")
}
}
func TestRegisterDuplicate(t *testing.T) {
ts := setupTestServer(t)
defer ts.Close()
payload := map[string]any{
"email": "dup@example.com",
"password": "securepassword123",
}
// First registration
resp, _ := jsonPost(ts.URL+"/auth/register", payload, nil)
if resp.StatusCode != http.StatusCreated {
t.Fatalf("first register: status = %d, want %d", resp.StatusCode, http.StatusCreated)
}
// Second registration with same email — still 201 (anti-enumeration)
resp, body := jsonPost(ts.URL+"/auth/register", payload, nil)
if resp.StatusCode != http.StatusCreated {
t.Fatalf("second register: status = %d, want %d", resp.StatusCode, http.StatusCreated)
}
if body["success"] != true {
t.Errorf("second register: success = %v, want true", body["success"])
}
}
func TestRegisterInvalidEmail(t *testing.T) {
ts := setupTestServer(t)
defer ts.Close()
resp, body := jsonPost(ts.URL+"/auth/register", map[string]any{
"email": "not-an-email",
"password": "securepassword123",
}, nil)
if resp.StatusCode != http.StatusBadRequest {
t.Fatalf("register invalid email: status = %d, want %d", resp.StatusCode, http.StatusBadRequest)
}
code, _ := body["code"].(string)
if code != "VALIDATION_ERROR" {
t.Errorf("register invalid email: code = %q, want %q", code, "VALIDATION_ERROR")
}
}
func TestRegisterRequiresToken(t *testing.T) {
ts := setupTestServer(t)
defer ts.Close()
cfg.RegistrationToken = "my-secret-token"
// Register without token — 403
resp, body := jsonPost(ts.URL+"/auth/register", map[string]any{
"email": "token@example.com",
"password": "securepassword123",
}, nil)
if resp.StatusCode != http.StatusForbidden {
t.Fatalf("register without token: status = %d, want %d", resp.StatusCode, http.StatusForbidden)
}
code, _ := body["code"].(string)
if code != "INVALID_TOKEN" {
t.Errorf("register without token: code = %q, want %q", code, "INVALID_TOKEN")
}
// Register with correct token — 201
resp, body = jsonPost(ts.URL+"/auth/register", map[string]any{
"email": "token@example.com",
"password": "securepassword123",
"registrationToken": "my-secret-token",
}, nil)
if resp.StatusCode != http.StatusCreated {
t.Fatalf("register with token: status = %d, want %d", resp.StatusCode, http.StatusCreated)
}
if body["success"] != true {
t.Errorf("register with token: success = %v, want true", body["success"])
}
}
func TestLoginInvalidCredentials(t *testing.T) {
ts := setupTestServer(t)
defer ts.Close()
// Register first
resp, _ := jsonPost(ts.URL+"/auth/register", map[string]any{
"email": "cred@example.com",
"password": "correctpassword1",
}, nil)
if resp.StatusCode != http.StatusCreated {
t.Fatalf("register: status = %d, want %d", resp.StatusCode, http.StatusCreated)
}
// Login with wrong password
resp, body := jsonPost(ts.URL+"/auth/login", map[string]any{
"email": "cred@example.com",
"password": "wrongpassword12",
}, nil)
if resp.StatusCode != http.StatusUnauthorized {
t.Fatalf("login wrong pw: status = %d, want %d", resp.StatusCode, http.StatusUnauthorized)
}
code, _ := body["code"].(string)
if code != "INVALID_CREDENTIALS" {
t.Errorf("login wrong pw: code = %q, want %q", code, "INVALID_CREDENTIALS")
}
}
func TestLoginNonexistentUser(t *testing.T) {
ts := setupTestServer(t)
defer ts.Close()
resp, body := jsonPost(ts.URL+"/auth/login", map[string]any{
"email": "nobody@example.com",
"password": "somepassword12",
}, nil)
if resp.StatusCode != http.StatusUnauthorized {
t.Fatalf("login nonexistent: status = %d, want %d", resp.StatusCode, http.StatusUnauthorized)
}
code, _ := body["code"].(string)
if code != "INVALID_CREDENTIALS" {
t.Errorf("login nonexistent: code = %q, want %q", code, "INVALID_CREDENTIALS")
}
}
func TestLogout(t *testing.T) {
ts := setupTestServer(t)
defer ts.Close()
// Register
jsonPost(ts.URL+"/auth/register", map[string]any{
"email": "logout@example.com",
"password": "securepassword123",
}, nil)
// Login
resp, _ := jsonPost(ts.URL+"/auth/login", map[string]any{
"email": "logout@example.com",
"password": "securepassword123",
}, nil)
cookies := resp.Cookies()
if len(cookies) == 0 {
t.Fatal("login: no cookies set")
}
// Logout
resp, body := jsonPost(ts.URL+"/auth/logout", nil, cookies)
if resp.StatusCode != http.StatusOK {
t.Fatalf("logout: status = %d, want %d", resp.StatusCode, http.StatusOK)
}
if body["success"] != true {
t.Errorf("logout: success = %v, want true", body["success"])
}
// /account/me should now return 401 or 403 (session revoked)
resp, _ = jsonGet(ts.URL+"/account/me", cookies)
if resp.StatusCode != http.StatusForbidden && resp.StatusCode != http.StatusUnauthorized {
t.Errorf("me after logout: status = %d, want 401 or 403", resp.StatusCode)
}
}
func TestPasswordChange(t *testing.T) {
ts := setupTestServer(t)
defer ts.Close()
// Register and login
jsonPost(ts.URL+"/auth/register", map[string]any{
"email": "pwchange@example.com",
"password": "oldpassword1234",
}, nil)
resp, _ := jsonPost(ts.URL+"/auth/login", map[string]any{
"email": "pwchange@example.com",
"password": "oldpassword1234",
}, nil)
cookies := resp.Cookies()
if len(cookies) == 0 {
t.Fatal("login: no cookies set")
}
// Change password
resp, body := jsonPost(ts.URL+"/account/password", map[string]any{
"currentPassword": "oldpassword1234",
"newPassword": "newpassword5678",
}, cookies)
if resp.StatusCode != http.StatusOK {
t.Fatalf("password change: status = %d, want %d", resp.StatusCode, http.StatusOK)
}
if body["success"] != true {
t.Errorf("password change: success = %v, want true", body["success"])
}
// Old cookies should no longer work (all sessions revoked)
resp, _ = jsonGet(ts.URL+"/account/me", cookies)
if resp.StatusCode != http.StatusForbidden && resp.StatusCode != http.StatusUnauthorized {
t.Errorf("me after pw change: status = %d, want 401 or 403", resp.StatusCode)
}
}
func TestPasswordChangeSamePassword(t *testing.T) {
ts := setupTestServer(t)
defer ts.Close()
// Register and login
jsonPost(ts.URL+"/auth/register", map[string]any{
"email": "samepw@example.com",
"password": "thepassword1234",
}, nil)
resp, _ := jsonPost(ts.URL+"/auth/login", map[string]any{
"email": "samepw@example.com",
"password": "thepassword1234",
}, nil)
cookies := resp.Cookies()
if len(cookies) == 0 {
t.Fatal("login: no cookies set")
}
// Try to change to the same password
resp, body := jsonPost(ts.URL+"/account/password", map[string]any{
"currentPassword": "thepassword1234",
"newPassword": "thepassword1234",
}, cookies)
if resp.StatusCode != http.StatusBadRequest {
t.Fatalf("same password: status = %d, want %d", resp.StatusCode, http.StatusBadRequest)
}
code, _ := body["code"].(string)
if code != "VALIDATION_ERROR" {
t.Errorf("same password: code = %q, want %q", code, "VALIDATION_ERROR")
}
}
func TestAuthStatus_Unregistered(t *testing.T) {
ts := setupTestServer(t)
defer ts.Close()
resp, body := jsonGet(ts.URL+"/auth/status", nil)
if resp.StatusCode != http.StatusOK {
t.Fatalf("auth status: status = %d, want %d", resp.StatusCode, http.StatusOK)
}
registered, _ := body["registered"].(bool)
if registered {
t.Errorf("auth status: registered = %v, want false", registered)
}
}
func TestAuthStatus_Registered(t *testing.T) {
ts := setupTestServer(t)
defer ts.Close()
// Register
resp, _ := jsonPost(ts.URL+"/auth/register", map[string]any{
"email": "status@example.com",
"password": "securepassword123",
}, nil)
if resp.StatusCode != http.StatusCreated {
t.Fatalf("register: status = %d, want %d", resp.StatusCode, http.StatusCreated)
}
// Check status
resp, body := jsonGet(ts.URL+"/auth/status", nil)
if resp.StatusCode != http.StatusOK {
t.Fatalf("auth status: status = %d, want %d", resp.StatusCode, http.StatusOK)
}
registered, _ := body["registered"].(bool)
if !registered {
t.Errorf("auth status: registered = %v, want true", registered)
}
}