package httpapi import ( "context" "encoding/json" "fmt" "knowledge-governance/internal/jobs" postgresstore "knowledge-governance/internal/platform/postgres" "knowledge-governance/internal/ppauth" "net/http/httptest" "os" "path/filepath" "sort" "strings" "testing" "time" ) type noPPJobStore struct { *fakeJobStore queued int } func (s *noPPJobStore) Enqueue(ctx context.Context, request jobs.EnqueueRequest, now time.Time) (*jobs.Job, error) { s.queued++ return s.fakeJobStore.Enqueue(ctx, request, now) } func TestPPHTTPRoundTripRechecksSaveAndNeverEnqueues(t *testing.T) { probes := 0 m := &ppauth.Manager{Path: t.TempDir() + "/credentials/settings.json", Probe: func(_ context.Context, c ppauth.Credentials) ppauth.Observation { probes++ return ppauth.Observation{State: "valid", Message: "认证有效 · 目录可读"} }} store := &noPPJobStore{fakeJobStore: &fakeJobStore{}} h, err := NewHandler(Config{Store: store, PPConnection: m}) if err != nil { t.Fatal(err) } call := func(method, path, body string) *httptest.ResponseRecorder { req := httptest.NewRequest(method, path, strings.NewReader(body)) req.Header.Set("X-Governance-Action", "pp-connection") req = req.WithContext(context.WithValue(req.Context(), sessionKey{}, sessionIdentity{Username: "tester", Role: roleAdmin})) rec := httptest.NewRecorder() h.ServeHTTP(rec, req) return rec } draft := `{"base_url":"https://api.example.invalid","username":"example","password":"example-private","revision":0}` for _, op := range [][2]string{{"POST", "/api/v1/pp-connection/test"}, {"PUT", "/api/v1/pp-connection"}, {"GET", "/api/v1/pp-connection"}} { rec := call(op[0], op[1], draft) if rec.Code != 200 { t.Fatalf("%s status=%d body=%s", op[0], rec.Code, rec.Body) } if strings.Contains(rec.Body.String(), "example-private") || strings.Contains(rec.Body.String(), `"password":`) { t.Fatal("credential leaked through response") } } if probes != 2 || store.queued != 0 { t.Fatalf("save must recheck and must not enqueue: checks=%d jobs=%d", probes, store.queued) } rec := call("PUT", "/api/v1/pp-connection", draft) if rec.Code != 409 { t.Fatalf("stale revision accepted: %d", rec.Code) } } func TestPPHTTPRefusesCrossOriginBeforeProbe(t *testing.T) { probes := 0 m := &ppauth.Manager{Path: t.TempDir() + "/credentials/settings.json", Probe: func(_ context.Context, _ ppauth.Credentials) ppauth.Observation { probes++ return ppauth.Observation{State: "valid"} }} h, _ := NewHandler(Config{Store: &fakeJobStore{}, PPConnection: m}) req := httptest.NewRequest("POST", "/api/v1/pp-connection/test", strings.NewReader(`{}`)) req.Header.Set("Origin", "https://foreign.example.invalid") req.Header.Set("X-Governance-Action", "pp-connection") req = req.WithContext(context.WithValue(req.Context(), sessionKey{}, sessionIdentity{Username: "tester", Role: roleAdmin})) rec := httptest.NewRecorder() h.ServeHTTP(rec, req) if rec.Code != 403 || probes != 0 { t.Fatal("cross-origin request reached credential probe") } } type combinedAuditStore struct { *fakeJobStore items []postgresstore.SourceAuditItem } func (s *combinedAuditStore) ListSourceAudit(_ context.Context, limit, offset int) (postgresstore.SourceAuditPage, error) { start := offset if start > len(s.items) { start = len(s.items) } end := start + limit if end > len(s.items) { end = len(s.items) } return postgresstore.SourceAuditPage{Items: s.items[start:end], Total: len(s.items), Limit: limit, Offset: offset}, nil } func TestPPSourceAuditSharesTheExistingPagedView(t *testing.T) { ctx := context.Background() m := &ppauth.Manager{Path: t.TempDir() + "/credentials/settings.json"} if err := os.Mkdir(filepath.Dir(m.Path), 0700); err != nil { t.Fatal(err) } now := time.Now().UTC() store := &combinedAuditStore{fakeJobStore: &fakeJobStore{}} expected := []postgresstore.SourceAuditItem{} for i := 0; i < 8; i++ { item := postgresstore.SourceAuditItem{ID: fmt.Sprintf("db-%02d", i), CreatedAt: now.Add(-time.Duration(i*2) * time.Minute), SourceName: "existing source"} store.items = append(store.items, item) expected = append(expected, item) } state := ppauth.State{} for i := 0; i < 4; i++ { event := ppauth.AuditEvent{ID: fmt.Sprintf("auth-%02d", i), CreatedAt: now.Add(-time.Duration(i*2+1) * time.Minute), SourceName: "PP", Action: "credential_test", Actor: "tester", Detail: "只读连接检查"} state.Audit = append(state.Audit, event) expected = append(expected, postgresstore.SourceAuditItem{ID: event.ID, CreatedAt: event.CreatedAt, SourceName: event.SourceName}) } raw, _ := json.Marshal(state) if err := os.WriteFile(m.Path, raw, 0600); err != nil { t.Fatal(err) } sort.Slice(expected, func(i, j int) bool { return expected[i].CreatedAt.After(expected[j].CreatedAt) }) for offset := 0; offset <= len(expected); offset++ { page, err := combinedSourceAudit(ctx, store, m, 3, offset) if err != nil || page.Total != len(expected) { t.Fatalf("offset=%d total=%d err=%v", offset, page.Total, err) } end := offset + 3 if end > len(expected) { end = len(expected) } if len(page.Items) != end-offset { t.Fatalf("wrong page length at %d", offset) } for i, item := range page.Items { if item.ID != expected[offset+i].ID { t.Fatalf("audit order mismatch at offset %d", offset) } } } }