diff --git a/internal/database/rbac_access_test.go b/internal/database/rbac_access_test.go index 4d71953d..504a9e62 100644 --- a/internal/database/rbac_access_test.go +++ b/internal/database/rbac_access_test.go @@ -220,8 +220,8 @@ func TestRBACVulnerabilityAccessInheritsProject(t *testing.T) { if err := db.AssignResourceToUser(user.ID, "project", p1.ID); err != nil { t.Fatal(err) } - v1, _ := db.CreateVulnerability(&Vulnerability{ProjectID: p1.ID, Title: "v1", Severity: "high"}) - v2, _ := db.CreateVulnerability(&Vulnerability{ProjectID: p2.ID, Title: "v2", Severity: "high"}) + v1, _ := db.CreateVulnerability(&Vulnerability{ProjectID: p1.ID, Title: "v1", Severity: "high", Target: "https://example.com/visible"}) + v2, _ := db.CreateVulnerability(&Vulnerability{ProjectID: p2.ID, Title: "v2", Severity: "high", Target: "https://example.com/hidden"}) items, err := db.ListVulnerabilitiesForAccess(50, 0, VulnerabilityListFilter{}, RBACListAccess{UserID: user.ID, Scope: RBACScopeAssigned}) if err != nil { @@ -230,6 +230,13 @@ func TestRBACVulnerabilityAccessInheritsProject(t *testing.T) { if len(items) != 1 || items[0].ID != v1.ID { t.Fatalf("vulnerabilities = %#v, want only %s; hidden %s", items, v1.ID, v2.ID) } + for _, group := range []string{"host", "task"} { + access := RBACListAccess{UserID: user.ID, Scope: RBACScopeAssigned} + items, err := db.ListVulnerabilitiesByGroupForAccess(1, 0, VulnerabilityListFilter{}, access, group) + if err != nil || len(items) != 1 || items[0].ID != v1.ID { + t.Fatalf("group %s returned %#v, %v; want only %s", group, items, err, v1.ID) + } + } if !db.UserCanAccessResource(user.ID, RBACScopeAssigned, "vulnerability", v1.ID) { t.Fatalf("expected project assignment to allow vulnerability detail") } diff --git a/internal/database/vulnerability.go b/internal/database/vulnerability.go index 1acd99cb..e0e285d9 100644 --- a/internal/database/vulnerability.go +++ b/internal/database/vulnerability.go @@ -288,36 +288,80 @@ func vulnerabilityTargetHost(target string) string { return host } -func (db *DB) ListVulnerabilitiesByGroupForAccess(limit, offset int, filter VulnerabilityListFilter, access RBACListAccess, groupBy string) ([]*Vulnerability, error) { - hostExpr, order := "NULL", "created_at DESC" +const vulnerabilityTaskIDExpr = `COALESCE((SELECT bt.id FROM batch_tasks bt + WHERE bt.conversation_id = vulnerabilities.conversation_id ORDER BY bt.id LIMIT 1), '')` + +func vulnerabilityGroupQuery(filter VulnerabilityListFilter, access RBACListAccess, groupBy string) (string, []interface{}) { + var key string switch groupBy { case "host": - hostExpr = "vulnerability_target_host(target)" - order = "target_host = '', target_host, created_at DESC, id" + key = "vulnerability_target_host(target)" 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": + key = `CASE + WHEN ` + vulnerabilityTaskIDExpr + ` <> '' THEN 'id:' || ` + vulnerabilityTaskIDExpr + ` + WHEN TRIM(task_tag) <> '' THEN 'tag:' || TRIM(task_tag) + ELSE '' END` + default: + return "", nil + } + query := "SELECT id, " + key + " AS group_key FROM vulnerabilities WHERE 1=1" + query, args := filter.appendWhere(query, nil) + return appendVulnerabilityAccessFilter(query, args, access) +} + +func (db *DB) CountVulnerabilityGroupsForAccess(filter VulnerabilityListFilter, access RBACListAccess, groupBy string) (int, error) { + query, args := vulnerabilityGroupQuery(filter, access, groupBy) + if query == "" { + return db.CountVulnerabilitiesForAccess(filter, access) + } + var count int + err := db.QueryRow("SELECT COUNT(DISTINCT group_key) FROM ("+query+")", args...).Scan(&count) + return count, err +} + +func (db *DB) ListVulnerabilitiesByGroupForAccess(limit, offset int, filter VulnerabilityListFilter, access RBACListAccess, groupBy string) ([]*Vulnerability, error) { + hostExpr, order := "NULL", "created_at DESC" + groupQuery, args := vulnerabilityGroupQuery(filter, access, groupBy) + var prefix, join string + if groupQuery != "" { + prefix = `WITH scoped AS (` + groupQuery + `), + page_groups AS ( + SELECT group_key FROM scoped GROUP BY group_key + ORDER BY group_key = '', group_key LIMIT ? OFFSET ? + ), + page_items AS ( + SELECT scoped.id, scoped.group_key + FROM scoped JOIN page_groups USING (group_key) + )` + args = append(args, limit, offset) + join = " JOIN page_items USING (id)" + order = "group_key = '', group_key, created_at DESC, id" + if groupBy == "host" { + hostExpr = "group_key" + } + } else if groupBy == "none" { order = "created_at DESC, id" } - query := ` + query := prefix + ` 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 ORDER BY bt.id LIMIT 1), '') AS task_id, + ` + vulnerabilityTaskIDExpr + ` 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 + FROM vulnerabilities` + join + ` WHERE 1=1 ` - args := []interface{}{} - query, args = filter.appendWhere(query, args) - query, args = appendVulnerabilityAccessFilter(query, args, access) - - query += " ORDER BY " + order + " LIMIT ? OFFSET ?" - args = append(args, limit, offset) + if groupQuery == "" { + query, args = filter.appendWhere(query, args) + query, args = appendVulnerabilityAccessFilter(query, args, access) + } + query += " ORDER BY " + order + if groupQuery == "" { + query += " LIMIT ? OFFSET ?" + args = append(args, limit, offset) + } rows, err := db.Query(query, args...) if err != nil { diff --git a/internal/handler/vulnerability.go b/internal/handler/vulnerability.go index fb580b2b..d68538f3 100644 --- a/internal/handler/vulnerability.go +++ b/internal/handler/vulnerability.go @@ -206,7 +206,7 @@ func (h *VulnerabilityHandler) ListVulnerabilities(c *gin.Context) { } // 获取总数 - total, err := h.db.CountVulnerabilitiesForAccess(filter, access) + total, err := h.db.CountVulnerabilityGroupsForAccess(filter, access, groupBy) if err != nil { h.logger.Error("获取漏洞总数失败", zap.Error(err)) // 继续执行,使用0作为总数 diff --git a/internal/handler/vulnerability_group_test.go b/internal/handler/vulnerability_group_test.go index f34c423b..bc7f31aa 100644 --- a/internal/handler/vulnerability_group_test.go +++ b/internal/handler/vulnerability_group_test.go @@ -40,7 +40,7 @@ func TestListVulnerabilitiesGroupedViews(t *testing.T) { {"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", "", ""}, + {"filtered", "https://example.com/filtered", "low", "a", linked.ID}, } { _, err := db.CreateVulnerability(&database.Vulnerability{ ID: item.id, Target: item.target, Title: item.id, Severity: item.severity, @@ -70,22 +70,21 @@ func TestListVulnerabilitiesGroupedViews(t *testing.T) { } for _, tc := range []struct { - query string - page int - ids, hosts []string + query string + page, total, pages int + ids, hosts []string }{ - {"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}, + {"group_by=host&page=1", 1, 4, 2, []string{"ipv6", "domain-new", "domain-old"}, []string{"2001:db8::1", "example.com", "example.com"}}, + {"group_by=host&page=4", 2, 4, 2, []string{"subdomain", "unknown"}, []string{"sub.example.com", ""}}, + {"group_by=task&page=1", 1, 3, 2, []string{"ipv6", "domain-new", "subdomain", "domain-old"}, nil}, + {"group_by=task&page=2", 2, 3, 2, []string{"unknown"}, nil}, + {"group_by=none&page=1", 1, 5, 3, []string{"unknown", "ipv6"}, nil}, + {"page=1", 1, 5, 3, []string{"unknown", "ipv6"}, nil}, } { t.Run(tc.query, func(t *testing.T) { result := fetch(tc.query) - if result.Total != 5 || result.TotalPages != 3 || result.Page != tc.page || len(result.Vulnerabilities) != len(tc.ids) { + if result.Total != tc.total || result.TotalPages != tc.pages || result.Page != tc.page || + result.PageSize != 2 || len(result.Vulnerabilities) != len(tc.ids) { t.Fatalf("unexpected pagination: %+v", result) } for i, v := range result.Vulnerabilities { diff --git a/web/static/i18n/ar-SA.json b/web/static/i18n/ar-SA.json index 5d4de63e..c25b7f22 100644 --- a/web/static/i18n/ar-SA.json +++ b/web/static/i18n/ar-SA.json @@ -2770,7 +2770,10 @@ "loadListFailed": "فشل التحميل", "noRecords": "لا توجد سجلات ثغرات", "unknownHost": "مضيف غير معروف", - "groupPageCount": "{{count}} في هذه الصفحة", + "groupPageCount": "الثغرات: {{count}}", + "hostPagination": "عرض {{start}}–{{end}} من أصل {{total}} مجموعة حسب المضيف", + "taskPagination": "عرض {{start}}–{{end}} من أصل {{total}} مجموعة حسب المهمة", + "recordPagination": "عرض {{start}}–{{end}} من أصل {{total}} سجل ثغرة", "viewLabel": "عرض الثغرات", "viewHost": "حسب المضيف", "viewTask": "حسب المهمة", diff --git a/web/static/i18n/en-US.json b/web/static/i18n/en-US.json index 506855bc..130ccd32 100644 --- a/web/static/i18n/en-US.json +++ b/web/static/i18n/en-US.json @@ -2913,7 +2913,10 @@ "loadListFailed": "Failed to load", "noRecords": "No vulnerability records", "unknownHost": "Unknown host", - "groupPageCount": "{{count}} on this page", + "groupPageCount": "Findings: {{count}}", + "hostPagination": "Showing {{start}}–{{end}} of {{total}} host groups", + "taskPagination": "Showing {{start}}–{{end}} of {{total}} task groups", + "recordPagination": "Showing {{start}}–{{end}} of {{total}} findings", "viewLabel": "Vulnerability view", "viewHost": "By host", "viewTask": "By task", diff --git a/web/static/i18n/ru-RU.json b/web/static/i18n/ru-RU.json index 36021303..64dcad98 100644 --- a/web/static/i18n/ru-RU.json +++ b/web/static/i18n/ru-RU.json @@ -2926,7 +2926,10 @@ "loadListFailed": "Не удалось загрузить", "noRecords": "Нет записей об уязвимостях", "unknownHost": "Неизвестный хост", - "groupPageCount": "На этой странице: {{count}}", + "groupPageCount": "Уязвимостей: {{count}}", + "hostPagination": "Показано {{start}}–{{end}} из {{total}} групп по хостам", + "taskPagination": "Показано {{start}}–{{end}} из {{total}} групп по задачам", + "recordPagination": "Показано {{start}}–{{end}} из {{total}} записей", "viewLabel": "Вид списка уязвимостей", "viewHost": "По хостам", "viewTask": "По задачам", diff --git a/web/static/i18n/zh-CN.json b/web/static/i18n/zh-CN.json index b1eadc22..7c9d9e5f 100644 --- a/web/static/i18n/zh-CN.json +++ b/web/static/i18n/zh-CN.json @@ -2901,7 +2901,10 @@ "loadListFailed": "加载失败", "noRecords": "暂无漏洞记录", "unknownHost": "未识别到主机", - "groupPageCount": "本页 {{count}} 条", + "groupPageCount": "{{count}} 条漏洞", + "hostPagination": "显示 {{start}}–{{end}} / 共 {{total}} 个域名组", + "taskPagination": "显示 {{start}}–{{end}} / 共 {{total}} 个任务组", + "recordPagination": "显示 {{start}}–{{end}} / 共 {{total}} 条漏洞", "viewLabel": "漏洞视图", "viewHost": "按域名", "viewTask": "按任务", diff --git a/web/static/js/vulnerability.js b/web/static/js/vulnerability.js index d24bd38a..d5053061 100644 --- a/web/static/js/vulnerability.js +++ b/web/static/js/vulnerability.js @@ -1513,6 +1513,11 @@ function renderVulnerabilityPagination() { } const { currentPage, totalPages, total, pageSize } = vulnerabilityPagination; + const paginationLabel = { + host: 'vulnerabilityPage.hostPagination', + task: 'vulnerabilityPage.taskPagination', + none: 'vulnerabilityPage.recordPagination' + }[vulnerabilityView]; // 计算显示范围 const start = total === 0 ? 0 : (currentPage - 1) * pageSize + 1; @@ -1523,7 +1528,7 @@ function renderVulnerabilityPagination() { // 左侧:显示范围信息和每页数量选择器(参考Skills样式) paginationHTML += `