Repository navigation
Expand file tree
/
Copy pathweb_admin_auth_test.go
More file actions
431 lines (377 loc) · 14.6 KB
/
Copy pathweb_admin_auth_test.go
File metadata and controls
431 lines (377 loc) · 14.6 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
package main
import (
"bytes"
"codeswitch/services"
"crypto/tls"
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
)
func newTestWebRuntime(t *testing.T) *appRuntime {
t.Helper()
t.Setenv("HOME", t.TempDir())
appSettings := services.NewAppSettingsService(nil)
adminSecurity, err := newAdminSecurity(appSettings)
if err != nil {
t.Fatalf("failed to create admin security: %v", err)
}
return &appRuntime{
adminAddr: "127.0.0.1:0",
staticDir: t.TempDir(),
eventHub: services.NewEventHub(),
appService: &AppService{},
appSettings: appSettings,
adminAuth: services.NewAdminAuthService(appSettings),
adminSecurity: adminSecurity,
codexRelayKeys: services.NewCodexRelayKeyService(),
}
}
type requestOptions struct {
Cookies []*http.Cookie
Headers map[string]string
RemoteAddr string
Host string
TLS bool
}
func performRequest(t *testing.T, handler http.Handler, method, path string, body any, cookies ...*http.Cookie) *httptest.ResponseRecorder {
return performRequestWithOptions(t, handler, method, path, body, requestOptions{
Cookies: cookies,
RemoteAddr: "127.0.0.1:12345",
})
}
func performRequestWithOptions(t *testing.T, handler http.Handler, method, path string, body any, options requestOptions) *httptest.ResponseRecorder {
t.Helper()
var requestBody *bytes.Reader
if body == nil {
requestBody = bytes.NewReader(nil)
} else {
payload, err := json.Marshal(body)
if err != nil {
t.Fatalf("failed to encode request body: %v", err)
}
requestBody = bytes.NewReader(payload)
}
req := httptest.NewRequest(method, path, requestBody)
if options.RemoteAddr != "" {
req.RemoteAddr = options.RemoteAddr
}
if options.Host != "" {
req.Host = options.Host
}
if options.TLS {
req.TLS = &tls.ConnectionState{}
}
if body != nil {
req.Header.Set("Content-Type", "application/json")
}
for key, value := range options.Headers {
req.Header.Set(key, value)
}
for _, cookie := range options.Cookies {
req.AddCookie(cookie)
}
recorder := httptest.NewRecorder()
handler.ServeHTTP(recorder, req)
return recorder
}
func decodeJSON[T any](t *testing.T, recorder *httptest.ResponseRecorder) T {
t.Helper()
var value T
if err := json.Unmarshal(recorder.Body.Bytes(), &value); err != nil {
t.Fatalf("failed to decode response body %q: %v", recorder.Body.String(), err)
}
return value
}
func TestAdminSessionCookieNameIncludesHostAndPort(t *testing.T) {
rt := newTestWebRuntime(t)
req8080 := httptest.NewRequest(http.MethodGet, "http://localhost:8080/api/admin/status", nil)
req8081 := httptest.NewRequest(http.MethodGet, "http://localhost:8081/api/admin/status", nil)
name8080 := adminSessionCookieNameForRequest(req8080, rt.adminSecurity)
name8081 := adminSessionCookieNameForRequest(req8081, rt.adminSecurity)
if name8080 != "code_switch_admin_session_localhost_8080" {
t.Fatalf("expected 8080 cookie name to include port, got %q", name8080)
}
if name8081 != "code_switch_admin_session_localhost_8081" {
t.Fatalf("expected 8081 cookie name to include port, got %q", name8081)
}
if name8080 == name8081 {
t.Fatalf("expected distinct cookie names for different ports, got %q", name8080)
}
}
func TestAdminServerProtectsRoutes(t *testing.T) {
rt := newTestWebRuntime(t)
server := newAdminServer(rt)
health := performRequest(t, server.Handler, http.MethodGet, "/healthz", nil)
if health.Code != http.StatusOK {
t.Fatalf("expected /healthz 200, got %d", health.Code)
}
ready := performRequest(t, server.Handler, http.MethodGet, "/readyz", nil)
if ready.Code != http.StatusOK {
t.Fatalf("expected /readyz 200, got %d", ready.Code)
}
status := performRequest(t, server.Handler, http.MethodGet, "/api/admin/status", nil)
if status.Code != http.StatusOK {
t.Fatalf("expected /api/admin/status 200, got %d", status.Code)
}
var authStatus services.AdminAuthStatus
authStatus = decodeJSON[services.AdminAuthStatus](t, status)
if authStatus.Initialized || authStatus.Authenticated {
t.Fatalf("expected initial admin status to be unauthenticated, got %+v", authStatus)
}
call := performRequest(t, server.Handler, http.MethodPost, "/api/wails/call", map[string]any{
"name": "codeswitch/services.AppSettingsService.GetAppSettings",
"args": []any{},
})
if call.Code != http.StatusUnauthorized {
t.Fatalf("expected unauthenticated /api/wails/call to return 401, got %d", call.Code)
}
events := performRequest(t, server.Handler, http.MethodGet, "/api/wails/events", nil)
if events.Code != http.StatusUnauthorized {
t.Fatalf("expected unauthenticated /api/wails/events to return 401, got %d", events.Code)
}
}
func TestAdminServerInitializeAndManageCodexKeys(t *testing.T) {
rt := newTestWebRuntime(t)
server := newAdminServer(rt)
if _, _, err := rt.adminAuth.InitializeAdmin("admin", "password123"); err != nil {
t.Fatalf("failed to seed user: %v", err)
}
login := performRequest(t, server.Handler, http.MethodPost, "/api/admin/login", map[string]string{
"username": "admin",
"password": "password123",
})
if login.Code != http.StatusOK {
t.Fatalf("expected login 200, got %d: %s", login.Code, login.Body.String())
}
cookies := login.Result().Cookies()
if len(cookies) == 0 {
t.Fatal("expected login response to set an admin session cookie")
}
adminCookie := cookies[0]
wailsCall := performRequest(t, server.Handler, http.MethodPost, "/api/wails/call", map[string]any{
"name": "codeswitch/services.AppSettingsService.GetAppSettings",
"args": []any{},
}, adminCookie)
if wailsCall.Code != http.StatusOK {
t.Fatalf("expected authenticated /api/wails/call 200, got %d: %s", wailsCall.Code, wailsCall.Body.String())
}
protectedKeys := performRequest(t, server.Handler, http.MethodGet, "/api/admin/codex-keys", nil)
if protectedKeys.Code != http.StatusUnauthorized {
t.Fatalf("expected unauthenticated codex key list 401, got %d", protectedKeys.Code)
}
createFirst := performRequest(t, server.Handler, http.MethodPost, "/api/admin/codex-keys", map[string]string{
"name": "local-dev",
}, adminCookie)
if createFirst.Code != http.StatusOK {
t.Fatalf("expected create first key 200, got %d: %s", createFirst.Code, createFirst.Body.String())
}
firstKey := decodeJSON[services.CodexRelayKeyCreateResult](t, createFirst)
if firstKey.Key == "" {
t.Fatal("expected create first key response to include secret")
}
secret := performRequest(t, server.Handler, http.MethodGet, "/api/admin/codex-keys/"+firstKey.ID+"/secret", nil, adminCookie)
if secret.Code != http.StatusOK {
t.Fatalf("expected get key secret 200, got %d: %s", secret.Code, secret.Body.String())
}
secretPayload := decodeJSON[map[string]string](t, secret)
if secretPayload["key"] != firstKey.Key {
t.Fatalf("expected returned secret to match created key")
}
deleteLast := performRequest(t, server.Handler, http.MethodDelete, "/api/admin/codex-keys/"+firstKey.ID, nil, adminCookie)
if deleteLast.Code != http.StatusNoContent {
t.Fatalf("expected deleting own key to succeed, got %d: %s", deleteLast.Code, deleteLast.Body.String())
}
createSecond := performRequest(t, server.Handler, http.MethodPost, "/api/admin/codex-keys", map[string]string{
"name": "ci",
}, adminCookie)
if createSecond.Code != http.StatusOK {
t.Fatalf("expected create second key 200, got %d: %s", createSecond.Code, createSecond.Body.String())
}
listKeys := performRequest(t, server.Handler, http.MethodGet, "/api/admin/codex-keys", nil, adminCookie)
if listKeys.Code != http.StatusOK {
t.Fatalf("expected authenticated codex key list 200, got %d: %s", listKeys.Code, listKeys.Body.String())
}
var listPayload struct {
Keys []services.CodexRelayKeyListItem `json:"keys"`
}
listPayload = decodeJSON[struct {
Keys []services.CodexRelayKeyListItem `json:"keys"`
}](t, listKeys)
if len(listPayload.Keys) != 1 {
t.Fatalf("expected one remaining key, got %+v", listPayload.Keys)
}
if listPayload.Keys[0].ID == firstKey.ID {
t.Fatalf("expected deleted key %q to be absent from list", firstKey.ID)
}
}
func TestAdminSessionCookiesAreIsolatedPerHost(t *testing.T) {
rt := newTestWebRuntime(t)
server := newAdminServer(rt)
if _, _, err := rt.adminAuth.InitializeAdmin("admin", "password123"); err != nil {
t.Fatalf("failed to seed user: %v", err)
}
login := performRequestWithOptions(t, server.Handler, http.MethodPost, "/api/admin/login", map[string]string{
"username": "admin",
"password": "password123",
}, requestOptions{
RemoteAddr: "127.0.0.1:12345",
Host: "localhost:8080",
})
if login.Code != http.StatusOK {
t.Fatalf("expected login on localhost:8080 to return 200, got %d: %s", login.Code, login.Body.String())
}
cookies := login.Result().Cookies()
if len(cookies) == 0 {
t.Fatal("expected login response to set an admin session cookie")
}
adminCookie := cookies[0]
if adminCookie.Name != "code_switch_admin_session_localhost_8080" {
t.Fatalf("expected host-specific cookie name, got %q", adminCookie.Name)
}
sameHost := performRequestWithOptions(t, server.Handler, http.MethodPost, "/api/wails/call", map[string]any{
"name": "codeswitch/services.AppSettingsService.GetAppSettings",
"args": []any{},
}, requestOptions{
Cookies: []*http.Cookie{adminCookie},
RemoteAddr: "127.0.0.1:12345",
Host: "localhost:8080",
})
if sameHost.Code != http.StatusOK {
t.Fatalf("expected host-matched cookie to authenticate, got %d: %s", sameHost.Code, sameHost.Body.String())
}
otherHost := performRequestWithOptions(t, server.Handler, http.MethodPost, "/api/wails/call", map[string]any{
"name": "codeswitch/services.AppSettingsService.GetAppSettings",
"args": []any{},
}, requestOptions{
Cookies: []*http.Cookie{adminCookie},
RemoteAddr: "127.0.0.1:12345",
Host: "localhost:8081",
})
if otherHost.Code != http.StatusUnauthorized {
t.Fatalf("expected localhost:8081 to reject localhost:8080 cookie, got %d: %s", otherHost.Code, otherHost.Body.String())
}
}
func TestAdminServerRejectsInsecurePublicHTTP(t *testing.T) {
rt := newTestWebRuntime(t)
server := newAdminServer(rt)
status := performRequestWithOptions(t, server.Handler, http.MethodGet, "/api/admin/status", nil, requestOptions{
RemoteAddr: "203.0.113.25:54321",
})
if status.Code != http.StatusForbidden {
t.Fatalf("expected insecure public request to return 403, got %d: %s", status.Code, status.Body.String())
}
}
func TestAdminServerAllowsTrustedProxyHTTPS(t *testing.T) {
rt := newTestWebRuntime(t)
server := newAdminServer(rt)
status := performRequestWithOptions(t, server.Handler, http.MethodGet, "/api/admin/status", nil, requestOptions{
RemoteAddr: "127.0.0.1:8081",
Host: "admin.example.com",
Headers: map[string]string{
"X-Forwarded-For": "203.0.113.25",
"X-Forwarded-Proto": "https",
"X-Forwarded-Host": "admin.example.com",
},
})
if status.Code != http.StatusOK {
t.Fatalf("expected trusted proxy https request to return 200, got %d: %s", status.Code, status.Body.String())
}
}
func TestAdminServerRemoteInitializeRequiresSetupToken(t *testing.T) {
rt := newTestWebRuntime(t)
server := newAdminServer(rt)
withoutToken := performRequestWithOptions(t, server.Handler, http.MethodPost, "/api/admin/initialize", map[string]string{
"username": "admin",
"password": "password123",
}, requestOptions{
RemoteAddr: "127.0.0.1:8081",
Host: "admin.example.com",
Headers: map[string]string{
"Origin": "https://admin.example.com",
"X-Forwarded-For": "203.0.113.25",
"X-Forwarded-Proto": "https",
"X-Forwarded-Host": "admin.example.com",
},
})
if withoutToken.Code != http.StatusForbidden {
t.Fatalf("expected remote initialize without setup token to return 403, got %d: %s", withoutToken.Code, withoutToken.Body.String())
}
withToken := performRequestWithOptions(t, server.Handler, http.MethodPost, "/api/admin/initialize", map[string]string{
"username": "admin",
"password": "password123",
"setupToken": rt.adminSecurity.setupToken,
}, requestOptions{
RemoteAddr: "127.0.0.1:8081",
Host: "admin.example.com",
Headers: map[string]string{
"Origin": "https://admin.example.com",
"X-Forwarded-For": "203.0.113.25",
"X-Forwarded-Proto": "https",
"X-Forwarded-Host": "admin.example.com",
},
})
if withToken.Code != http.StatusForbidden {
t.Fatalf("expected remote initialize with setup token to remain disabled, got %d: %s", withToken.Code, withToken.Body.String())
}
}
func TestAdminServerRateLimitsLogin(t *testing.T) {
rt := newTestWebRuntime(t)
server := newAdminServer(rt)
if _, _, err := rt.adminAuth.InitializeAdmin("admin", "password123"); err != nil {
t.Fatalf("failed to seed user: %v", err)
}
for i := 0; i < services.AdminAuthMaxFailures; i++ {
response := performRequest(t, server.Handler, http.MethodPost, "/api/admin/login", map[string]string{
"username": "admin",
"password": "wrong-password",
})
if i < services.AdminAuthMaxFailures-1 && response.Code != http.StatusUnauthorized {
t.Fatalf("expected attempt %d to return 401, got %d: %s", i+1, response.Code, response.Body.String())
}
}
limited := performRequest(t, server.Handler, http.MethodPost, "/api/admin/login", map[string]string{
"username": "admin",
"password": "password123",
})
if limited.Code != http.StatusTooManyRequests {
t.Fatalf("expected rate-limited login to return 429, got %d: %s", limited.Code, limited.Body.String())
}
if limited.Header().Get("Retry-After") == "" {
t.Fatal("expected rate-limited response to include Retry-After header")
}
}
func TestAdminServerRejectsCrossSiteAdminMutation(t *testing.T) {
rt := newTestWebRuntime(t)
server := newAdminServer(rt)
if _, _, err := rt.adminAuth.InitializeAdmin("admin", "password123"); err != nil {
t.Fatalf("failed to seed user: %v", err)
}
login := performRequestWithOptions(t, server.Handler, http.MethodPost, "/api/admin/login", map[string]string{
"username": "admin",
"password": "password123",
}, requestOptions{
RemoteAddr: "127.0.0.1:12345",
Host: "example.com",
Headers: map[string]string{
"Origin": "http://example.com",
},
})
if login.Code != http.StatusOK {
t.Fatalf("expected login 200, got %d: %s", login.Code, login.Body.String())
}
adminCookie := login.Result().Cookies()[0]
crossSite := performRequestWithOptions(t, server.Handler, http.MethodPost, "/api/admin/codex-keys", map[string]string{
"name": "evil",
}, requestOptions{
Cookies: []*http.Cookie{adminCookie},
RemoteAddr: "127.0.0.1:12345",
Host: "example.com",
Headers: map[string]string{
"Origin": "https://evil.example",
},
})
if crossSite.Code != http.StatusForbidden {
t.Fatalf("expected cross-site mutation to return 403, got %d: %s", crossSite.Code, crossSite.Body.String())
}
}