-
Notifications
You must be signed in to change notification settings - Fork 78
Expand file tree
/
Copy pathserver_test.go
More file actions
589 lines (476 loc) · 16.4 KB
/
server_test.go
File metadata and controls
589 lines (476 loc) · 16.4 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
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
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
package dashboard
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"
"time"
)
const (
maxBodyBytes = 64 * 1024
maxQuestionLen = 2000
chatRateLimit = 10
)
func testServer(t *testing.T, dir string) *Server {
t.Helper()
cfg := defaultConfig()
cfg.AI.Enabled = false
cfg.Refresh.IntervalSeconds = 1
return NewServer(dir, "test", cfg, "", []byte("<head><body>__VERSION__</body>"), context.Background())
}
func testServerWithConfig(t *testing.T, dir string, cfg Config) *Server {
t.Helper()
cfg.AI.Enabled = false
return NewServer(dir, "test", cfg, "", []byte("<head><body>__VERSION__</body>"), context.Background())
}
// --- Cache coherence ---
func TestCacheCoherence_RawUpdateInvalidatesParsed(t *testing.T) {
dir := t.TempDir()
srv := testServer(t, dir)
// Write initial data.json
data1 := map[string]any{"version": "v1", "totalCostToday": 1.0}
writeJSON(t, filepath.Join(dir, "data.json"), data1)
// Prime parsed cache via getDataCached
parsed, err := srv.getDataCached()
if err != nil {
t.Fatal(err)
}
if parsed["version"] != "v1" {
t.Fatalf("expected v1, got %v", parsed["version"])
}
// Advance mtime — write new data
time.Sleep(50 * time.Millisecond)
data2 := map[string]any{"version": "v2", "totalCostToday": 2.0}
writeJSON(t, filepath.Join(dir, "data.json"), data2)
// Simulate /api/refresh reading raw cache (updates cachedDataRaw + mtime)
raw, err := srv.getDataRawCached()
if err != nil {
t.Fatal(err)
}
if !strings.Contains(string(raw), `"v2"`) {
t.Fatalf("raw cache should contain v2, got: %s", raw[:80])
}
// Now getDataCached MUST return v2, not stale v1
parsed2, err := srv.getDataCached()
if err != nil {
t.Fatal(err)
}
if parsed2["version"] != "v2" {
t.Fatalf("cache coherence bug: expected v2, got %v (stale parsed cache)", parsed2["version"])
}
}
// --- HEAD request handling ---
func TestHandleIndex_HEAD_NoBody(t *testing.T) {
dir := t.TempDir()
srv := testServer(t, dir)
req := httptest.NewRequest(http.MethodHead, "/", nil)
w := httptest.NewRecorder()
srv.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Fatalf("expected 200, got %d", w.Code)
}
if w.Body.Len() != 0 {
t.Fatalf("HEAD / should have empty body, got %d bytes", w.Body.Len())
}
if cl := w.Header().Get("Content-Length"); cl == "" {
t.Fatal("HEAD / missing Content-Length header")
}
}
func TestHandleRefresh_HEAD_NoBody(t *testing.T) {
dir := t.TempDir()
srv := testServer(t, dir)
// Create data.json so the handler has something to serve
writeJSON(t, filepath.Join(dir, "data.json"), map[string]any{"ok": true})
req := httptest.NewRequest(http.MethodHead, "/api/refresh", nil)
w := httptest.NewRecorder()
srv.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Fatalf("expected 200, got %d", w.Code)
}
// HEAD responses MUST NOT contain a body
if w.Body.Len() != 0 {
t.Fatalf("HEAD /api/refresh should have empty body, got %d bytes", w.Body.Len())
}
if cl := w.Header().Get("Content-Length"); cl == "" {
t.Fatal("HEAD /api/refresh missing Content-Length header")
}
}
func TestHandleRefresh_GET_HasBody(t *testing.T) {
dir := t.TempDir()
srv := testServer(t, dir)
writeJSON(t, filepath.Join(dir, "data.json"), map[string]any{"ok": true})
req := httptest.NewRequest(http.MethodGet, "/api/refresh", nil)
w := httptest.NewRecorder()
srv.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Fatalf("expected 200, got %d", w.Code)
}
if w.Body.Len() == 0 {
t.Fatal("GET /api/refresh should have body")
}
}
// --- Static file allowlist ---
func TestStaticFile_AllowedFile(t *testing.T) {
dir := t.TempDir()
srv := testServer(t, dir)
os.WriteFile(filepath.Join(dir, "themes.json"), []byte(`{"dark":true}`), 0644)
req := httptest.NewRequest(http.MethodGet, "/themes.json", nil)
w := httptest.NewRecorder()
srv.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Fatalf("expected 200 for themes.json, got %d", w.Code)
}
if ct := w.Header().Get("Content-Type"); ct != "application/json" {
t.Fatalf("expected application/json, got %s", ct)
}
}
func TestStaticFile_DisallowedFile(t *testing.T) {
dir := t.TempDir()
srv := testServer(t, dir)
os.WriteFile(filepath.Join(dir, "config.json"), []byte(`{"secret":true}`), 0644)
req := httptest.NewRequest(http.MethodGet, "/config.json", nil)
w := httptest.NewRecorder()
srv.ServeHTTP(w, req)
if w.Code != http.StatusNotFound {
t.Fatalf("expected 404 for non-allowlisted file, got %d", w.Code)
}
}
func TestStaticFile_PathTraversal(t *testing.T) {
dir := t.TempDir()
srv := testServer(t, dir)
// This should not reach handleStaticFile (not in allowlist)
// but test the traversal guard anyway via direct call
req := httptest.NewRequest(http.MethodGet, "/../etc/passwd", nil)
w := httptest.NewRecorder()
srv.handleStaticFile(w, req, "/../etc/passwd", "text/plain")
if w.Code != http.StatusNotFound {
t.Fatalf("expected 404 for path traversal, got %d", w.Code)
}
}
func TestStaticFile_HEAD_NoBody(t *testing.T) {
dir := t.TempDir()
srv := testServer(t, dir)
os.WriteFile(filepath.Join(dir, "themes.json"), []byte(`{"dark":true}`), 0644)
req := httptest.NewRequest(http.MethodHead, "/themes.json", nil)
w := httptest.NewRecorder()
srv.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Fatalf("expected 200, got %d", w.Code)
}
if w.Body.Len() != 0 {
t.Fatalf("HEAD should have empty body, got %d bytes", w.Body.Len())
}
}
// --- Method not allowed ---
func TestMethodNotAllowed(t *testing.T) {
dir := t.TempDir()
srv := testServer(t, dir)
req := httptest.NewRequest(http.MethodDelete, "/", nil)
w := httptest.NewRecorder()
srv.ServeHTTP(w, req)
if w.Code != http.StatusMethodNotAllowed {
t.Fatalf("expected 405, got %d", w.Code)
}
}
// --- Chat disabled ---
func TestChat_DisabledReturns503(t *testing.T) {
dir := t.TempDir()
srv := testServer(t, dir) // AI disabled by default in test helper
body := `{"question":"hello"}`
req := httptest.NewRequest(http.MethodPost, "/api/chat", strings.NewReader(body))
w := httptest.NewRecorder()
srv.ServeHTTP(w, req)
if w.Code != http.StatusServiceUnavailable {
t.Fatalf("expected 503, got %d", w.Code)
}
}
// --- Chat input validation ---
func TestChat_EmptyQuestion(t *testing.T) {
dir := t.TempDir()
cfg := defaultConfig()
cfg.AI.Enabled = true
srv := NewServer(dir, "test", cfg, "tok", []byte("<head></head>"), context.Background())
body := `{"question":" "}`
req := httptest.NewRequest(http.MethodPost, "/api/chat", strings.NewReader(body))
w := httptest.NewRecorder()
srv.ServeHTTP(w, req)
if w.Code != http.StatusBadRequest {
t.Fatalf("expected 400, got %d", w.Code)
}
}
func TestChat_QuestionTooLong(t *testing.T) {
dir := t.TempDir()
cfg := defaultConfig()
cfg.AI.Enabled = true
srv := NewServer(dir, "test", cfg, "tok", []byte("<head></head>"), context.Background())
q := strings.Repeat("a", maxQuestionLen+1)
body := `{"question":"` + q + `"}`
req := httptest.NewRequest(http.MethodPost, "/api/chat", strings.NewReader(body))
w := httptest.NewRecorder()
srv.ServeHTTP(w, req)
if w.Code != http.StatusBadRequest {
t.Fatalf("expected 400, got %d", w.Code)
}
}
func TestChat_BodyTooLarge(t *testing.T) {
dir := t.TempDir()
cfg := defaultConfig()
cfg.AI.Enabled = true
srv := NewServer(dir, "test", cfg, "tok", []byte("<head></head>"), context.Background())
body := strings.Repeat("x", maxBodyBytes+100)
req := httptest.NewRequest(http.MethodPost, "/api/chat", strings.NewReader(body))
w := httptest.NewRecorder()
srv.ServeHTTP(w, req)
if w.Code != http.StatusRequestEntityTooLarge {
t.Fatalf("expected 413, got %d", w.Code)
}
}
func TestChat_InvalidJSON(t *testing.T) {
dir := t.TempDir()
cfg := defaultConfig()
cfg.AI.Enabled = true
srv := NewServer(dir, "test", cfg, "tok", []byte("<head></head>"), context.Background())
req := httptest.NewRequest(http.MethodPost, "/api/chat", strings.NewReader("{bad"))
w := httptest.NewRecorder()
srv.ServeHTTP(w, req)
if w.Code != http.StatusBadRequest {
t.Fatalf("expected 400, got %d", w.Code)
}
}
func TestChat_MissingDataJSON_Returns503(t *testing.T) {
dir := t.TempDir()
cfg := defaultConfig()
cfg.AI.Enabled = true
srv := NewServer(dir, "test", cfg, "tok", []byte("<head></head>"), context.Background())
req := httptest.NewRequest(http.MethodPost, "/api/chat", strings.NewReader(`{"question":"hello"}`))
w := httptest.NewRecorder()
srv.ServeHTTP(w, req)
if w.Code != http.StatusServiceUnavailable {
t.Fatalf("expected 503 when data.json missing, got %d body=%s", w.Code, w.Body.String())
}
}
func TestChat_InvalidDataJSON_Returns500(t *testing.T) {
dir := t.TempDir()
cfg := defaultConfig()
cfg.AI.Enabled = true
srv := NewServer(dir, "test", cfg, "tok", []byte("<head></head>"), context.Background())
if err := os.WriteFile(filepath.Join(dir, "data.json"), []byte("{bad json"), 0o644); err != nil {
t.Fatal(err)
}
req := httptest.NewRequest(http.MethodPost, "/api/chat", strings.NewReader(`{"question":"hello"}`))
w := httptest.NewRecorder()
srv.ServeHTTP(w, req)
if w.Code != http.StatusInternalServerError {
t.Fatalf("expected 500 for invalid data.json, got %d body=%s", w.Code, w.Body.String())
}
}
func TestChat_NullDataJSON_Returns500(t *testing.T) {
dir := t.TempDir()
cfg := defaultConfig()
cfg.AI.Enabled = true
srv := NewServer(dir, "test", cfg, "tok", []byte("<head></head>"), context.Background())
nullData, err := os.ReadFile(filepath.Join("testdata", "dashboard", "data-null.json"))
if err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(dir, "data.json"), nullData, 0o644); err != nil {
t.Fatal(err)
}
req := httptest.NewRequest(http.MethodPost, "/api/chat", strings.NewReader(`{"question":"hello"}`))
w := httptest.NewRecorder()
srv.ServeHTTP(w, req)
if w.Code != http.StatusInternalServerError {
t.Fatalf("expected 500 for null data.json, got %d body=%s", w.Code, w.Body.String())
}
}
func TestGetDataCached_NullDataJSON_ReturnsError(t *testing.T) {
dir := t.TempDir()
srv := testServer(t, dir)
nullData, err := os.ReadFile(filepath.Join("testdata", "dashboard", "data-null.json"))
if err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(dir, "data.json"), nullData, 0o644); err != nil {
t.Fatal(err)
}
parsed, err := srv.getDataCached()
if err == nil {
t.Fatal("expected null data.json to be rejected")
}
if parsed != nil {
t.Fatalf("expected parsed data to be nil, got %#v", parsed)
}
}
// --- Index rendering ---
func TestIndex_VersionInjected(t *testing.T) {
dir := t.TempDir()
srv := NewServer(dir, "1.2.3", defaultConfig(), "", []byte("<head><body>__VERSION__</body>"), context.Background())
req := httptest.NewRequest(http.MethodGet, "/", nil)
w := httptest.NewRecorder()
srv.ServeHTTP(w, req)
if !strings.Contains(w.Body.String(), "1.2.3") {
t.Fatal("version not injected into index.html")
}
}
func TestIndex_RuntimeInjected(t *testing.T) {
dir := t.TempDir()
srv := NewServer(dir, "1.0", defaultConfig(), "", []byte("<head><body>__RUNTIME__ · v__VERSION__</body>"), context.Background())
req := httptest.NewRequest(http.MethodGet, "/", nil)
w := httptest.NewRecorder()
srv.ServeHTTP(w, req)
body := w.Body.String()
if !strings.Contains(body, "Go") {
t.Fatal("runtime badge 'Go' not injected into index.html")
}
if strings.Contains(body, "__RUNTIME__") {
t.Fatal("__RUNTIME__ placeholder not replaced")
}
}
func TestIndex_ThemeMetaInjected(t *testing.T) {
dir := t.TempDir()
cfg := defaultConfig()
cfg.Theme.Preset = "solar"
srv := NewServer(dir, "1.0", cfg, "", []byte("<head><body></body>"), context.Background())
req := httptest.NewRequest(http.MethodGet, "/", nil)
w := httptest.NewRecorder()
srv.ServeHTTP(w, req)
if !strings.Contains(w.Body.String(), `content="solar"`) {
t.Fatal("theme preset not injected into index.html")
}
}
// --- CORS ---
func TestCORS_LocalhostOriginReflected(t *testing.T) {
dir := t.TempDir()
srv := testServer(t, dir)
writeJSON(t, filepath.Join(dir, "data.json"), map[string]any{"ok": true})
req := httptest.NewRequest(http.MethodGet, "/api/refresh", nil)
req.Header.Set("Origin", "http://localhost:3000")
w := httptest.NewRecorder()
srv.ServeHTTP(w, req)
if acao := w.Header().Get("Access-Control-Allow-Origin"); acao != "http://localhost:3000" {
t.Fatalf("expected origin reflected, got %q", acao)
}
}
func TestCORS_ExternalOriginDefaulted(t *testing.T) {
dir := t.TempDir()
srv := testServer(t, dir)
writeJSON(t, filepath.Join(dir, "data.json"), map[string]any{"ok": true})
req := httptest.NewRequest(http.MethodGet, "/api/refresh", nil)
req.Header.Set("Origin", "http://evil.com")
w := httptest.NewRecorder()
srv.ServeHTTP(w, req)
acao := w.Header().Get("Access-Control-Allow-Origin")
if acao == "http://evil.com" {
t.Fatal("external origin should NOT be reflected")
}
}
// --- Data missing ---
func TestRefresh_DataMissing_Returns503(t *testing.T) {
dir := t.TempDir()
t.Setenv("OPENCLAW_HOME", t.TempDir())
prev := refreshCollectorFunc
defer func() { refreshCollectorFunc = prev }()
refreshCollectorFunc = func(ctx context.Context, dashboardDir, openclawPath string, cfgOpt ...Config) error {
return os.ErrNotExist
}
srv := testServer(t, dir)
req := httptest.NewRequest(http.MethodGet, "/api/refresh", nil)
w := httptest.NewRecorder()
srv.ServeHTTP(w, req)
if w.Code != http.StatusServiceUnavailable {
t.Fatalf("expected 503 when data.json missing, got %d", w.Code)
}
}
func TestRefresh_DataMissing_WaitsForRefreshAndReturnsFreshData(t *testing.T) {
dir := t.TempDir()
openclawHome := t.TempDir()
t.Setenv("OPENCLAW_HOME", openclawHome)
prev := refreshCollectorFunc
defer func() { refreshCollectorFunc = prev }()
refreshCollectorFunc = func(ctx context.Context, dashboardDir, openclawPath string, cfgOpt ...Config) error {
if dashboardDir != dir {
t.Fatalf("unexpected dashboard dir: %s", dashboardDir)
}
if openclawPath != openclawHome {
t.Fatalf("unexpected openclaw path: %s", openclawPath)
}
time.Sleep(20 * time.Millisecond)
return os.WriteFile(filepath.Join(dashboardDir, "data.json"), []byte(`{"ok":true}`), 0o644)
}
srv := testServer(t, dir)
req := httptest.NewRequest(http.MethodGet, "/api/refresh", nil)
w := httptest.NewRecorder()
srv.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Fatalf("expected 200 after waiting for initial refresh, got %d body=%s", w.Code, w.Body.String())
}
if !strings.Contains(w.Body.String(), `"ok":true`) {
t.Fatalf("expected fresh data.json body, got %s", w.Body.String())
}
}
// --- Rate limiting ---
func TestChat_RateLimitExceeded(t *testing.T) {
dir := t.TempDir()
cfg := defaultConfig()
cfg.AI.Enabled = true
srv := NewServer(dir, "test", cfg, "tok", []byte("<head></head>"), context.Background())
// Send chatRateLimit requests — all should be accepted (400 because no gateway, but not 429)
for i := range chatRateLimit {
body := `{"question":"hello"}`
req := httptest.NewRequest(http.MethodPost, "/api/chat", strings.NewReader(body))
req.RemoteAddr = "192.168.1.1:12345"
w := httptest.NewRecorder()
srv.ServeHTTP(w, req)
if w.Code == http.StatusTooManyRequests {
t.Fatalf("request %d should not be rate limited", i+1)
}
}
// Next request should be rate limited
body := `{"question":"one more"}`
req := httptest.NewRequest(http.MethodPost, "/api/chat", strings.NewReader(body))
req.RemoteAddr = "192.168.1.1:12345"
w := httptest.NewRecorder()
srv.ServeHTTP(w, req)
if w.Code != http.StatusTooManyRequests {
t.Fatalf("expected 429 after %d requests, got %d", chatRateLimit, w.Code)
}
if ra := w.Header().Get("Retry-After"); ra != "60" {
t.Errorf("expected Retry-After: 60, got %q", ra)
}
}
func TestChat_RateLimitPerIP(t *testing.T) {
dir := t.TempDir()
cfg := defaultConfig()
cfg.AI.Enabled = true
srv := NewServer(dir, "test", cfg, "tok", []byte("<head></head>"), context.Background())
// Exhaust rate limit for IP A
for range chatRateLimit {
req := httptest.NewRequest(http.MethodPost, "/api/chat", strings.NewReader(`{"question":"hi"}`))
req.RemoteAddr = "10.0.0.1:1111"
w := httptest.NewRecorder()
srv.ServeHTTP(w, req)
}
// IP B should still be allowed
req := httptest.NewRequest(http.MethodPost, "/api/chat", strings.NewReader(`{"question":"hi"}`))
req.RemoteAddr = "10.0.0.2:2222"
w := httptest.NewRecorder()
srv.ServeHTTP(w, req)
if w.Code == http.StatusTooManyRequests {
t.Fatal("different IP should not be rate limited")
}
}
// --- Helpers ---
func writeJSON(t *testing.T, path string, v any) {
t.Helper()
data, err := json.Marshal(v)
if err != nil {
t.Fatal(err)
}
if err := os.WriteFile(path, data, 0644); err != nil {
t.Fatal(err)
}
}