package adminweb import ( "context" "net/http" "net/http/httptest" "strings" "testing" "time" ) type fakeService struct { snapshot Snapshot verified bool saved bool } func (f *fakeService) Snapshot(context.Context) (Snapshot, error) { return f.snapshot, nil } func (f *fakeService) SaveCredentials(context.Context, string, string) error { f.saved = true return nil } func (f *fakeService) VerifyCredentials(context.Context, string, string) Verification { f.verified = true return Verification{OK: true, Code: "ok", CheckedAt: time.Unix(1, 0)} } func TestDashboardNeverRendersSecrets(t *testing.T) { svc := &fakeService{snapshot: Snapshot{SystemState: "active", ClientIDMasked: "ding***", SecretConfigured: true}} h := New(svc, "admin-token") req := httptest.NewRequest(http.MethodGet, "/admin/settings", nil) req.Header.Set("Authorization", "Bearer admin-token") w := httptest.NewRecorder() h.ServeHTTP(w, req) if w.Code != 200 { t.Fatalf("status=%d", w.Code) } body := w.Body.String() if strings.Contains(body, "admin-token") || strings.Contains(strings.ToLower(body), "client secret value") { t.Fatal("secret leaked") } if !strings.Contains(body, "ding***") { t.Fatal("masked client id missing") } } func TestDashboardRendersOperationalComponentFields(t *testing.T) { checked := time.Date(2026, 8, 13, 18, 0, 0, 0, time.UTC) svc := &fakeService{snapshot: Snapshot{Components: []Component{{ Name: "WeKnora", State: "ok", Code: "health_ok", Detail: "HTTP健康探针正常", LastSuccess: checked.Add(-time.Minute), CheckedAt: checked, }}}} h := New(svc, "admin-token") req := httptest.NewRequest(http.MethodGet, "/admin/settings", nil) req.Header.Set("Authorization", "Bearer admin-token") w := httptest.NewRecorder() h.ServeHTTP(w, req) body := w.Body.String() for _, want := range []string{"WeKnora", "health_ok", "HTTP健康探针正常", "2026-08-13 17:59:00", "2026-08-13 18:00:00"} { if !strings.Contains(body, want) { t.Fatalf("dashboard missing %q: %s", want, body) } } } func TestSaveCredentialsRequiresVerification(t *testing.T) { svc := &fakeService{} h := New(svc, "admin-token") req := httptest.NewRequest(http.MethodPost, "/admin/setup/credentials", strings.NewReader("client_id=id&client_secret=secret")) req.Header.Set("Content-Type", "application/x-www-form-urlencoded") req.Header.Set("Authorization", "Bearer admin-token") w := httptest.NewRecorder() h.ServeHTTP(w, req) if w.Code != http.StatusSeeOther || !svc.verified || !svc.saved { t.Fatalf("status=%d verified=%v saved=%v", w.Code, svc.verified, svc.saved) } }