feat(findings): add one-click cleanup for historical findings

- Add DB `DeleteFindings` bulk deletion inside `WithEvidenceTx`, locking affected tasks/findings, cascading retests/cases, and removing originating `exploration_nodes` (kind='finding').
- Add `DELETE /api/exploration/findings` endpoint supporting `scope` (`all`, `filtered`, `selected`) via JSON body or query params with strict validation and 409 on archive-state conflicts.
- Add `api.cleanupFindings`, mock handler support, bilingual `findingsCleanup.*` i18n keys, and a one-click cleanup button + confirmation dialog on the Findings page refreshing all four views.
- Add Go DB/server tests (`TestDeleteFindings`, `TestDeleteFindingsValidation`, `TestDeleteFindingsEndpoint`).

Fixes #157
This commit is contained in:
ji ruo committed 2026-11-23 18:20:33 +08:00
1 parent 7b196bf683
commit e196a06aa9
9 files changed
+755 -3

No files matched your search

+153
View File
@@ -416,3 +416,156 @@ func TestDeepenAdmissionFailureDiscardsFollowUpIntent(t *testing.T) {
t.Fatalf("failed admission left an orphan audit: before=%d after=%d", activitiesBefore, activitiesAfter)
}
}
func TestDeleteFindingsValidation(t *testing.T) {
s := &Server{}
for _, tc := range []struct {
name string
url string
body string
}{
{name: "missing scope", url: "/api/exploration/findings", body: `{}`},
{name: "empty body and query", url: "/api/exploration/findings", body: ""},
{name: "bad scope", url: "/api/exploration/findings", body: `{"scope":"unknown"}`},
{name: "selected without ids", url: "/api/exploration/findings", body: `{"scope":"selected","ids":[]}`},
{name: "selected bad string id", url: "/api/exploration/findings", body: `{"scope":"selected","ids":["abc"]}`},
{name: "selected zero id", url: "/api/exploration/findings", body: `{"scope":"selected","ids":[0]}`},
{name: "selected negative id", url: "/api/exploration/findings", body: `{"scope":"selected","ids":["-5"]}`},
{name: "selected query bad id", url: "/api/exploration/findings?scope=selected&ids=1,bad", body: ""},
{name: "invalid json", url: "/api/exploration/findings", body: `{`},
} {
t.Run(tc.name, func(t *testing.T) {
rec := httptest.NewRecorder()
var body *strings.Reader
if tc.body != "" {
body = strings.NewReader(tc.body)
}
var req *http.Request
if body != nil {
req = httptest.NewRequest(http.MethodDelete, tc.url, body)
} else {
req = httptest.NewRequest(http.MethodDelete, tc.url, nil)
}
s.deleteFindings(rec, req)
if rec.Code != http.StatusBadRequest {
t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String())
}
})
}
}
func TestDeleteFindingsEndpoint(t *testing.T) {
m, err := NewManager(t.TempDir(), "")
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { m.Close() })
marker := fmt.Sprintf("__cleanup_endpoint_%d__", time.Now().UnixNano())
task, err := m.CreateTask("cleanup endpoint test", "goal", nil, 0, 0)
if err != nil {
t.Fatal(err)
}
taskID := mustTaskID(t, task.ID)
t.Cleanup(func() {
_, _ = m.pg.Exec(`DELETE FROM findings WHERE vulnclass=$1`, marker)
_, _ = m.pg.Exec(`UPDATE tasks SET deleted_at=NULL WHERE id=$1`, taskID)
_ = m.pg.DeleteTask(taskID)
})
f1, err := m.pg.AddFinding(taskID, 0, marker, "first", db.SeverityHigh, "s1", "p1", "test", nil)
if err != nil {
t.Fatal(err)
}
f2, err := m.pg.AddFinding(taskID, 0, marker, "second", db.SeverityLow, "s2", "p2", "test", nil)
if err != nil {
t.Fatal(err)
}
f3, err := m.pg.AddFinding(0, 0, marker, "orphan", db.SeverityMedium, "s3", "p3", "test", nil)
if err != nil {
t.Fatal(err)
}
s := &Server{m: m}
// Validation errors.
for _, tc := range []struct {
name string
url string
body string
}{
{name: "missing scope", url: "/api/exploration/findings", body: `{}`},
{name: "bad scope", url: "/api/exploration/findings", body: `{"scope":"unknown"}`},
{name: "selected without ids", url: "/api/exploration/findings", body: `{"scope":"selected","ids":[]}`},
{name: "selected bad id", url: "/api/exploration/findings", body: `{"scope":"selected","ids":["abc"]}`},
{name: "invalid json", url: "/api/exploration/findings", body: `{`},
} {
t.Run(tc.name, func(t *testing.T) {
rec := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodDelete, tc.url, strings.NewReader(tc.body))
s.deleteFindings(rec, req)
if rec.Code != http.StatusBadRequest {
t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String())
}
})
}
// Selected delete via JSON body (string id).
rec := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodDelete, "/api/exploration/findings",
strings.NewReader(fmt.Sprintf(`{"scope":"selected","ids":["%d"]}`, f1)))
s.deleteFindings(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("selected delete status=%d body=%s", rec.Code, rec.Body.String())
}
var resp struct {
Deleted int64 `json:"deleted"`
}
if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil || resp.Deleted != 1 {
t.Fatalf("selected delete resp=%s err=%v", rec.Body.String(), err)
}
// Filtered delete via JSON body filters (unassigned only).
rec = httptest.NewRecorder()
req = httptest.NewRequest(http.MethodDelete, "/api/exploration/findings",
strings.NewReader(fmt.Sprintf(`{"scope":"filtered","filters":{"vulnclass":%q,"task_id":%q}}`, marker, db.FindingUnassignedTask)))
s.deleteFindings(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("filtered delete status=%d body=%s", rec.Code, rec.Body.String())
}
if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil || resp.Deleted != 1 {
t.Fatalf("filtered delete resp=%s err=%v", rec.Body.String(), err)
}
if got, _ := m.pg.GetFinding(f3); got != nil {
t.Fatalf("f3 should have been deleted")
}
// Archive-state conflict returns 409.
if _, err := m.pg.Exec(`UPDATE tasks SET deleted_at=now() WHERE id=$1`, taskID); err != nil {
t.Fatal(err)
}
rec = httptest.NewRecorder()
req = httptest.NewRequest(http.MethodDelete, "/api/exploration/findings",
strings.NewReader(fmt.Sprintf(`{"scope":"selected","ids":[%d]}`, f2)))
s.deleteFindings(rec, req)
if rec.Code != http.StatusConflict {
t.Fatalf("archive conflict status=%d body=%s", rec.Code, rec.Body.String())
}
if _, err := m.pg.Exec(`UPDATE tasks SET deleted_at=NULL WHERE id=$1`, taskID); err != nil {
t.Fatal(err)
}
// Query-string fallback for filtered cleanup.
rec = httptest.NewRecorder()
req = httptest.NewRequest(http.MethodDelete, "/api/exploration/findings?scope=filtered&vulnclass="+marker, nil)
s.deleteFindings(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("query filtered delete status=%d body=%s", rec.Code, rec.Body.String())
}
if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil || resp.Deleted != 1 {
t.Fatalf("query filtered delete resp=%s err=%v", rec.Body.String(), err)
}
if got, _ := m.pg.GetFinding(f2); got != nil {
t.Fatalf("f2 should have been deleted")
}
}
+118
View File
@@ -933,6 +933,7 @@ func (s *Server) Handler() http.Handler {
mux.HandleFunc("GET /api/exploration/frontier", s.frontier)
mux.HandleFunc("GET /api/exploration/findings", s.findings)
mux.HandleFunc("DELETE /api/exploration/findings", s.deleteFindings)
mux.HandleFunc("GET /api/exploration/findings/groups", s.findingGroups)
mux.HandleFunc("GET /api/exploration/finding-cases", s.listFindingCases)
mux.HandleFunc("POST /api/exploration/finding-cases", s.mergeFindingCase)
@@ -2726,6 +2727,123 @@ func (s *Server) deleteFinding(w http.ResponseWriter, r *http.Request) {
writeJSON(w, 200, map[string]any{"deleted": true, "id": id})
}
// deleteFindings bulk-deletes findings according to scope:
// - scope="all": delete all findings
// - scope="filtered": delete findings matching the shared FindingFilter fields
// - scope="selected": delete findings listed in ids (required, positive int64)
//
// Accepts a JSON body (preferred for large id lists) or query parameters.
func (s *Server) deleteFindings(w http.ResponseWriter, r *http.Request) {
var req struct {
Scope string `json:"scope"`
IDs []json.RawMessage `json:"ids"`
Filters *struct {
Severity string `json:"severity"`
Status string `json:"status"`
VulnClass string `json:"vulnclass"`
TaskID string `json:"task_id"`
Query string `json:"q"`
From string `json:"from"`
To string `json:"to"`
AssetScope string `json:"asset_scope"`
} `json:"filters"`
}
if r.Body != nil && r.Body != http.NoBody && r.ContentLength != 0 {
r.Body = http.MaxBytesReader(w, r.Body, 1<<20)
if err := json.NewDecoder(r.Body).Decode(&req); err != nil && !errors.Is(err, io.EOF) {
writeErr(w, 400, "invalid body")
return
}
}
q := r.URL.Query()
scope := strings.TrimSpace(req.Scope)
if scope == "" {
scope = strings.TrimSpace(q.Get("scope"))
}
var (
ids []int64
filter db.FindingFilter
)
switch scope {
case "selected":
if len(req.IDs) > 0 {
for _, raw := range req.IDs {
var (
id int64
str string
)
if err := json.Unmarshal(raw, &id); err != nil {
if err2 := json.Unmarshal(raw, &str); err2 != nil {
writeErr(w, 400, "bad finding id")
return
}
parsed, err2 := strconv.ParseInt(strings.TrimSpace(str), 10, 64)
if err2 != nil {
writeErr(w, 400, "bad finding id: "+str)
return
}
id = parsed
}
if id <= 0 {
writeErr(w, 400, "bad finding id")
return
}
ids = append(ids, id)
}
} else {
for _, part := range strings.Split(q.Get("ids"), ",") {
part = strings.TrimSpace(part)
if part == "" {
continue
}
id, err := strconv.ParseInt(part, 10, 64)
if err != nil || id <= 0 {
writeErr(w, 400, "bad finding id: "+part)
return
}
ids = append(ids, id)
}
}
if len(ids) == 0 {
writeErr(w, 400, "no findings selected")
return
}
case "all":
// Empty filter deletes every finding in the standalone findings table.
case "filtered":
if req.Filters != nil {
filter = db.FindingFilter{
Severity: normFilter(req.Filters.Severity),
Status: normFilter(req.Filters.Status),
VulnClass: normFilter(req.Filters.VulnClass),
TaskID: normFilter(req.Filters.TaskID),
Query: req.Filters.Query,
From: strings.TrimSpace(req.Filters.From),
To: strings.TrimSpace(req.Filters.To),
AssetScope: strings.TrimSpace(req.Filters.AssetScope),
}
} else {
filter = findingFilterFromQuery(q)
}
default:
writeErr(w, 400, "bad scope: "+scope)
return
}
n, err := s.m.pg.DeleteFindings(r.Context(), filter, ids)
if err != nil {
if errors.Is(err, db.ErrTaskArchiveState) {
writeErr(w, 409, err.Error())
return
}
writeErr(w, 500, err.Error())
return
}
writeJSON(w, 200, map[string]any{"deleted": n})
}
func (s *Server) intents(w http.ResponseWriter, r *http.Request) {
t := s.m.ResolveTask(r.URL.Query().Get("task"))
if t == nil {