package app import ( "context" "encoding/json" "fmt" "net/http" "net/http/httptest" "os" "os/signal" "strings" "syscall" "testing" "time" ) func adminCall(handler http.Handler, method, path, body string, cookie *http.Cookie, headers map[string]string) *httptest.ResponseRecorder { r := httptest.NewRequest(method, path, strings.NewReader(body)) r.Header.Set("Content-Type", "application/json") if cookie != nil { r.AddCookie(cookie) } for key, value := range headers { r.Header.Set(key, value) } w := httptest.NewRecorder() handler.ServeHTTP(w, r) return w } func adminLogin(t *testing.T, handler http.Handler, password string) *http.Cookie { t.Helper() w := adminCall(handler, "POST", "/admin/api/login", jsonText(map[string]string{"password": password}), nil, nil) if w.Code != 200 { t.Fatalf("login: %d %s", w.Code, w.Body.String()) } cookies := w.Result().Cookies() if len(cookies) != 1 || cookies[0].Name != adminCookie { t.Fatal("missing session cookie") } return cookies[0] } func TestAdminAuthenticationBoundary(t *testing.T) { s, _ := fixtureService(t) for _, path := range []string{"/admin", "/admin/", "/admin/api/overview"} { if w := adminCall(s.handler(), "GET", path, "", nil, nil); w.Code != 404 { t.Fatalf("disabled dashboard: %s %d", path, w.Code) } } s.cfg.AdminPassword, s.cfg.AdminCookieSecure = "test-admin-password", true h := s.handler() for _, path := range []string{"/admin/api/session", "/admin/api/overview", "/admin/api/requests", "/admin/api/requests/secret"} { w := adminCall(h, "GET", path, "", nil, map[string]string{"x-api-key": s.cfg.Token}) if w.Code != 401 { t.Fatalf("api key bypass: %s %d", path, w.Code) } if w.Header().Get("Cache-Control") != "no-store" { t.Fatal("sensitive response may be cached") } } if w := adminCall(h, "POST", "/admin/api/login", `{"password":"wrong-password"}`, nil, nil); w.Code != 401 { t.Fatal(w.Code) } cookie := adminLogin(t, h, s.cfg.AdminPassword) if !cookie.HttpOnly || !cookie.Secure || cookie.SameSite != http.SameSiteStrictMode || cookie.Path != "/admin" || cookie.MaxAge != 43200 { t.Fatalf("unsafe cookie: %+v", cookie) } if w := adminCall(h, "GET", "/admin/api/session", "", cookie, nil); w.Code != 200 { t.Fatal(w.Code) } if w := adminCall(s.handler(), "GET", "/admin/api/session", "", cookie, nil); w.Code != 401 { t.Fatal("a new server handler accepted an old process-local session") } if w := adminCall(h, "POST", "/search", `{"query":"limits"}`, cookie, nil); w.Code != 401 { t.Fatal("admin session bypassed public api auth") } if w := adminCall(h, "POST", "/admin/api/mcp", `{}`, cookie, nil); w.Code != 404 { t.Fatal("unexpected mcp bridge") } for _, headers := range []map[string]string{{"Origin": "https://evil.example"}, {"Sec-Fetch-Site": "cross-site"}} { w := adminCall(h, "POST", "/admin/api/logout", `{}`, cookie, headers) if w.Code != 403 { t.Fatalf("csrf accepted: %d", w.Code) } w = adminCall(h, "POST", "/admin/api/login", `{"password":"test-admin-password"}`, nil, headers) if w.Code != 403 { t.Fatal("login csrf accepted") } } w := adminCall(h, "POST", "/admin/api/logout", `{}`, cookie, map[string]string{"Content-Type": "text/plain"}) if w.Code != 415 { t.Fatal("simple cross-site content type accepted") } w = adminCall(h, "POST", "/admin/api/logout", `{}`, cookie, nil) if w.Code != 200 || w.Result().Cookies()[0].MaxAge != -1 { t.Fatal("logout failed") } if w := adminCall(h, "GET", "/admin/api/overview", "", cookie, nil); w.Code != 401 { t.Fatal("revoked cookie still authorized") } if w := adminCall(h, "GET", "/admin/api/session", "", &http.Cookie{Name: adminCookie, Value: "forged"}, nil); w.Code != 401 { t.Fatal("forged cookie accepted") } page := adminCall(h, "GET", "/admin/", "", nil, nil) if page.Code != 200 || !strings.Contains(page.Body.String(), "/admin/assets/") { t.Fatal("embedded ui missing") } if !strings.Contains(page.Header().Get("Content-Security-Policy"), "frame-ancestors 'none'") { t.Fatal("missing csp") } if w := adminCall(h, "GET", "/admin/.env", "", nil, nil); w.Code != 404 { t.Fatal("static handler exposed non-assets") } } func TestAdminLoginRateLimit(t *testing.T) { s, _ := fixtureService(t) s.cfg.AdminPassword = "test-admin-password" h := s.handler() for i := range 11 { w := adminCall(h, "POST", "/admin/api/login", `{"password":"incorrect"}`, nil, nil) want := 401 if i == 10 { want = 429 } if w.Code != want { t.Fatalf("attempt %d: %d", i, w.Code) } } if w := adminCall(h, "POST", "/admin/api/login", `{"password":"test-admin-password"}`, nil, nil); w.Code != 429 { t.Fatal("rate limit bypass") } } func TestAdminPlaygroundLogsAndReadModels(t *testing.T) { s, page := fixtureService(t) s.cfg.AdminPassword = "test-admin-password" s.cfg.JevKey, s.cfg.LLMKey = "secret-jev-key", "secret-llm-key" h := s.handler() cookie := adminLogin(t, h, s.cfg.AdminPassword) body := fmt.Sprintf(`{"urls":[%q,%q],"highlights":{"query":"request size"},"summary":{"query":"request size"}}`, page.URL, page.URL+"/missing") w := adminCall(h, "POST", "/admin/api/contents", body, cookie, nil) if w.Code != 200 { t.Fatalf("contents: %s", w.Body.String()) } var response ResultsResponse if err := json.Unmarshal(w.Body.Bytes(), &response); err != nil { t.Fatal(err) } if len(response.Results) != 1 || len(response.Statuses) != 2 || response.Statuses[1].Error == nil { t.Fatal("lost partial failure") } trace, err := s.log.adminTrace(context.Background(), response.RequestID) if err != nil { t.Fatal(err) } if len(trace.Requests) != 2 || len(trace.Completions) != 1 || len(trace.Decisions) == 0 || len(trace.Evidence) != 1 { t.Fatalf("incomplete trace: %+v", trace) } if trace.Requests[0]["caller"] != "admin-dashboard" { t.Fatal("missing dashboard caller") } if trace.Completions[0]["response"] != *response.Results[0].Summary { t.Fatal("training reply changed") } w = adminCall(h, "POST", "/admin/api/search", `{"query":""}`, cookie, nil) if w.Code != 400 { t.Fatal("public request validation not reused") } w = adminCall(h, "GET", "/admin/api/overview", "", cookie, nil) if w.Code != 200 { t.Fatal(w.Body.String()) } for _, secret := range []string{s.cfg.AdminPassword, s.cfg.Token, s.cfg.JevKey, s.cfg.LLMKey} { if strings.Contains(w.Body.String(), secret) { t.Fatal("credentials in overview") } } var stats struct { Requests struct{ Total, Errors int } Models struct{ Calls int } Tokens struct{ Input, Output int } } if err := json.Unmarshal(w.Body.Bytes(), &stats); err != nil { t.Fatal(err) } if stats.Requests.Total != 2 || stats.Requests.Errors != 2 || stats.Models.Calls != len(trace.Decisions)+1 || stats.Tokens.Input != 250 || stats.Tokens.Output != 20 { t.Fatalf("wrong totals: %+v", stats) } for _, path := range []string{"/admin/api/requests?before=oops", "/admin/api/requests?endpoint=extract"} { if w := adminCall(h, "GET", path, "", cookie, nil); w.Code != 400 { t.Fatal("invalid filter accepted") } } if w := adminCall(h, "GET", "/admin/api/requests/missing", "", cookie, nil); w.Code != 404 { t.Fatal("unknown trace should be missing") } } // Opt-in browser fixture: real HTTP/pipeline/SQLite, local mocked providers, no paid calls. func TestAdminBrowserFixture(t *testing.T) { path := os.Getenv("ADMIN_BROWSER_FIXTURE") if path == "" { t.Skip("set ADMIN_BROWSER_FIXTURE to start the browser-test server") } s, page := fixtureService(t) s.cfg.AdminPassword = "browser-fixture-password" s.cfg.JevKey, s.cfg.JevModel, s.cfg.LLMKey, s.cfg.LLMModel = "fixture", "jev-test", "fixture", "configured-model" h := s.handler() cookie := adminLogin(t, h, s.cfg.AdminPassword) for i := range 32 { adminCall(h, "POST", "/admin/api/search", fmt.Sprintf(`{"query":"fixture request limits %d","numResults":1}`, i), cookie, nil) } adminCall(h, "POST", "/admin/api/search", `{"query":""}`, cookie, nil) server := httptest.NewServer(h) defer server.Close() if err := os.WriteFile(path, []byte(jsonText(map[string]string{"url": server.URL, "sourceURL": page.URL, "password": s.cfg.AdminPassword})), 0600); err != nil { t.Fatal(err) } ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) defer stop() <-ctx.Done() } func TestAdminPaginationAndHistoricalRows(t *testing.T) { s, _ := fixtureService(t) for i := range 65 { ctx := context.WithValue(context.Background(), contextKey{}, callContext{ID: fmt.Sprint(i), Caller: "test"}) s.log.request(ctx, "search", map[string]string{"query": "query"}, "ok") } ctx := context.Background() first, err := s.adminRequests(ctx, 0, "", false) if err != nil || len(first.Rows) != 30 || first.NextBefore != 36 { t.Fatalf("first: %+v %v", first, err) } second, err := s.adminRequests(ctx, first.NextBefore, "search", false) if err != nil || len(second.Rows) != 30 || second.Rows[0]["id"] != int64(35) { t.Fatal("pagination skipped or duplicated rows") } third, err := s.adminRequests(ctx, second.NextBefore, "", false) if err != nil || len(third.Rows) != 5 || third.NextBefore != 0 { t.Fatal("last page invalid") } empty, err := s.adminRequests(ctx, 0, "", true) if err != nil || empty.Rows == nil || len(empty.Rows) != 0 { t.Fatal("empty page should be an array") } s.log.write(`INSERT INTO requests(created_at,request_id,endpoint,detail,outcome) VALUES(?,?,?,?,?)`, time.Now().Unix(), "legacy", "search", "not-json", "ok") trace, err := s.log.adminTrace(ctx, "legacy") if err != nil || trace.Requests[0]["detail"] != "not-json" || trace.Decisions == nil { t.Fatal("legacy rows not preserved") } } func TestAdminConfig(t *testing.T) { t.Setenv("API_AUTH_TOKEN", "local-token") t.Setenv("ADMIN_PASSWORD", "short") if _, err := readConfig(); err == nil { t.Fatal("weak password accepted") } t.Setenv("ADMIN_PASSWORD", "test-admin-password") t.Setenv("ADMIN_COOKIE_SECURE", "true") c, err := readConfig() if err != nil || !c.AdminCookieSecure || c.AdminPassword != "test-admin-password" { t.Fatal("admin config missing") } }