diff --git a/db/notification.go b/db/notification.go index 9e0daaf..40187e6 100644 --- a/db/notification.go +++ b/db/notification.go @@ -509,6 +509,38 @@ func (d *DB) SetFindingStatusWithNotify(ctx context.Context, id int64, status st return from, found, notified, err } +// FindingStatusBatchResult is one id's outcome in a bulk status update. +type FindingStatusBatchResult struct { + ID int64 `json:"id"` + From string `json:"from,omitempty"` + Found bool `json:"found"` + Changed bool `json:"changed"` + Notified bool `json:"notified"` +} + +// SetFindingStatusesWithNotify updates several findings to the same status in one +// transaction. It returns a result per id, so an unknown id is reported as +// found=false instead of hiding the others; a database error rolls the whole +// batch back. Notification semantics stay identical to the single-row path: one +// delivery event per finding whose status actually changed, none for a no-op. +func (d *DB) SetFindingStatusesWithNotify(ctx context.Context, ids []int64, status string) ([]FindingStatusBatchResult, error) { + out := make([]FindingStatusBatchResult, 0, len(ids)) + err := d.WithEvidenceTx(ctx, func(tx *sql.Tx) error { + for _, id := range ids { + from, found, changed, notified, err := SetFindingStatusTx(ctx, tx, id, status) + if err != nil { + return err + } + out = append(out, FindingStatusBatchResult{ID: id, From: from, Found: found, Changed: changed, Notified: notified}) + } + return nil + }) + if err != nil { + return nil, err + } + return out, nil +} + // SetFindingStatusTx updates a finding's status and registers a status-change delivery // event inside the **caller's transaction**. // diff --git a/db/notification_test.go b/db/notification_test.go index e7c8fc9..dd7c807 100644 --- a/db/notification_test.go +++ b/db/notification_test.go @@ -607,6 +607,69 @@ func TestSetFindingStatusWithNotifyOnlyEmitsOnRealChange(t *testing.T) { } } +// A bulk update is one transaction with a per-id result: unknown ids are +// reported, not fatal, and a second call is a no-op that emits no event. +func TestSetFindingStatusesWithNotify(t *testing.T) { + d := notifyTestDB(t) + ctx := context.Background() + + tk, err := d.CreateTask("bulk status test", "goal", nil, 0, 0) + if err != nil { + t.Fatal(err) + } + defer d.DeleteTask(tk.ID) + es := d.Exploration(tk.ExplorationID) + record := func(name string) int64 { + fi, err := es.RecordFinding(ctx, RecordFindingInput{ + TaskID: tk.ID, Worker: "test", VulnClass: "XSS", Name: name, + Severity: "medium", Summary: "summary", + }) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { d.Exec(`DELETE FROM notification_events WHERE finding_id=$1`, fi.FindingID) }) + return fi.FindingID + } + first, second := record("bulk one"), record("bulk two") + const missingID = int64(999999999) + + results, err := d.SetFindingStatusesWithNotify(ctx, []int64{first, second, missingID}, FindingConfirmed) + if err != nil { + t.Fatal(err) + } + if len(results) != 3 { + t.Fatalf("want 3 results, got %d", len(results)) + } + for i, want := range []int64{first, second} { + r := results[i] + if r.ID != want || !r.Found || !r.Changed || !r.Notified || r.From != FindingPending { + t.Fatalf("result %d: %+v", i, r) + } + } + if r := results[2]; r.Found || r.Changed || r.Notified { + t.Fatalf("a missing id should be found=false with no change: %+v", r) + } + for _, id := range []int64{first, second} { + var status string + if err := d.QueryRow(`SELECT status FROM findings WHERE id=$1`, id).Scan(&status); err != nil || status != FindingConfirmed { + t.Fatalf("finding %d status = %q (%v)", id, status, err) + } + var events int + if err := d.QueryRow(`SELECT count(*) FROM notification_events WHERE finding_id=$1 AND kind=$2`, id, notify.EventFindingStatusChanged).Scan(&events); err != nil || events != 1 { + t.Fatalf("finding %d status events = %d (%v)", id, events, err) + } + } + + // Same status again: no change, so no push. + again, err := d.SetFindingStatusesWithNotify(ctx, []int64{first}, FindingConfirmed) + if err != nil || len(again) != 1 { + t.Fatalf("second batch: %v %v", again, err) + } + if again[0].Changed || again[0].Notified { + t.Fatalf("a no-op batch should neither change nor notify: %+v", again[0]) + } +} + func TestNotificationStatsSnapshot(t *testing.T) { d := notifyTestDB(t) ctx := context.Background() diff --git a/server/bulk_finding_status_test.go b/server/bulk_finding_status_test.go new file mode 100644 index 0000000..a0932ad --- /dev/null +++ b/server/bulk_finding_status_test.go @@ -0,0 +1,34 @@ +package server + +import ( + "net/http" + "net/http/httptest" + "strings" + "testing" +) + +// The bulk endpoint validates the whole request before touching the database, so +// a malformed body, an unknown status and an empty id list are client errors. +func TestBulkFindingStatusValidation(t *testing.T) { + s := &Server{m: &Manager{}} + cases := []struct { + name string + body string + want int + }{ + {"bad json", `{`, http.StatusBadRequest}, + {"unknown status", `{"ids":[1],"status":"nope"}`, http.StatusBadRequest}, + {"empty ids", `{"ids":[],"status":"confirmed"}`, http.StatusBadRequest}, + {"non-positive ids", `{"ids":[0,-3],"status":"confirmed"}`, http.StatusBadRequest}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + rec := httptest.NewRecorder() + req := httptest.NewRequest(http.MethodPost, "/api/exploration/findings/bulk-status", strings.NewReader(tc.body)) + s.bulkPatchFindingStatus(rec, req) + if rec.Code != tc.want { + t.Fatalf("status %d, want %d: %s", rec.Code, tc.want, rec.Body.String()) + } + }) + } +} diff --git a/server/server.go b/server/server.go index 7956221..7676d93 100644 --- a/server/server.go +++ b/server/server.go @@ -801,6 +801,7 @@ func (s *Server) Handler() http.Handler { mux.HandleFunc("GET /api/exploration/findings/retests/active", s.listActiveFindingRetests) mux.HandleFunc("POST /api/exploration/findings/{id}/retests", s.startFindingRetest) mux.HandleFunc("PATCH /api/exploration/findings/{id}", s.patchFinding) + mux.HandleFunc("POST /api/exploration/findings/bulk-status", s.bulkPatchFindingStatus) mux.HandleFunc("DELETE /api/exploration/findings/{id}", s.deleteFinding) mux.HandleFunc("GET /api/exploration/intents", s.intents) mux.HandleFunc("GET /api/exploration/graph", s.explorationGraph) @@ -2565,6 +2566,61 @@ func (s *Server) patchFinding(w http.ResponseWriter, r *http.Request) { writeJSON(w, 200, findingFromDB(f, s.resolveAssetIDs(f.AssetIDs))) } +// maxBulkFindingStatus caps one bulk status request. The UI acts on a page at a +// time, so this is far above a normal selection and still bounds the work. +const maxBulkFindingStatus = 500 + +// bulkPatchFindingStatus sets the same triage status on a batch of findings in +// one transaction. Ids that do not exist are reported per id, not as a batch +// failure, and the notification semantics are the single-row ones: one event per +// finding whose status actually changed. The node payload mirror (#289) runs in +// the same transaction, so the per-task view stays in sync. +func (s *Server) bulkPatchFindingStatus(w http.ResponseWriter, r *http.Request) { + var body struct { + IDs []int64 `json:"ids"` + Status string `json:"status"` + } + if err := json.NewDecoder(r.Body).Decode(&body); err != nil { + writeErr(w, 400, "bad json: "+err.Error()) + return + } + if !db.ValidFindingStatus(body.Status) { + writeErr(w, 400, "bad status: "+body.Status) + return + } + seen := make(map[int64]bool, len(body.IDs)) + ids := make([]int64, 0, len(body.IDs)) + for _, id := range body.IDs { + if id <= 0 || seen[id] { + continue + } + seen[id] = true + ids = append(ids, id) + if len(ids) == maxBulkFindingStatus { + break + } + } + if len(ids) == 0 { + writeErr(w, 400, "no finding ids") + return + } + results, err := s.m.pg.SetFindingStatusesWithNotify(r.Context(), ids, body.Status) + if err != nil { + writeErr(w, 500, err.Error()) + return + } + updated, missing := 0, 0 + for _, res := range results { + if res.Changed { + updated++ + } + if !res.Found { + missing++ + } + } + writeJSON(w, 200, map[string]any{"updated": updated, "missing": missing, "results": results}) +} + // deleteFinding removes a finding (findings row + originating exploration node). // id is the standalone findings-table id (DTO finding_id). func (s *Server) deleteFinding(w http.ResponseWriter, r *http.Request) { diff --git a/web/src/app/(main)/function/findings/page.tsx b/web/src/app/(main)/function/findings/page.tsx index 0f2788e..68e4f90 100644 --- a/web/src/app/(main)/function/findings/page.tsx +++ b/web/src/app/(main)/function/findings/page.tsx @@ -260,6 +260,7 @@ export default function FindingsPage() { // Export selection: tracked by finding_id (the standalone table's id), preserved across pages. const [selectedIds, setSelectedIds] = React.useState>(() => new Set()); + const [bulkBusy, setBulkBusy] = React.useState(false); // Export dialog state: scope (current filter / all / selected) × format (single md / per-finding md zip / csv / json). const [exportOpen, setExportOpen] = React.useState(false); const [exportScope, setExportScope] = React.useState<"filtered" | "all" | "selected">("filtered"); @@ -656,6 +657,36 @@ export default function FindingsPage() { [refreshAfterMutation, setFindings, status], ); + // applyBulkStatus sets the same triage status on every selected finding, then + // reloads the current view so rows hidden by the status filter disappear. + const applyBulkStatus = React.useCallback( + async (next: FindingStatus) => { + if (selectedIds.size === 0 || bulkBusy) return; + setBulkBusy(true); + try { + const r = await api.bulkSetFindingStatus([...selectedIds], next); + setSelectedIds(new Set()); + const label = statusMeta("finding", next).label; + toast.success( + r.updated === 1 ? `Marked 1 finding as "${label}"` : `Marked ${r.updated} findings as "${label}"`, + ); + void loadFlat(); + if (view === "asset") void loadAssetTree(); + api + .findingStats() + .then(setStats) + .catch(() => { + // The list reload remains valid even if the aggregate refresh fails. + }); + } catch (e) { + toast.error(`Bulk update failed: ${(e as Error).message}`); + } finally { + setBulkBusy(false); + } + }, + [bulkBusy, loadAssetTree, loadFlat, selectedIds, view], + ); + // The inline expanded detailed-report cache is keyed by the globally stable row key. report is long-form // Markdown the list query doesn't include, so it is fetched once by finding_id on expand; done with empty text = no report yet. const [reports, setReports] = React.useState>({}); @@ -995,7 +1026,27 @@ export default function FindingsPage() {
{selectedIds.size > 0 && ( - {selectedIds.size} selected +
+ {selectedIds.size} selected + +
)}