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

@@ -12,6 +12,7 @@ import {
InfoIcon,
SearchIcon,
ShieldAlertIcon,
Trash2Icon,
TriangleAlertIcon,
} from "lucide-react";
import { useTranslation } from "react-i18next";
@@ -285,6 +286,10 @@ export default function FindingsPage() {
const [includeOriginals, setIncludeOriginals] = React.useState(false);
const [reviewing, setReviewing] = React.useState(false);
const [exporting, setExporting] = React.useState(false);
const [cleanupOpen, setCleanupOpen] = React.useState(false);
const [cleanupScope, setCleanupScope] = React.useState<"filtered" | "all" | "selected">("all");
const [cleaning, setCleaning] = React.useState(false);
const [caseRefreshKey, setCaseRefreshKey] = React.useState(0);
const toggleSelected = React.useCallback((id: string, checked: boolean) => {
setSelectedIds((prev) => {
@@ -312,6 +317,23 @@ export default function FindingsPage() {
setExportOpen(true);
}
const hasActiveFilters =
severity !== "all" ||
status !== "all" ||
vulnclass !== "all" ||
task !== "all" ||
query !== "" ||
Boolean(dateRange.from) ||
Boolean(dateRange.to) ||
(view === "asset" && assetScope !== null);
function openCleanup() {
if (selectedIds.size > 0) setCleanupScope("selected");
else if (hasActiveFilters && stats.total > 0) setCleanupScope("filtered");
else setCleanupScope("all");
setCleanupOpen(true);
}
async function doExport() {
setExporting(true);
try {
@@ -791,6 +813,58 @@ export default function FindingsPage() {
[refreshAfterMutation, refreshStats, setFindings, liveUI],
);
async function doCleanup() {
if (cleaning) return;
setCleaning(true);
try {
const res = await api.cleanupFindings({
scope: cleanupScope,
filters: {
severity,
status,
vulnclass,
task,
query,
sort,
...dateRange,
assetScope: view === "asset" ? (assetScope ?? undefined) : undefined,
},
ids: [...selectedIds],
});
setCleanupOpen(false);
setSelectedIds(new Set());
setExpanded(null);
setEdit(null);
setReports({});
setPage(1);
setFlatPage(1);
setExpandedGroups(new Set());
setGroupFindings({});
if (view === "asset" && cleanupScope === "all") {
setAssetScope(null);
}
setCaseRefreshKey((v) => v + 1);
void refreshStats();
if (view === "asset") {
void loadFlat();
void loadAssetTree();
} else if (view === "flat") {
void loadFlat();
} else if (view === "grouped") {
void refreshGroups();
}
if (res.deleted > 0) {
toast.success(t("findingsCleanup.success", { count: res.deleted }));
} else {
toast.info(t("findingsCleanup.empty"));
}
} catch (e) {
toast.error(t("findingsCleanup.failed", { message: (e as Error).message }));
} finally {
setCleaning(false);
}
}
const openDeepen = React.useCallback((f: Finding) => {
setDeepenFinding(f);
setDeepenDescription("");
@@ -1053,6 +1127,15 @@ export default function FindingsPage() {
<Button size="sm" variant="outline" onClick={openExport}>
<DownloadIcon /> {ui("screen.76420433f22d1c")}
</Button>
<Button
size="sm"
variant="outline"
className="text-destructive hover:bg-destructive/10 hover:text-destructive"
disabled={cleaning || (statsLoaded && !hasActiveFilters && stats.total === 0 && selectedIds.size === 0)}
onClick={openCleanup}
>
<Trash2Icon /> {t("findingsCleanup.button")}
</Button>
</div>
</div>
@@ -1121,6 +1204,7 @@ export default function FindingsPage() {
query={{ severity, status, vulnclass, task, query, sort, ...dateRange }}
selectedIds={selectedIds}
onSelect={toggleSelected}
refreshKey={caseRefreshKey}
/>
)}
{view === "grouped" && (
@@ -1394,6 +1478,62 @@ export default function FindingsPage() {
</DialogFooter>
</DialogContent>
</Dialog>
<Dialog
open={cleanupOpen}
onOpenChange={(open) => {
if (!cleaning) setCleanupOpen(open);
}}
>
<DialogContent>
<DialogHeader>
<DialogTitle>{t("findingsCleanup.title")}</DialogTitle>
<DialogDescription>{t("findingsCleanup.description")}</DialogDescription>
</DialogHeader>
<div className="flex flex-col gap-2 py-1">
<span className="text-muted-foreground text-xs">{t("findingsCleanup.scopeLabel")}</span>
<RadioGroup value={cleanupScope} onValueChange={(v) => setCleanupScope(v as typeof cleanupScope)}>
<label
htmlFor="cleanup-scope-filtered"
className={cn("flex items-center gap-2 text-sm", stats.total === 0 && "text-muted-foreground")}
>
<RadioGroupItem id="cleanup-scope-filtered" value="filtered" disabled={stats.total === 0} />
{t("findingsCleanup.scopeFiltered", { count: stats.total })}
</label>
<label
htmlFor="cleanup-scope-selected"
className={cn("flex items-center gap-2 text-sm", selectedIds.size === 0 && "text-muted-foreground")}
>
<RadioGroupItem id="cleanup-scope-selected" value="selected" disabled={selectedIds.size === 0} />
{t("findingsCleanup.scopeSelected", { count: selectedIds.size })}
</label>
<label htmlFor="cleanup-scope-all" className="flex items-center gap-2 text-sm">
<RadioGroupItem id="cleanup-scope-all" value="all" />
{t("findingsCleanup.scopeAll")}
</label>
</RadioGroup>
</div>
<DialogFooter>
<Button variant="outline" onClick={() => setCleanupOpen(false)} disabled={cleaning}>
{t("common.cancel")}
</Button>
<Button
variant="destructive"
onClick={doCleanup}
disabled={
cleaning ||
(cleanupScope === "selected" && selectedIds.size === 0) ||
(cleanupScope === "filtered" && stats.total === 0)
}
>
{cleaning ? <Spinner data-icon="inline-start" /> : <Trash2Icon />}
{cleaning ? t("findingsCleanup.cleaning") : t("findingsCleanup.confirm")}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</div>
);
}
+5 -3
View File
@@ -448,6 +448,7 @@ export function FindingCaseList({
contextTask,
readOnly = false,
onTotal,
refreshKey = 0,
}: {
query: Omit<FindingQuery, "page" | "pageSize">;
selectedIds?: Set<string>;
@@ -455,6 +456,7 @@ export function FindingCaseList({
contextTask?: string;
readOnly?: boolean;
onTotal?: (total: number) => void;
refreshKey?: number;
}) {
const { ui } = useUITranslation();
@@ -464,10 +466,10 @@ export function FindingCaseList({
const [error, setError] = React.useState("");
const [refresh, setRefresh] = React.useState(0);
const key = JSON.stringify(query);
// biome-ignore lint/correctness/useExhaustiveDependencies: reset pagination when the filter fingerprint changes.
// biome-ignore lint/correctness/useExhaustiveDependencies: reset pagination when the filter fingerprint or external refresh changes.
React.useEffect(() => {
setPage(1);
}, [key]);
}, [key, refreshKey]);
// biome-ignore lint/correctness/useExhaustiveDependencies: refresh is an explicit reload requested after grouping/retry.
React.useEffect(() => {
let active = true;
@@ -490,7 +492,7 @@ export function FindingCaseList({
active = false;
clearTimeout(timer);
};
}, [key, page, pageSize, refresh]);
}, [key, page, pageSize, refresh, refreshKey]);
React.useEffect(() => {
if (data) onTotal?.(data.total);
}, [data, onTotal]);
+15
View File
@@ -214,6 +214,21 @@ export const messages = {
],
"ui.ascending": ["正序", "ascending"],
"ui.descending": ["倒序", "descending"],
"findingsCleanup.button": ["一键清理", "One-click cleanup"],
"findingsCleanup.title": ["一键清理历史漏洞", "Clean up historical findings"],
"findingsCleanup.description": [
"永久删除所选范围内的漏洞发现记录及其来源探索节点、复测记录和归并成员关系,删除后无法恢复。",
"Permanently delete matching findings along with their originating exploration nodes, retest records, and case memberships. This action cannot be undone.",
],
"findingsCleanup.scopeLabel": ["清理范围", "Cleanup scope"],
"findingsCleanup.scopeFiltered": ["当前筛选结果({{count}} 条)", "Current filter results ({{count}})"],
"findingsCleanup.scopeSelected": ["已勾选漏洞({{count}} 条)", "Selected findings ({{count}})"],
"findingsCleanup.scopeAll": ["全部历史漏洞", "All historical findings"],
"findingsCleanup.confirm": ["确认清理", "Confirm cleanup"],
"findingsCleanup.cleaning": ["清理中…", "Cleaning up…"],
"findingsCleanup.success": ["已清理 {{count}} 条漏洞", "Deleted {{count}} finding(s)"],
"findingsCleanup.empty": ["没有符合条件的漏洞可清理", "No matching findings to delete"],
"findingsCleanup.failed": ["清理失败:{{message}}", "Cleanup failed: {{message}}"],
} satisfies Record<string, readonly [string, string]>;
const statuses: Record<string, readonly (readonly [string, string, string])[]> = {
+24
View File
@@ -970,6 +970,30 @@ export const api = {
) => patch<Finding>(`/exploration/findings/${id}`, fields),
// 删除漏洞:移除 findings 记录 + 来源探索节点(从发现列表/任务发现 Tab/探索图一并消失)。
deleteFinding: (id: string) => del<{ deleted: boolean; id: number }>(`/exploration/findings/${id}`),
// 批量一键清理漏洞:按范围(当前筛选/全部/已勾选)移除 findings 记录及来源探索节点。
cleanupFindings: (opts: {
scope: "filtered" | "all" | "selected";
filters?: Omit<FindingQuery, "page" | "pageSize">;
ids?: string[];
}) => {
const body: Record<string, unknown> = { scope: opts.scope };
if (opts.scope === "selected") {
body.ids = opts.ids ?? [];
} else if (opts.scope === "filtered" && opts.filters) {
const f = opts.filters;
body.filters = {
...(f.severity && f.severity !== "all" ? { severity: f.severity } : {}),
...(f.status && f.status !== "all" ? { status: f.status } : {}),
...(f.vulnclass && f.vulnclass !== "all" ? { vulnclass: f.vulnclass } : {}),
...(f.task && f.task !== "all" ? { task_id: f.task } : {}),
...(f.query?.trim() ? { q: f.query.trim() } : {}),
...(f.from ? { from: f.from } : {}),
...(f.to ? { to: f.to } : {}),
...(f.assetScope ? { asset_scope: f.assetScope } : {}),
};
}
return del<{ deleted: number }>("/exploration/findings", body);
},
findingRetests: (id: string) =>
get<{ retests: FindingRetest[] }>(`/exploration/findings/${encodeURIComponent(id)}/retests`).then((r) =>
arr(r.retests),
+44
View File
@@ -483,6 +483,10 @@ function mockFilterFindings(q: URLSearchParams): (typeof mockFindings)[number][]
if (vulnclass) list = list.filter((finding) => finding.vulnclass === vulnclass);
if (taskID === "__unassigned__") list = list.filter((finding) => !finding.task_id);
else if (taskID) list = list.filter((finding) => finding.task_id === taskID);
const fromTs = q.get("from") ? Date.parse(q.get("from") as string) : Number.NaN;
const toTs = q.get("to") ? Date.parse(q.get("to") as string) : Number.NaN;
if (Number.isFinite(fromTs)) list = list.filter((finding) => Date.parse(finding.ts) >= fromTs);
if (Number.isFinite(toTs)) list = list.filter((finding) => Date.parse(finding.ts) <= toTs);
return list;
}
@@ -2317,6 +2321,11 @@ function route(m: string, path: string, seg: string[], q: URLSearchParams, b: Re
if (seg[0] === "exploration" && seg[1] === "findings" && seg.length === 3 && seg[2] !== "stats") {
const f = mockFindings.find((x) => x.id === seg[2]);
if (!f) return {};
if (m === "DELETE") {
const idx = mockFindings.findIndex((x) => x.id === seg[2]);
if (idx >= 0) mockFindings.splice(idx, 1);
return { deleted: idx >= 0, id: Number(seg[2]) || 0 };
}
if (m === "PATCH") {
if (typeof b.status === "string") f.status = b.status as typeof f.status;
if (typeof b.severity === "string") f.severity = b.severity as typeof f.severity;
@@ -2339,6 +2348,41 @@ function route(m: string, path: string, seg: string[], q: URLSearchParams, b: Re
};
}
if (path === "/exploration/findings") {
if (m === "DELETE") {
const scope = (typeof b.scope === "string" ? b.scope : q.get("scope"))?.trim() ?? "";
let targets: (typeof mockFindings)[number][] = [];
if (scope === "all") {
targets = [...mockFindings];
} else if (scope === "selected") {
const rawIds = Array.isArray(b.ids)
? b.ids.map((v) => String(v))
: (q.get("ids") ?? "")
.split(",")
.map((s) => s.trim())
.filter(Boolean);
const idSet = new Set(rawIds);
targets = mockFindings.filter((f) => idSet.has(f.id));
} else if (scope === "filtered") {
const params = new URLSearchParams(q);
if (b.filters && typeof b.filters === "object") {
for (const [k, v] of Object.entries(b.filters as Record<string, unknown>)) {
if (typeof v === "string" && v) params.set(k, v);
}
}
targets = mockApplyAssetScope(mockFilterFindings(params), params.get("asset_scope"));
} else {
throw new Error(`bad scope: ${scope}`);
}
const targetSet = new Set(targets.map((f) => f.id));
let deleted = 0;
for (let i = mockFindings.length - 1; i >= 0; i--) {
if (targetSet.has(mockFindings[i].id)) {
mockFindings.splice(i, 1);
deleted++;
}
}
return { deleted };
}
// finding_id=id:真后端用独立表行 id 作为状态/详情句柄,mock 里用自身 id 顶上。
// report 仅详情接口返回,列表剥掉(与后端一致)。
const withFid = (f: (typeof mockFindings)[number]) => ({