feat(vulnerabilities): add host, task, and raw list views

This commit is contained in:
Sycun 2026-11-13 15:04:06 +08:00
parent 9a0ea174b1
commit 2c4364ad47
10 changed files with 206 additions and 66 deletions

View File

@ -239,11 +239,7 @@ func (db *DB) ListVulnerabilities(limit, offset int, filter VulnerabilityListFil
}
func (db *DB) ListVulnerabilitiesForAccess(limit, offset int, filter VulnerabilityListFilter, access RBACListAccess) ([]*Vulnerability, error) {
return db.listVulnerabilitiesForAccess(limit, offset, filter, access, false)
}
func (db *DB) ListVulnerabilitiesByHostForAccess(limit, offset int, filter VulnerabilityListFilter, access RBACListAccess) ([]*Vulnerability, error) {
return db.listVulnerabilitiesForAccess(limit, offset, filter, access, true)
return db.ListVulnerabilitiesByGroupForAccess(limit, offset, filter, access, "")
}
func vulnerabilityTargetHost(target string) string {
@ -292,19 +288,26 @@ func vulnerabilityTargetHost(target string) string {
return host
}
func (db *DB) listVulnerabilitiesForAccess(limit, offset int, filter VulnerabilityListFilter, access RBACListAccess, byHost bool) ([]*Vulnerability, error) {
func (db *DB) ListVulnerabilitiesByGroupForAccess(limit, offset int, filter VulnerabilityListFilter, access RBACListAccess, groupBy string) ([]*Vulnerability, error) {
hostExpr, order := "NULL", "created_at DESC"
if byHost {
switch groupBy {
case "host":
hostExpr = "vulnerability_target_host(target)"
order = "target_host = '', target_host, created_at DESC, id"
case "task":
order = `task_id = '', task_id,
CASE WHEN task_id = '' THEN NULLIF(TRIM(task_tag), '') END ASC NULLS LAST,
created_at DESC, id`
case "none":
order = "created_at DESC, id"
}
query := `
SELECT id, COALESCE(conversation_id,''), COALESCE(project_id,''), title, description, severity, status, conversation_tag, task_tag,
vulnerability_type, target,
COALESCE(preconditions,''), COALESCE(reproduction_steps,''), COALESCE(evidence,''),
impact, recommendation, COALESCE(retest_notes,''), COALESCE(retest_log,''),
COALESCE((SELECT bt.id FROM batch_tasks bt WHERE bt.conversation_id = vulnerabilities.conversation_id LIMIT 1), '') AS task_id,
COALESCE((SELECT bt.queue_id FROM batch_tasks bt WHERE bt.conversation_id = vulnerabilities.conversation_id LIMIT 1), '') AS task_queue_id,
COALESCE((SELECT bt.id FROM batch_tasks bt WHERE bt.conversation_id = vulnerabilities.conversation_id ORDER BY bt.id LIMIT 1), '') AS task_id,
COALESCE((SELECT bt.queue_id FROM batch_tasks bt WHERE bt.conversation_id = vulnerabilities.conversation_id ORDER BY bt.id LIMIT 1), '') AS task_queue_id,
created_at, updated_at, ` + hostExpr + ` AS target_host
FROM vulnerabilities
WHERE 1=1

View File

@ -184,7 +184,7 @@ func (h *VulnerabilityHandler) ListVulnerabilities(c *gin.Context) {
pageStr := c.Query("page")
filter := parseVulnerabilityListFilter(c)
access := vulnerabilityAccessFromContext(c)
byHost := c.Query("group_by") == "host"
groupBy := c.Query("group_by")
limit, _ := strconv.Atoi(limitStr)
if limit <= 0 || limit > 100 {
@ -224,15 +224,11 @@ func (h *VulnerabilityHandler) ListVulnerabilities(c *gin.Context) {
page = (offset / limit) + 1
}
list := h.db.ListVulnerabilitiesForAccess
if byHost {
list = h.db.ListVulnerabilitiesByHostForAccess
if page > totalPages {
page = totalPages
offset = (page - 1) * limit
}
if (groupBy == "host" || groupBy == "task" || groupBy == "none") && page > totalPages {
page = totalPages
offset = (page - 1) * limit
}
vulnerabilities, err := list(limit, offset, filter, access)
vulnerabilities, err := h.db.ListVulnerabilitiesByGroupForAccess(limit, offset, filter, access, groupBy)
if err != nil {
h.logger.Error("获取漏洞列表失败", zap.Error(err))
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})

View File

@ -13,25 +13,38 @@ import (
"go.uber.org/zap"
)
func TestListVulnerabilitiesGroupedByHost(t *testing.T) {
func TestListVulnerabilitiesGroupedViews(t *testing.T) {
db, err := database.NewDB(filepath.Join(t.TempDir(), "grouped.db"), zap.NewNop())
if err != nil {
t.Fatal(err)
}
defer db.Close()
linked, err := db.CreateConversation("linked task", database.ConversationCreateMeta{})
if err != nil {
t.Fatal(err)
}
if err := db.CreateBatchQueue("queue", "queue", "", "eino_single", "manual", "", nil, "", 1,
[]map[string]interface{}{{"id": "task", "message": "task"}}); err != nil {
t.Fatal(err)
}
if err := db.UpdateBatchTaskStatus("queue", "task", "completed", linked.ID, "", ""); err != nil {
t.Fatal(err)
}
for i, item := range []struct {
id, target, severity string
id, target, severity, taskTag, conversationID string
}{
{"domain-old", "HTTPS://Example.COM.:443/login?keyword=%ZZ (旧接口);https://secondary.example.net/", "high"},
{"domain-new", "example.com:8443(受影响的服务)", "high"},
{"subdomain", "https://sub.example.com(旧记录)", "high"},
{"ipv6", "https://[2001:0DB8::1]:8080/", "high"},
{"unknown", "/api/login", "high"},
{"filtered", "https://other.example.com/", "low"},
{"domain-old", "HTTPS://Example.COM.:443/login?keyword=%ZZ (旧接口);https://secondary.example.net/", "high", "a", ""},
{"domain-new", "example.com:8443(受影响的服务)", "high", "", linked.ID},
{"subdomain", "https://sub.example.com(旧记录)", "high", "a", ""},
{"ipv6", "https://[2001:0DB8::1]:8080/", "high", "b", linked.ID},
{"unknown", "/api/login", "high", "", ""},
{"filtered", "https://other.example.com/", "low", "", ""},
} {
_, err := db.CreateVulnerability(&database.Vulnerability{
ID: item.id, Target: item.target, Title: item.id, Severity: item.severity,
TaskTag: item.taskTag, ConversationID: item.conversationID,
CreatedAt: time.Unix(int64(i+1), 0),
})
if err != nil {
@ -64,6 +77,10 @@ func TestListVulnerabilitiesGroupedByHost(t *testing.T) {
{"group_by=host&page=1", 1, []string{"ipv6", "domain-new"}, []string{"2001:db8::1", "example.com"}},
{"group_by=host&page=2", 2, []string{"domain-old", "subdomain"}, []string{"example.com", "sub.example.com"}},
{"group_by=host&page=4", 3, []string{"unknown"}, []string{""}},
{"group_by=task&page=1", 1, []string{"ipv6", "domain-new"}, nil},
{"group_by=task&page=2", 2, []string{"subdomain", "domain-old"}, nil},
{"group_by=task&page=3", 3, []string{"unknown"}, nil},
{"group_by=none&page=1", 1, []string{"unknown", "ipv6"}, nil},
{"page=1", 1, []string{"unknown", "ipv6"}, nil},
} {
t.Run(tc.query, func(t *testing.T) {

View File

@ -27456,37 +27456,86 @@ tr.mcp-stats-tool-row[data-tool-name]:focus-visible {
margin-bottom: 0;
}
.vulnerability-host-group {
#page-vulnerabilities > .page-header,
.vulnerability-header-start {
flex-wrap: wrap;
gap: 12px;
}
.vulnerability-header-start {
display: flex;
align-items: center;
min-width: 0;
}
.vulnerability-view-switch {
display: flex;
flex-wrap: wrap;
gap: 2px;
padding: 3px;
border: 1px solid var(--border-color);
border-radius: 8px;
background: var(--bg-secondary);
}
.vulnerability-view-switch button {
border: 0;
border-radius: 5px;
background: transparent;
color: var(--text-secondary);
padding: 5px 10px;
font: inherit;
font-size: 0.8125rem;
cursor: pointer;
}
.vulnerability-view-switch button:hover {
color: var(--text-primary);
}
.vulnerability-view-switch button[aria-pressed="true"] {
background: var(--bg-primary);
color: var(--text-primary);
font-weight: 600;
box-shadow: var(--shadow-sm);
}
.vulnerability-view-switch button:focus-visible {
outline: 2px solid var(--accent-color);
outline-offset: -2px;
}
.vulnerability-group {
min-width: 0;
border: 1px solid var(--border-color);
border-radius: 8px;
background: var(--bg-secondary);
}
.vulnerability-host-group > summary {
.vulnerability-group > summary {
padding: 12px 16px;
cursor: pointer;
overflow-wrap: anywhere;
}
.vulnerability-host-group > summary:focus-visible {
.vulnerability-group > summary:focus-visible {
outline: 2px solid var(--accent-color);
outline-offset: -2px;
border-radius: 8px;
}
.vulnerability-host-name {
.vulnerability-group-name {
margin-inline-start: 6px;
font-weight: 600;
}
.vulnerability-host-count {
.vulnerability-group-count {
margin-inline-start: 8px;
color: var(--text-muted);
font-size: 0.8125rem;
}
.vulnerability-host-cards {
.vulnerability-group-cards {
display: grid;
gap: 10px;
padding: 0 12px 12px;

View File

@ -2770,7 +2770,13 @@
"loadListFailed": "فشل التحميل",
"noRecords": "لا توجد سجلات ثغرات",
"unknownHost": "مضيف غير معروف",
"hostPageCount": "{{count}} في هذه الصفحة",
"groupPageCount": "{{count}} في هذه الصفحة",
"viewLabel": "عرض الثغرات",
"viewHost": "حسب المضيف",
"viewTask": "حسب المهمة",
"viewRaw": "السجلات الأصلية",
"viewTaskGroup": "المهمة {{id}}",
"viewNoTask": "لا توجد مهمة مرتبطة",
"batchExport": "تصدير جماعي",
"batchDelete": "حذف جماعي",
"batchDeleteNoResults": "لا توجد ثغرات تطابق عوامل التصفية الحالية لحذفها",

View File

@ -2913,7 +2913,13 @@
"loadListFailed": "Failed to load",
"noRecords": "No vulnerability records",
"unknownHost": "Unknown host",
"hostPageCount": "{{count}} on this page",
"groupPageCount": "{{count}} on this page",
"viewLabel": "Vulnerability view",
"viewHost": "By host",
"viewTask": "By task",
"viewRaw": "Raw records",
"viewTaskGroup": "Task {{id}}",
"viewNoTask": "No linked task",
"batchExport": "Batch export",
"batchDelete": "Batch delete",
"batchDeleteNoResults": "No vulnerabilities match the current filters to delete",

View File

@ -2926,7 +2926,13 @@
"loadListFailed": "Не удалось загрузить",
"noRecords": "Нет записей об уязвимостях",
"unknownHost": "Неизвестный хост",
"hostPageCount": "На этой странице: {{count}}",
"groupPageCount": "На этой странице: {{count}}",
"viewLabel": "Вид списка уязвимостей",
"viewHost": "По хостам",
"viewTask": "По задачам",
"viewRaw": "Исходные записи",
"viewTaskGroup": "Задача {{id}}",
"viewNoTask": "Без связанной задачи",
"batchExport": "Пакетный экспорт",
"batchDelete": "Пакетное удаление",
"batchDeleteNoResults": "Нет уязвимостей по текущим фильтрам для удаления",

View File

@ -2901,7 +2901,13 @@
"loadListFailed": "加载失败",
"noRecords": "暂无漏洞记录",
"unknownHost": "未识别到主机",
"hostPageCount": "本页 {{count}} 条",
"groupPageCount": "本页 {{count}} 条",
"viewLabel": "漏洞视图",
"viewHost": "按域名",
"viewTask": "按任务",
"viewRaw": "原始记录",
"viewTaskGroup": "任务 {{id}}",
"viewNoTask": "未关联任务",
"batchExport": "批量导出",
"batchDelete": "批量删除",
"batchDeleteNoResults": "当前筛选条件下没有可删除的漏洞",

View File

@ -252,6 +252,10 @@ let vulnerabilityPagination = {
total: 0,
totalPages: 1
};
const VULNERABILITY_VIEWS = ['host', 'task', 'none'];
const savedVulnerabilityView = localStorage.getItem('vulnerabilityListView');
let vulnerabilityView = VULNERABILITY_VIEWS.includes(savedVulnerabilityView) ? savedVulnerabilityView : 'host';
let vulnerabilityListRequest = 0;
const VULN_STAT_SEVERITIES = ['critical', 'high', 'medium', 'low', 'info'];
let vulnerabilityStatCardsBound = false;
@ -373,6 +377,7 @@ async function initVulnerabilityPage() {
vulnerabilityPagination.pageSize = getVulnerabilityPageSize();
initVulnerabilityStatCards();
initVulnerabilityFilterPanel();
initVulnerabilityViewSwitch();
syncVulnerabilityFiltersFromLocationHash();
await refreshVulnerabilityProjectFilter();
updateVulnerabilityFilterPanelState();
@ -382,6 +387,27 @@ async function initVulnerabilityPage() {
loadVulnerabilities();
}
function initVulnerabilityViewSwitch() {
const control = document.getElementById('vulnerability-view-switch');
if (!control || control.dataset.bound) return;
control.dataset.bound = 'true';
const buttons = control.querySelectorAll('button[data-vuln-view]');
const updateSelection = () => buttons.forEach(button => {
button.setAttribute('aria-pressed', String(button.dataset.vulnView === vulnerabilityView));
});
updateSelection();
control.addEventListener('click', event => {
const view = event.target.closest('button[data-vuln-view]')?.dataset.vulnView;
if (!VULNERABILITY_VIEWS.includes(view) || view === vulnerabilityView) return;
vulnerabilityView = view;
localStorage.setItem('vulnerabilityListView', view);
updateSelection();
const scroll = getVulnerabilityScrollContainer();
if (scroll) scroll.scrollTop = 0;
loadVulnerabilities(1);
});
}
function initVulnerabilityStatCards() {
if (vulnerabilityStatCardsBound) {
syncVulnerabilityStatCardActiveState();
@ -1251,6 +1277,8 @@ function updateVulnerabilityStats(stats) {
// 加载漏洞列表
async function loadVulnerabilities(page = null, options = {}) {
const request = ++vulnerabilityListRequest;
const view = vulnerabilityView;
const opts = options && typeof options === 'object' ? options : {};
const preserveScroll = !!opts.preserveScroll;
const silent = !!opts.silent;
@ -1264,7 +1292,7 @@ async function loadVulnerabilities(page = null, options = {}) {
const listContainer = document.getElementById('vulnerabilities-list');
const groupOpenStates = preserveScroll
? new Map(Array.from(listContainer.querySelectorAll('.vulnerability-host-group'), group => [group.dataset.host, group.open]))
? new Map(Array.from(listContainer.querySelectorAll('.vulnerability-group'), group => [group.dataset.groupKey, group.open]))
: new Map();
if (!silent) {
listContainer.innerHTML = `<div class="loading-spinner">${escapeHtml(vulnT('vulnerabilityPage.loading'))}</div>`;
@ -1283,7 +1311,7 @@ async function loadVulnerabilities(page = null, options = {}) {
}
const params = buildVulnerabilityFilterParams();
params.append('group_by', 'host');
params.append('group_by', view);
params.append('page', vulnerabilityPagination.currentPage.toString());
params.append('limit', vulnerabilityPagination.pageSize.toString());
@ -1295,6 +1323,7 @@ async function loadVulnerabilities(page = null, options = {}) {
}
const data = await response.json();
if (request !== vulnerabilityListRequest) return;
// 判断响应格式:新格式(有total字段)还是旧格式(直接是数组)
let vulnerabilities;
@ -1318,15 +1347,16 @@ async function loadVulnerabilities(page = null, options = {}) {
console.error('未知的响应格式:', data);
}
renderVulnerabilities(vulnerabilities, { expandedIds: expandedIds || [], groupOpenStates });
renderVulnerabilities(vulnerabilities, { view, expandedIds: expandedIds || [], groupOpenStates });
renderVulnerabilityPagination();
if (preserveScroll && scrollEl) {
requestAnimationFrame(function () {
scrollEl.scrollTop = scrollTop;
if (request === vulnerabilityListRequest) scrollEl.scrollTop = scrollTop;
});
}
} catch (error) {
if (request !== vulnerabilityListRequest) return;
console.error('加载漏洞列表失败:', error);
listContainer.innerHTML = `<div class="error-message">${escapeHtml(vulnT('vulnerabilityPage.loadListFailed'))}: ${escapeHtml(error.message)}</div>`;
}
@ -1345,39 +1375,52 @@ function renderVulnerabilities(vulnerabilities, renderOptions) {
return;
}
const groups = new Map();
for (const vuln of vulnerabilities) {
const host = vuln.target_host || '';
if (!groups.has(host)) groups.set(host, []);
groups.get(host).push(vuln);
}
const exactMatch = vulnerabilities.length === 1 && vulnerabilityFilters.id === vulnerabilities[0].id
? vulnerabilities[0].id
: null;
const expandedIds = new Set(opts.expandedIds);
listContainer.innerHTML = Array.from(groups, ([host, items], index) => {
const open = exactMatch || (opts.groupOpenStates?.get(host) ??
(index === 0 || items.some(vuln => expandedIds.has(vuln.id))));
const label = host || vulnT('vulnerabilityPage.unknownHost');
const count = vulnT('vulnerabilityPage.hostPageCount', { count: items.length });
return `
<details class="vulnerability-host-group" data-host="${escapeAttr(host)}"${open ? ' open' : ''}>
<summary>
<span class="vulnerability-host-name">${escapeHtml(label)}</span>
<span class="vulnerability-host-count">${escapeHtml(count)}</span>
</summary>
<div class="vulnerability-host-cards">${items.map(renderVulnerabilityCard).join('')}</div>
</details>
`;
}).join('');
const expandedIds = exactMatch ? [exactMatch] : opts.expandedIds;
listContainer.innerHTML = opts.view === 'none'
? vulnerabilities.map(renderVulnerabilityCard).join('')
: renderVulnerabilityGroups(vulnerabilities, { ...opts, expandedIds });
initVulnerabilityStatusPickers(listContainer);
initVulnerabilityProjectBindSelects(listContainer);
if (typeof window.applyTranslations === 'function') {
window.applyTranslations(listContainer);
}
if (typeof rbacAfterDynamicRender === 'function') rbacAfterDynamicRender(listContainer);
restoreExpandedVulnerabilityDetails(expandedIds);
}
restoreExpandedVulnerabilityDetails(exactMatch ? [exactMatch] : opts.expandedIds);
function renderVulnerabilityGroups(vulnerabilities, opts) {
const groups = new Map();
for (const vuln of vulnerabilities) {
let key = vuln.target_host || '';
let label = key || vulnT('vulnerabilityPage.unknownHost');
if (opts.view === 'task') {
const taskTag = (vuln.task_tag || '').replace(/^ +| +$/g, '');
key = vuln.task_id ? 'id:' + vuln.task_id : 'tag:' + taskTag;
label = vuln.task_id
? vulnT('vulnerabilityPage.viewTaskGroup', { id: vuln.task_id })
: taskTag || vulnT('vulnerabilityPage.viewNoTask');
}
if (!groups.has(key)) groups.set(key, { label, items: [] });
groups.get(key).items.push(vuln);
}
const expandedIds = new Set(opts.expandedIds);
return Array.from(groups, ([key, { label, items }], index) => {
const open = items.some(vuln => vulnerabilityFilters.id === vuln.id) ||
(opts.groupOpenStates?.get(key) ?? (index === 0 || items.some(vuln => expandedIds.has(vuln.id))));
const count = vulnT('vulnerabilityPage.groupPageCount', { count: items.length });
return `
<details class="vulnerability-group" data-group-key="${escapeAttr(key)}"${open ? ' open' : ''}>
<summary>
<span class="vulnerability-group-name">${escapeHtml(label)}</span>
<span class="vulnerability-group-count">${escapeHtml(count)}</span>
</summary>
<div class="vulnerability-group-cards">${items.map(renderVulnerabilityCard).join('')}</div>
</details>
`;
}).join('');
}
function renderVulnerabilityCard(vuln) {

View File

@ -39,7 +39,7 @@
}
})();
</script>
<link rel="stylesheet" href="/static/css/style.css?v=20261113-vulnerability-host-groups">
<link rel="stylesheet" href="/static/css/style.css?v=20261113-vulnerability-views">
<link rel="stylesheet" href="/static/css/vulnerability-download.css?v=20261030-2">
<link rel="stylesheet" href="/static/css/tool-guard.css?v=20260907-7">
<link rel="stylesheet" href="/static/css/chat-plan-progress.css?v=20260813-4">
@ -2695,7 +2695,15 @@
<!-- 漏洞管理页面 -->
<div id="page-vulnerabilities" class="page">
<div class="page-header">
<h2 data-i18n="vulnerability.title">漏洞管理</h2>
<div class="vulnerability-header-start">
<h2 data-i18n="vulnerability.title">漏洞管理</h2>
<div id="vulnerability-view-switch" class="vulnerability-view-switch" role="group"
aria-label="漏洞视图" data-i18n="vulnerabilityPage.viewLabel" data-i18n-attr="aria-label">
<button type="button" data-vuln-view="host" aria-pressed="true" data-i18n="vulnerabilityPage.viewHost">按域名</button>
<button type="button" data-vuln-view="task" aria-pressed="false" data-i18n="vulnerabilityPage.viewTask">按任务</button>
<button type="button" data-vuln-view="none" aria-pressed="false" data-i18n="vulnerabilityPage.viewRaw">原始记录</button>
</div>
</div>
<div class="page-header-actions">
<button class="btn-secondary" data-require-permission="vulnerability:read" onclick="exportVulnerabilityReports()" data-i18n="vulnerabilityPage.batchExport">批量导出</button>
<button class="btn-secondary btn-delete" data-require-permission="vulnerability:delete" onclick="batchDeleteVulnerabilityReports()" data-i18n="vulnerabilityPage.batchDelete">批量删除</button>
@ -7081,7 +7089,7 @@
<script src="/static/js/skills.js?v=20261103-personal-integration"></script>
<script src="/static/js/fact-graph.js"></script>
<script src="/static/js/projects.js?v=20260819-1-pagination-20261027"></script>
<script src="/static/js/vulnerability.js?v=20261113-vulnerability-host-groups"></script>
<script src="/static/js/vulnerability.js?v=20261113-vulnerability-views"></script>
<script src="/static/js/vulnerability-download.js?v=20261030-2"></script>
<script src="/static/js/webshell.js?v=20261011-token-usage-tool-title"></script>
<script src="/static/js/chat-files.js?v=20261103-personal-integration"></script>