mirror of
https://github.com/Ed1s0nZ/CyberStrikeAI.git
synced 2026-12-01 12:03:26 +01:00
Merge pull request #404 from Sycun/codex/vulnerability-record-pagination
fix(vulnerabilities): paginate findings independently of full navigation
This commit is contained in:
11 files changed
+432
-118
No files matched your search
@@ -17,19 +17,20 @@ import (
|
||||
|
||||
// VulnerabilityListFilter 列表/统计/导出共用的筛选条件
|
||||
type VulnerabilityListFilter struct {
|
||||
ID string
|
||||
Search string // 关键词模糊匹配(标题、描述、类型、目标等)
|
||||
HostQuery string
|
||||
TaskQuery string
|
||||
CaseID string
|
||||
SummaryOnly bool
|
||||
ConversationID string
|
||||
ProjectID string
|
||||
Severity string
|
||||
Status string
|
||||
TaskID string
|
||||
ConversationTag string
|
||||
TaskTag string
|
||||
BrowserSelection string
|
||||
ID string
|
||||
Search string // 关键词模糊匹配(标题、描述、类型、目标等)
|
||||
HostQuery string
|
||||
TaskQuery string
|
||||
CaseID string
|
||||
SummaryOnly bool
|
||||
ConversationID string
|
||||
ProjectID string
|
||||
Severity string
|
||||
Status string
|
||||
TaskID string
|
||||
ConversationTag string
|
||||
TaskTag string
|
||||
}
|
||||
|
||||
type RBACListAccess struct {
|
||||
@@ -45,6 +46,7 @@ func escapeVulnerabilityLikePattern(s string) string {
|
||||
}
|
||||
|
||||
func (f VulnerabilityListFilter) appendWhere(query string, args []interface{}) (string, []interface{}) {
|
||||
query, args = appendVulnerabilitySelection(query, args, f.BrowserSelection)
|
||||
if host := strings.TrimSpace(f.HostQuery); host != "" {
|
||||
query += ` AND EXISTS (SELECT 1 FROM json_each(targets_json) jt WHERE json_extract(jt.value,'$.host') LIKE ? ESCAPE '\')`
|
||||
args = append(args, escapeVulnerabilityLikePattern(strings.ToLower(host)))
|
||||
|
||||
@@ -0,0 +1,152 @@
|
||||
package database
|
||||
|
||||
import (
|
||||
"net/netip"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"golang.org/x/net/publicsuffix"
|
||||
)
|
||||
|
||||
// VulnerabilityNavigation contains counts across the entire filtered result set.
|
||||
// Records can belong to several hosts, so parent counts are deduplicated by ID.
|
||||
type VulnerabilityNavigation struct {
|
||||
Key string `json:"key"`
|
||||
Label string `json:"label"`
|
||||
Count int `json:"count"`
|
||||
Severities map[string]int `json:"severities"`
|
||||
Pending int `json:"pending"`
|
||||
Children []*VulnerabilityNavigation `json:"children,omitempty"`
|
||||
}
|
||||
|
||||
type vulnerabilityNavigationCount struct {
|
||||
node *VulnerabilityNavigation
|
||||
ids map[string]bool
|
||||
}
|
||||
|
||||
func (g *vulnerabilityNavigationCount) add(id, severity, status string) {
|
||||
if g.ids[id] {
|
||||
return
|
||||
}
|
||||
g.ids[id] = true
|
||||
g.node.Count++
|
||||
g.node.Severities[severity]++
|
||||
if status == "" || status == "open" || status == "confirmed" {
|
||||
g.node.Pending++
|
||||
}
|
||||
}
|
||||
|
||||
const vulnerabilityQueueIDExpr = `COALESCE((SELECT bt.queue_id FROM batch_tasks bt WHERE bt.conversation_id=vulnerabilities.conversation_id ORDER BY bt.id LIMIT 1),'')`
|
||||
|
||||
// appendVulnerabilitySelection restricts records without joining/duplicating them.
|
||||
func appendVulnerabilitySelection(query string, args []interface{}, selection string) (string, []interface{}) {
|
||||
kind, value, _ := strings.Cut(selection, ":")
|
||||
host := `COALESCE(json_extract(jt.value,'$.host'),'')`
|
||||
switch kind {
|
||||
case "host":
|
||||
if value == "" {
|
||||
query += ` AND NOT EXISTS(SELECT 1 FROM json_each(targets_json) jt WHERE json_extract(jt.value,'$.group_host')=1 AND ` + host + `<>'')`
|
||||
} else {
|
||||
query += ` AND EXISTS(SELECT 1 FROM json_each(targets_json) jt WHERE json_extract(jt.value,'$.group_host')=1 AND ` + host + `=?)`
|
||||
args = append(args, value)
|
||||
}
|
||||
case "domain":
|
||||
query += ` AND EXISTS(SELECT 1 FROM json_each(targets_json) jt WHERE json_extract(jt.value,'$.group_host')=1 AND (` + host + `=? OR ` + host + ` LIKE ? ESCAPE '\'))`
|
||||
querySuffix := strings.TrimSuffix(escapeVulnerabilityLikePattern("."+value), "%")
|
||||
args = append(args, value, querySuffix)
|
||||
case "task":
|
||||
query += " AND " + vulnerabilityTaskIDExpr + "=?"
|
||||
args = append(args, value)
|
||||
case "queue":
|
||||
query += " AND " + vulnerabilityQueueIDExpr + "=?"
|
||||
args = append(args, value)
|
||||
case "tag":
|
||||
query += " AND " + vulnerabilityTaskIDExpr + "='' AND TRIM(COALESCE(task_tag,''))=?"
|
||||
args = append(args, value)
|
||||
}
|
||||
return query, args
|
||||
}
|
||||
|
||||
func (db *DB) VulnerabilityNavigationForAccess(filter VulnerabilityListFilter, access RBACListAccess, view string) ([]*VulnerabilityNavigation, error) {
|
||||
filter.BrowserSelection = ""
|
||||
fields, join := `COALESCE(json_extract(jt.value,'$.host'),''), '', ''`, ` LEFT JOIN json_each(targets_json) jt ON json_extract(jt.value,'$.group_host')=1`
|
||||
if view == "task" {
|
||||
fields = vulnerabilityTaskIDExpr + ", " + vulnerabilityQueueIDExpr + `, COALESCE((SELECT bq.title FROM batch_tasks bt JOIN batch_task_queues bq ON bq.id=bt.queue_id WHERE bt.conversation_id=vulnerabilities.conversation_id ORDER BY bt.id LIMIT 1),'')`
|
||||
join = ""
|
||||
}
|
||||
query := `SELECT DISTINCT vulnerabilities.id, severity, COALESCE(status,''), COALESCE(task_tag,''), ` + fields + ` FROM vulnerabilities` + join + ` WHERE 1=1`
|
||||
query, args := filter.appendWhere(query, nil)
|
||||
if view == "host" && strings.TrimSpace(filter.HostQuery) != "" {
|
||||
query += ` AND json_extract(jt.value,'$.host') LIKE ? ESCAPE '\'`
|
||||
args = append(args, escapeVulnerabilityLikePattern(strings.ToLower(strings.TrimSpace(filter.HostQuery))))
|
||||
}
|
||||
query, args = appendVulnerabilityAccessFilter(query, args, access)
|
||||
rows, err := db.Query(query, args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
roots := map[string]*vulnerabilityNavigationCount{}
|
||||
children := map[string]map[string]*vulnerabilityNavigationCount{}
|
||||
makeCount := func(key, label string) *vulnerabilityNavigationCount {
|
||||
return &vulnerabilityNavigationCount{node: &VulnerabilityNavigation{Key: key, Label: label, Severities: map[string]int{}}, ids: map[string]bool{}}
|
||||
}
|
||||
for rows.Next() {
|
||||
var id, severity, status, tag, target, queue, queueTitle string
|
||||
if err := rows.Scan(&id, &severity, &status, &tag, &target, &queue, &queueTitle); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
key, label := "host:"+target, target
|
||||
rootKey, rootLabel := key, label
|
||||
if view == "host" {
|
||||
if _, err := netip.ParseAddr(target); err != nil {
|
||||
if domain, err := publicsuffix.EffectiveTLDPlusOne(target); err == nil {
|
||||
rootKey, rootLabel = "domain:"+domain, domain
|
||||
}
|
||||
}
|
||||
} else {
|
||||
key, label = "tag:"+strings.Trim(tag, " "), strings.Trim(tag, " ")
|
||||
if target != "" {
|
||||
key, label = "task:"+target, target
|
||||
}
|
||||
rootKey, rootLabel = key, label
|
||||
if target != "" && queue != "" {
|
||||
rootKey, rootLabel = "queue:"+queue, queueTitle
|
||||
}
|
||||
}
|
||||
if roots[rootKey] == nil {
|
||||
roots[rootKey] = makeCount(rootKey, rootLabel)
|
||||
children[rootKey] = map[string]*vulnerabilityNavigationCount{}
|
||||
}
|
||||
roots[rootKey].add(id, severity, status)
|
||||
if key != rootKey {
|
||||
if children[rootKey][key] == nil {
|
||||
children[rootKey][key] = makeCount(key, label)
|
||||
}
|
||||
children[rootKey][key].add(id, severity, status)
|
||||
}
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result := make([]*VulnerabilityNavigation, 0, len(roots))
|
||||
less := func(a, b *VulnerabilityNavigation) bool {
|
||||
if (a.Label == "") != (b.Label == "") {
|
||||
return b.Label == ""
|
||||
}
|
||||
return a.Key < b.Key
|
||||
}
|
||||
for key, g := range roots {
|
||||
for _, child := range children[key] {
|
||||
g.node.Children = append(g.node.Children, child.node)
|
||||
}
|
||||
sort.Slice(g.node.Children, func(i, j int) bool { return less(g.node.Children[i], g.node.Children[j]) })
|
||||
// Avoid a redundant parent when a domain has only its own host.
|
||||
if len(g.node.Children) == 1 && g.node.Children[0].Label == g.node.Label {
|
||||
g.node = g.node.Children[0]
|
||||
}
|
||||
result = append(result, g.node)
|
||||
}
|
||||
sort.Slice(result, func(i, j int) bool { return less(result[i], result[j]) })
|
||||
return result, nil
|
||||
}
|
||||
@@ -152,11 +152,13 @@ func (h *VulnerabilityHandler) GetVulnerability(c *gin.Context) {
|
||||
|
||||
// ListVulnerabilitiesResponse 漏洞列表响应
|
||||
type ListVulnerabilitiesResponse struct {
|
||||
Vulnerabilities []*database.Vulnerability `json:"vulnerabilities"`
|
||||
Total int `json:"total"`
|
||||
Page int `json:"page"`
|
||||
PageSize int `json:"page_size"`
|
||||
TotalPages int `json:"total_pages"`
|
||||
Navigation []*database.VulnerabilityNavigation `json:"navigation,omitempty"`
|
||||
Selection string `json:"selection"`
|
||||
Vulnerabilities []*database.Vulnerability `json:"vulnerabilities"`
|
||||
Total int `json:"total"`
|
||||
Page int `json:"page"`
|
||||
PageSize int `json:"page_size"`
|
||||
TotalPages int `json:"total_pages"`
|
||||
}
|
||||
|
||||
func parseVulnerabilityListFilter(c *gin.Context) database.VulnerabilityListFilter {
|
||||
@@ -214,6 +216,30 @@ func (h *VulnerabilityHandler) ListVulnerabilities(c *gin.Context) {
|
||||
offset = 0
|
||||
}
|
||||
|
||||
// The browser paginates records while its navigation covers all matching groups.
|
||||
var navigation []*database.VulnerabilityNavigation
|
||||
if c.Query("pagination") == "records" && (groupBy == "host" || groupBy == "task") {
|
||||
var err error
|
||||
navigation, err = h.db.VulnerabilityNavigationForAccess(filter, access, groupBy)
|
||||
if err != nil {
|
||||
h.logger.Error("获取漏洞导航失败", zap.Error(err))
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
selection := c.Query("selection")
|
||||
for _, node := range navigation {
|
||||
if node.Key == selection {
|
||||
filter.BrowserSelection = selection
|
||||
}
|
||||
for _, child := range node.Children {
|
||||
if child.Key == selection {
|
||||
filter.BrowserSelection = selection
|
||||
}
|
||||
}
|
||||
}
|
||||
groupBy = "none"
|
||||
}
|
||||
|
||||
// 获取总数
|
||||
total, err := h.db.CountVulnerabilityGroupsForAccess(filter, access, groupBy)
|
||||
if err != nil {
|
||||
@@ -245,6 +271,8 @@ func (h *VulnerabilityHandler) ListVulnerabilities(c *gin.Context) {
|
||||
}
|
||||
|
||||
response := ListVulnerabilitiesResponse{
|
||||
Navigation: navigation,
|
||||
Selection: filter.BrowserSelection,
|
||||
Vulnerabilities: vulnerabilities,
|
||||
Total: total,
|
||||
Page: page,
|
||||
|
||||
@@ -0,0 +1,145 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"cyberstrike-ai/internal/database"
|
||||
"github.com/gin-gonic/gin"
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
func TestVulnerabilityBrowserRecordPagination(t *testing.T) {
|
||||
db, err := database.NewDB(filepath.Join(t.TempDir(), "browser.db"), zap.NewNop())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer db.Close()
|
||||
for i := 0; i < 55; i++ {
|
||||
target, tag := "https://a.example.test", "shared"
|
||||
if i == 28 {
|
||||
target += " https://b.example.test"
|
||||
}
|
||||
if i >= 29 {
|
||||
target, tag = fmt.Sprintf("https://host%d.test", i), fmt.Sprintf("task%d", i)
|
||||
}
|
||||
if i == 54 {
|
||||
target, tag = "/api/login", ""
|
||||
}
|
||||
_, err := db.CreateVulnerability(&database.Vulnerability{ID: fmt.Sprintf("v%02d", i), Title: fmt.Sprintf("Finding %d", i), Target: target, TaskTag: tag, Severity: "low", Status: "open", CreatedAt: time.Unix(int64(i+1), 0)})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
h := NewVulnerabilityHandler(db, zap.NewNop())
|
||||
fetch := func(view, selection string, page int, extra string) ListVulnerabilitiesResponse {
|
||||
t.Helper()
|
||||
w := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(w)
|
||||
c.Request = httptest.NewRequest(http.MethodGet, fmt.Sprintf("/api/vulnerabilities?pagination=records&summary=true&sort=latest&group_by=%s&selection=%s&limit=20&page=%d%s", view, url.QueryEscape(selection), page, extra), nil)
|
||||
h.ListVulnerabilities(c)
|
||||
if w.Code != 200 {
|
||||
t.Fatalf("%d %s", w.Code, w.Body)
|
||||
}
|
||||
var result ListVulnerabilitiesResponse
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &result); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return result
|
||||
}
|
||||
for _, view := range []string{"host", "task"} {
|
||||
first, second := fetch(view, "", 1, ""), fetch(view, "", 2, "")
|
||||
if first.Total != 55 || len(first.Vulnerabilities) != 20 || len(second.Vulnerabilities) != 20 || len(first.Navigation) <= 20 {
|
||||
t.Fatalf("%s: incomplete navigation or wrong record pagination", view)
|
||||
}
|
||||
if !reflect.DeepEqual(first.Navigation, second.Navigation) {
|
||||
t.Fatal("navigation changed between record pages")
|
||||
}
|
||||
selection := "domain:example.test"
|
||||
if view == "task" {
|
||||
selection = "tag:shared"
|
||||
}
|
||||
first, second = fetch(view, selection, 1, ""), fetch(view, selection, 2, "")
|
||||
if first.Total != 29 || second.Total != 29 || len(first.Vulnerabilities) != 20 || len(second.Vulnerabilities) != 9 || first.Selection != selection {
|
||||
t.Fatalf("%s: expected 29 findings in pages of 20 and 9: %+v", view, second)
|
||||
}
|
||||
ids := map[string]bool{}
|
||||
for _, v := range append(first.Vulnerabilities, second.Vulnerabilities...) {
|
||||
if ids[v.ID] {
|
||||
t.Fatal("duplicate finding", v.ID)
|
||||
}
|
||||
ids[v.ID] = true
|
||||
}
|
||||
if second.Vulnerabilities[0].ID != "v08" {
|
||||
t.Fatal("incorrect chronological pagination")
|
||||
}
|
||||
last := fetch(view, selection, 99, "")
|
||||
if last.Page != 2 || len(last.Vulnerabilities) != 9 {
|
||||
t.Fatal("out-of-range page not clamped")
|
||||
}
|
||||
none := fetch(view, selection, 1, "&severity=critical")
|
||||
if none.Total != 0 || len(none.Navigation) != 0 || none.Selection != "" {
|
||||
t.Fatal("stale selection after filtering")
|
||||
}
|
||||
}
|
||||
root := fetch("host", "domain:example.test", 1, "").Navigation
|
||||
for _, node := range root {
|
||||
if node.Key == "domain:example.test" && (node.Count != 29 || len(node.Children) != 2) {
|
||||
t.Fatalf("multi-host finding counted twice: %+v", node)
|
||||
}
|
||||
}
|
||||
unknown := fetch("host", "host:", 1, "")
|
||||
if unknown.Total != 1 || unknown.Vulnerabilities[0].ID != "v54" {
|
||||
t.Fatal("unknown host not selectable")
|
||||
}
|
||||
searched := fetch("host", "", 1, "&host_q=b.example.test")
|
||||
if searched.Total != 1 || len(searched.Navigation) != 1 {
|
||||
t.Fatal("host search must cover all records")
|
||||
}
|
||||
|
||||
linked, err := db.CreateConversation("linked", 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)
|
||||
}
|
||||
if _, err := db.Exec("UPDATE vulnerabilities SET conversation_id=? WHERE id='v00'", linked.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for selection, id := range map[string]string{"queue:queue": "v00", "task:task": "v00", "tag:": "v54"} {
|
||||
result := fetch("task", selection, 1, "")
|
||||
if result.Total != 1 || result.Selection != selection || result.Vulnerabilities[0].ID != id {
|
||||
t.Fatalf("task selection %s returned wrong records", selection)
|
||||
}
|
||||
}
|
||||
// Navigation and records must obey the same access scope.
|
||||
if _, err := db.Exec("UPDATE vulnerabilities SET owner_user_id='other'"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := db.Exec("UPDATE vulnerabilities SET owner_user_id='reader' WHERE id='v00'"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
access := database.RBACListAccess{UserID: "reader", Scope: "own"}
|
||||
nav, err := db.VulnerabilityNavigationForAccess(database.VulnerabilityListFilter{}, access, "host")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(nav) != 1 || nav[0].Count != 1 {
|
||||
t.Fatalf("navigation leaked unauthorized records: %+v", nav)
|
||||
}
|
||||
count, err := db.CountVulnerabilitiesForAccess(database.VulnerabilityListFilter{BrowserSelection: "domain:example.test"}, access)
|
||||
if err != nil || count != 1 {
|
||||
t.Fatalf("record access mismatch: %d %v", count, err)
|
||||
}
|
||||
}
|
||||
@@ -2755,7 +2755,7 @@
|
||||
"history_detach": "إزالة الارتباط",
|
||||
"openRetestChat": "فتح محادثة الاختبار",
|
||||
"noHistory": "لا يوجد سجل منظم بعد",
|
||||
"exportVisibleHosts": "تصدير النتائج المعروضة",
|
||||
"exportVisibleHosts": "تصدير هذه الصفحة",
|
||||
"tableDownload": "تنزيل",
|
||||
"allHosts": "جميع المضيفين",
|
||||
"clearHostSelection": "مسح مرشح المضيف",
|
||||
@@ -2826,6 +2826,8 @@
|
||||
"expandPage": "توسيع الصفحة",
|
||||
"collapsePage": "طي الصفحة",
|
||||
"hostPagination": "عرض {{start}}–{{end}} من أصل {{total}} مجموعة حسب المضيف",
|
||||
"browserPageFindings": "{{count}} ثغرة في هذه الصفحة / {{total}} إجمالاً",
|
||||
"recordsPerPage": "الثغرات لكل صفحة",
|
||||
"taskPagination": "عرض {{start}}–{{end}} من أصل {{total}} مجموعة حسب المهمة",
|
||||
"recordPagination": "عرض {{start}}–{{end}} من أصل {{total}} سجل ثغرة",
|
||||
"viewLabel": "عرض الثغرات",
|
||||
|
||||
@@ -2897,7 +2897,7 @@
|
||||
"history_detach": "Association removed",
|
||||
"openRetestChat": "Open retest chat",
|
||||
"noHistory": "No structured history yet",
|
||||
"exportVisibleHosts": "Export displayed findings",
|
||||
"exportVisibleHosts": "Export this page",
|
||||
"tableDownload": "Download",
|
||||
"allHosts": "All hosts",
|
||||
"clearHostSelection": "Clear host filter",
|
||||
@@ -2968,6 +2968,8 @@
|
||||
"expandPage": "Expand page",
|
||||
"collapsePage": "Collapse page",
|
||||
"hostPagination": "Showing {{start}}–{{end}} of {{total}} host groups",
|
||||
"browserPageFindings": "{{count}} findings on this page / {{total}} total",
|
||||
"recordsPerPage": "Findings per page",
|
||||
"taskPagination": "Showing {{start}}–{{end}} of {{total}} task groups",
|
||||
"recordPagination": "Showing {{start}}–{{end}} of {{total}} findings",
|
||||
"viewLabel": "Vulnerability view",
|
||||
|
||||
@@ -2910,7 +2910,7 @@
|
||||
"history_detach": "Связь удалена",
|
||||
"openRetestChat": "Открыть чат проверки",
|
||||
"noHistory": "Структурированной истории пока нет",
|
||||
"exportVisibleHosts": "Экспорт показанных записей",
|
||||
"exportVisibleHosts": "Экспорт этой страницы",
|
||||
"tableDownload": "Скачать",
|
||||
"allHosts": "Все хосты",
|
||||
"clearHostSelection": "Сбросить фильтр хостов",
|
||||
@@ -2981,6 +2981,8 @@
|
||||
"expandPage": "Развернуть страницу",
|
||||
"collapsePage": "Свернуть страницу",
|
||||
"hostPagination": "Показано {{start}}–{{end}} из {{total}} групп по хостам",
|
||||
"browserPageFindings": "На странице {{count}} из {{total}} уязвимостей",
|
||||
"recordsPerPage": "Уязвимостей на странице",
|
||||
"taskPagination": "Показано {{start}}–{{end}} из {{total}} групп по задачам",
|
||||
"recordPagination": "Показано {{start}}–{{end}} из {{total}} записей",
|
||||
"viewLabel": "Вид списка уязвимостей",
|
||||
|
||||
@@ -2885,7 +2885,7 @@
|
||||
"history_detach": "解除关联",
|
||||
"openRetestChat": "打开复测对话",
|
||||
"noHistory": "暂无结构化处置记录",
|
||||
"exportVisibleHosts": "导出右侧列表",
|
||||
"exportVisibleHosts": "导出本页漏洞",
|
||||
"tableDownload": "下载",
|
||||
"allHosts": "全部域名",
|
||||
"clearHostSelection": "清除域名筛选",
|
||||
@@ -2956,6 +2956,8 @@
|
||||
"expandPage": "展开本页",
|
||||
"collapsePage": "收起本页",
|
||||
"hostPagination": "显示 {{start}}–{{end}} / 共 {{total}} 个域名组",
|
||||
"browserPageFindings": "本页 {{count}} 条 / 共 {{total}} 条漏洞",
|
||||
"recordsPerPage": "每页漏洞数",
|
||||
"taskPagination": "显示 {{start}}–{{end}} / 共 {{total}} 个任务组",
|
||||
"recordPagination": "显示 {{start}}–{{end}} / 共 {{total}} 条漏洞",
|
||||
"viewLabel": "漏洞视图",
|
||||
|
||||
@@ -3,16 +3,14 @@ const fs = require('node:fs');
|
||||
const vm = require('node:vm');
|
||||
const test = require('node:test');
|
||||
|
||||
test('domain export includes exactly the visible records from the loaded page', () => {
|
||||
const rows = [
|
||||
{ id: 'a', target_host: 'api.example.com', target_domain: 'example.com', task_id:'task-a', task_queue_id:'queue' },
|
||||
{ id: 'b', target_host: 'www.example.com', target_domain: 'example.com', task_id:'task-b', task_queue_id:'queue' },
|
||||
{ id: 'c', target_host: 'example.net', target_domain: 'example.net' },
|
||||
{ id: 'unknown', target_host: '' },
|
||||
];
|
||||
test('export uses the server-paginated records even when target_host is absent', async () => {
|
||||
const downloads = [];
|
||||
const context = vm.createContext({
|
||||
vulnerabilityBrowserRows: rows,
|
||||
vulnerabilityBrowserRows: [{ id: 'server-selected', summary_only: true }],
|
||||
apiFetch: async url => {
|
||||
assert.equal(url, '/api/vulnerabilities/server-selected');
|
||||
return { ok: true, json: async () => ({ id: 'server-selected' }) };
|
||||
},
|
||||
vulnerabilityBrowserSelection: '',
|
||||
vulnerabilityView: 'host',
|
||||
formatVulnerabilityAsMarkdown: item => item.id,
|
||||
@@ -21,21 +19,23 @@ test('domain export includes exactly the visible records from the loaded page',
|
||||
const source = fs.readFileSync('web/static/js/vulnerability.js', 'utf8');
|
||||
vm.runInContext(source.slice(
|
||||
source.indexOf('function getVisibleVulnerabilityBrowserItems()'),
|
||||
source.indexOf('function renderVulnerabilityHostRiskDot(')
|
||||
source.indexOf('function renderVulnerabilityBrowserTable(')
|
||||
), context);
|
||||
|
||||
for (const [selection, expected] of [
|
||||
['', ['a', 'b', 'c', 'unknown']],
|
||||
['host:api.example.com', ['a']],
|
||||
['domain:example.com', ['a', 'b']],
|
||||
['host:', ['unknown']],
|
||||
['host:missing.example.com', []],
|
||||
['task:task-a',['a']],
|
||||
['queue:queue',['a','b']],
|
||||
]) {
|
||||
context.vulnerabilityBrowserSelection = selection;
|
||||
downloads.length = 0;
|
||||
context.exportVisibleVulnerabilityBrowser();
|
||||
assert.deepEqual(downloads, expected.length ? [expected.join('\n\n---\n\n')] : []);
|
||||
context.vulnerabilityBrowserSelection = 'domain:example.com';
|
||||
await context.exportVisibleVulnerabilityBrowser();
|
||||
assert.deepEqual(downloads, ['server-selected']);
|
||||
});
|
||||
|
||||
test('selecting or clearing a group reloads the first record page and keeps navigation scroll', () => {
|
||||
const calls = [];
|
||||
const context = vm.createContext({ vulnerabilityBrowserSelection: '', loadVulnerabilities: (...args) => calls.push(args) });
|
||||
const source = fs.readFileSync('web/static/js/vulnerability.js', 'utf8');
|
||||
vm.runInContext(source.slice(source.indexOf('function selectVulnerabilityBrowserGroup('), source.indexOf('function getVisibleVulnerabilityBrowserItems(')), context);
|
||||
for (const key of ['host:example.com', 'task:task-a', '']) {
|
||||
context.selectVulnerabilityBrowserGroup(key);
|
||||
assert.equal(context.vulnerabilityBrowserSelection, key);
|
||||
assert.equal(calls.at(-1)[0], 1);
|
||||
assert.equal(calls.at(-1)[1].preserveScroll, true);
|
||||
}
|
||||
});
|
||||
@@ -244,6 +244,7 @@ let vulnerabilityHostQuery = '';
|
||||
let vulnerabilityTaskQuery = '';
|
||||
let vulnerabilityBrowserSelection = '';
|
||||
let vulnerabilityBrowserRows = [];
|
||||
let vulnerabilityBrowserNavigation = [];
|
||||
let vulnerabilityHostSearchTimer = null;
|
||||
|
||||
const VULN_STAT_SEVERITIES = ['critical', 'high', 'medium', 'low', 'info'];
|
||||
@@ -1282,9 +1283,8 @@ async function loadVulnerabilities(page = null, options = {}) {
|
||||
const scrollTop = scrollEl ? scrollEl.scrollTop : 0;
|
||||
|
||||
const listContainer = document.getElementById('vulnerabilities-list');
|
||||
const hostOpenStates = preserveScroll
|
||||
? new Map(Array.from(listContainer.querySelectorAll('.vulnerability-domain-branch'), branch => [branch.dataset.domain, branch.open]))
|
||||
: new Map();
|
||||
const hostOpenStates = new Map(Array.from(listContainer.querySelectorAll('.vulnerability-domain-branch'), branch => [branch.dataset.domain, branch.open]));
|
||||
const treeScrollTop = listContainer.querySelector('.vulnerability-host-tree')?.scrollTop || 0;
|
||||
if (!silent) {
|
||||
listContainer.innerHTML = `<div class="loading-spinner">${escapeHtml(vulnT('vulnerabilityPage.loading'))}</div>`;
|
||||
updateVulnerabilityListSummary();
|
||||
@@ -1305,6 +1305,10 @@ async function loadVulnerabilities(page = null, options = {}) {
|
||||
const params = buildVulnerabilityFilterParams();
|
||||
params.append('group_by', view);
|
||||
params.append('summary', 'true');
|
||||
if (view === 'host' || view === 'task') {
|
||||
params.append('pagination', 'records');
|
||||
params.append('selection', vulnerabilityBrowserSelection);
|
||||
}
|
||||
if (vulnerabilitySort) params.append('sort', vulnerabilitySort);
|
||||
if (view === 'host' && vulnerabilityHostQuery) params.append('host_q', vulnerabilityHostQuery);
|
||||
if (view === 'task' && vulnerabilityTaskQuery) params.append('task_q', vulnerabilityTaskQuery);
|
||||
@@ -1343,9 +1347,10 @@ async function loadVulnerabilities(page = null, options = {}) {
|
||||
console.error('未知的响应格式:', data);
|
||||
}
|
||||
|
||||
if (view === 'host' || view === 'task') vulnerabilityBrowserSelection = data.selection || '';
|
||||
renderVulnerabilities(vulnerabilities, {
|
||||
view, hostOpenStates,
|
||||
preserveHostSelection: preserveScroll
|
||||
view, hostOpenStates, treeScrollTop,
|
||||
navigation: data.navigation || []
|
||||
});
|
||||
renderVulnerabilityPagination();
|
||||
if (page !== null && !preserveScroll) {
|
||||
@@ -1424,43 +1429,28 @@ function renderVulnerabilityBrowser(vulnerabilities, opts) {
|
||||
const caret = activeSearch ? document.activeElement.selectionStart : null;
|
||||
vulnerabilityBrowserRows = vulnerabilities;
|
||||
const isTask = opts.view === 'task';
|
||||
const groups = new Map();
|
||||
for (const vuln of vulnerabilities) {
|
||||
const host = vuln.target_host || '';
|
||||
const domain = vuln.target_domain || host;
|
||||
let rootKey = 'domain:' + domain, rootLabel = domain;
|
||||
let key = 'host:' + host, label = host || vulnT('vulnerabilityPage.unknownHost');
|
||||
let flat = host === domain;
|
||||
if (isTask) {
|
||||
const tag = (vuln.task_tag || '').replace(/^ +| +$/g, '');
|
||||
key = vuln.task_id ? 'task:' + vuln.task_id : 'tag:' + tag;
|
||||
label = vuln.task_id ? vulnT('vulnerabilityPage.viewTaskGroup', {id:vuln.task_id}) : tag || vulnT('vulnerabilityPage.viewNoTask');
|
||||
rootKey = vuln.task_queue_id ? 'queue:' + vuln.task_queue_id : key;
|
||||
rootLabel = vuln.task_queue_title || (vuln.task_queue_id
|
||||
? vulnT('vulnerabilityPage.taskQueueGroup', {id:vuln.task_queue_id}) : label);
|
||||
flat = !vuln.task_queue_id;
|
||||
}
|
||||
if (!groups.has(rootKey)) groups.set(rootKey, {label:rootLabel, children:new Map(), items:[], flat});
|
||||
const group = groups.get(rootKey);
|
||||
group.flat = group.flat && flat;
|
||||
group.items.push(vuln);
|
||||
if (!group.children.has(key)) group.children.set(key, {label, items:[]});
|
||||
group.children.get(key).items.push(vuln);
|
||||
}
|
||||
const button = (key, label, count, items = []) => `
|
||||
<button type="button" class="vulnerability-host-option" data-host-key="${escapeAttr(key)}" aria-pressed="false">
|
||||
<span class="vulnerability-host-option-name" title="${escapeAttr(label)}">${renderVulnerabilityHostRiskDot(items)}${escapeHtml(label)}</span><span class="vulnerability-host-number">${count}</span>
|
||||
vulnerabilityBrowserNavigation = opts.navigation || [];
|
||||
const labelFor = node => {
|
||||
if (node.label) return node.key.startsWith('task:')
|
||||
? vulnT('vulnerabilityPage.viewTaskGroup', { id: node.label }) : node.label;
|
||||
if (node.key.startsWith('host:')) return vulnT('vulnerabilityPage.unknownHost');
|
||||
if (node.key.startsWith('queue:')) return vulnT('vulnerabilityPage.taskQueueGroup', { id: node.key.slice(6) });
|
||||
return vulnT('vulnerabilityPage.viewNoTask');
|
||||
};
|
||||
const button = node => {
|
||||
const label = labelFor(node);
|
||||
const risk = VULN_STAT_SEVERITIES.find(severity => node.severities[severity]);
|
||||
return `<button type="button" class="vulnerability-host-option" data-host-key="${escapeAttr(node.key)}" aria-pressed="false">
|
||||
<span class="vulnerability-host-option-name" title="${escapeAttr(label)}">${risk ? `<span class="vulnerability-host-risk-dot severity-${risk}" title="${escapeAttr(vulnSeverityLabel(risk))}"></span>` : ''}${escapeHtml(label)}</span><span class="vulnerability-host-number">${node.count}</span>
|
||||
</button>`;
|
||||
const tree = Array.from(groups, ([rootKey, group]) => {
|
||||
const count = new Set(group.items.map(vuln => vuln.id)).size;
|
||||
if (group.flat && group.children.size === 1) {
|
||||
const [key,child] = group.children.entries().next().value;
|
||||
return button(key, child.label, count, child.items);
|
||||
}
|
||||
const open = opts.hostOpenStates?.get(rootKey) ?? true;
|
||||
return `<details class="vulnerability-domain-branch" data-domain="${escapeAttr(rootKey)}"${open ? ' open' : ''}>
|
||||
<summary><button type="button" class="vulnerability-domain-label" data-host-key="${escapeAttr(rootKey)}" title="${escapeAttr(group.label)}" aria-pressed="false">${escapeHtml(group.label)}</button><span class="vulnerability-host-number">${count}</span></summary>
|
||||
${Array.from(group.children, ([key, child]) => button(key, child.label, child.items.length, child.items)).join('')}
|
||||
};
|
||||
const tree = vulnerabilityBrowserNavigation.map(node => {
|
||||
if (!node.children?.length) return button(node);
|
||||
const label = labelFor(node);
|
||||
const open = opts.hostOpenStates?.get(node.key) ?? true;
|
||||
return `<details class="vulnerability-domain-branch" data-domain="${escapeAttr(node.key)}"${open ? ' open' : ''}>
|
||||
<summary><button type="button" class="vulnerability-domain-label" data-host-key="${escapeAttr(node.key)}" title="${escapeAttr(label)}" aria-pressed="false">${escapeHtml(label)}</button><span class="vulnerability-host-number">${node.count}</span></summary>
|
||||
${node.children.map(button).join('')}
|
||||
</details>`;
|
||||
}).join('');
|
||||
const list = document.getElementById('vulnerabilities-list');
|
||||
@@ -1481,7 +1471,7 @@ function renderVulnerabilityBrowser(vulnerabilities, opts) {
|
||||
<div class="vulnerability-host-overview">
|
||||
<div id="vulnerability-host-risk-summary"></div>
|
||||
<div class="vulnerability-host-heading-actions">
|
||||
<button type="button" id="vulnerability-host-clear" class="btn-ghost" onclick="vulnerabilityBrowserSelection='';renderVulnerabilityBrowserTable()" hidden>${escapeHtml(vulnT(isTask ? 'vulnerabilityPage.clearTaskSelection' : 'vulnerabilityPage.clearHostSelection'))}</button>
|
||||
<button type="button" id="vulnerability-host-clear" class="btn-ghost" onclick="selectVulnerabilityBrowserGroup('')" hidden>${escapeHtml(vulnT(isTask ? 'vulnerabilityPage.clearTaskSelection' : 'vulnerabilityPage.clearHostSelection'))}</button>
|
||||
<span id="vulnerability-host-selection-count"></span>
|
||||
<button type="button" class="btn-secondary" id="vulnerability-host-export"
|
||||
onclick="exportVisibleVulnerabilityBrowser()" data-require-permission="vulnerability:read">${escapeHtml(vulnT('vulnerabilityPage.exportVisibleHosts'))}</button>
|
||||
@@ -1506,29 +1496,23 @@ function renderVulnerabilityBrowser(vulnerabilities, opts) {
|
||||
const option = event.target.closest('button[data-host-key]');
|
||||
if (!option) return;
|
||||
event.preventDefault();
|
||||
vulnerabilityBrowserSelection = option.dataset.hostKey;
|
||||
renderVulnerabilityBrowserTable();
|
||||
selectVulnerabilityBrowserGroup(option.dataset.hostKey);
|
||||
});
|
||||
if (!opts.preserveHostSelection &&
|
||||
!Array.from(list.querySelectorAll('[data-host-key]')).some(el => el.dataset.hostKey === vulnerabilityBrowserSelection)) {
|
||||
vulnerabilityBrowserSelection = '';
|
||||
}
|
||||
renderVulnerabilityBrowserTable();
|
||||
list.querySelector('.vulnerability-host-tree').scrollTop = opts.treeScrollTop || 0;
|
||||
if (activeSearch) {
|
||||
search.focus({ preventScroll: true });
|
||||
search.setSelectionRange(caret, caret);
|
||||
}
|
||||
}
|
||||
|
||||
function selectVulnerabilityBrowserGroup(key) {
|
||||
vulnerabilityBrowserSelection = key;
|
||||
loadVulnerabilities(1, { silent: true, preserveScroll: true });
|
||||
}
|
||||
|
||||
function getVisibleVulnerabilityBrowserItems() {
|
||||
const selection = vulnerabilityBrowserSelection;
|
||||
const items = vulnerabilityBrowserRows.filter(vuln => !selection ||
|
||||
selection === 'host:' + (vuln.target_host || '') ||
|
||||
selection === 'domain:' + (vuln.target_domain || vuln.target_host || '') ||
|
||||
(vuln.task_id && selection === 'task:' + vuln.task_id) ||
|
||||
(vuln.task_queue_id && selection === 'queue:' + vuln.task_queue_id) ||
|
||||
(!vuln.task_id && selection === 'tag:' + (vuln.task_tag || '').replace(/^ +| +$/g, '')));
|
||||
return Array.from(new Map(items.map(vuln => [vuln.id,vuln])).values());
|
||||
return vulnerabilityBrowserRows;
|
||||
}
|
||||
|
||||
async function exportVisibleVulnerabilityBrowser() {
|
||||
@@ -1547,11 +1531,6 @@ async function exportVisibleVulnerabilityBrowser() {
|
||||
} catch(error) { alert(error.message); }
|
||||
}
|
||||
|
||||
function renderVulnerabilityHostRiskDot(items) {
|
||||
const highest = VULN_STAT_SEVERITIES.find(severity => items.some(item => item.severity === severity));
|
||||
return highest ? `<span class="vulnerability-host-risk-dot severity-${highest}" title="${escapeAttr(vulnSeverityLabel(highest))}"></span>` : '';
|
||||
}
|
||||
|
||||
function renderVulnerabilityBrowserTable() {
|
||||
const selection = vulnerabilityBrowserSelection;
|
||||
const items = getVisibleVulnerabilityBrowserItems();
|
||||
@@ -1568,12 +1547,15 @@ function renderVulnerabilityBrowserTable() {
|
||||
heading.title = heading.textContent;
|
||||
document.getElementById('vulnerability-host-clear').hidden = !selection;
|
||||
document.getElementById('vulnerability-host-selection-count').textContent =
|
||||
vulnT('vulnerabilityPage.groupPageCount', { count: items.length });
|
||||
const counts = {};
|
||||
let pending = 0;
|
||||
for (const item of items) {
|
||||
counts[item.severity] = (counts[item.severity] || 0) + 1;
|
||||
if (!item.status || item.status === 'open' || item.status === 'confirmed') pending++;
|
||||
vulnT('vulnerabilityPage.browserPageFindings', { count: items.length, total: vulnerabilityPagination.total });
|
||||
const selectedGroup = vulnerabilityBrowserNavigation.flatMap(node => [node, ...(node.children || [])]).find(node => node.key === selection);
|
||||
const counts = selectedGroup ? selectedGroup.severities : {};
|
||||
let pending = selectedGroup ? selectedGroup.pending : 0;
|
||||
if (!selectedGroup) {
|
||||
for (const item of items) {
|
||||
counts[item.severity] = (counts[item.severity] || 0) + 1;
|
||||
if (!item.status || item.status === 'open' || item.status === 'confirmed') pending++;
|
||||
}
|
||||
}
|
||||
document.getElementById('vulnerability-host-risk-summary').innerHTML =
|
||||
VULN_STAT_SEVERITIES.filter(severity => counts[severity]).map(severity =>
|
||||
@@ -1648,11 +1630,8 @@ function renderVulnerabilityPagination() {
|
||||
}
|
||||
|
||||
const { currentPage, totalPages, total, pageSize } = vulnerabilityPagination;
|
||||
const paginationLabel = {
|
||||
host: 'vulnerabilityPage.hostPagination',
|
||||
task: 'vulnerabilityPage.taskPagination',
|
||||
none: 'vulnerabilityPage.recordPagination'
|
||||
}[vulnerabilityView];
|
||||
const paginationLabel = 'vulnerabilityPage.recordPagination';
|
||||
const pageSizeLabel = 'vulnerabilityPage.recordsPerPage';
|
||||
|
||||
// 计算显示范围
|
||||
const start = total === 0 ? 0 : (currentPage - 1) * pageSize + 1;
|
||||
@@ -1665,7 +1644,7 @@ function renderVulnerabilityPagination() {
|
||||
<div class="pagination-info">
|
||||
<span>${escapeHtml(vulnT(paginationLabel, { start, end, total }))}</span>
|
||||
<label class="pagination-page-size">
|
||||
${escapeHtml(vulnT('skillsPage.perPageLabel'))}
|
||||
${escapeHtml(vulnT(pageSizeLabel))}
|
||||
<select id="vulnerability-page-size-pagination" onchange="changeVulnerabilityPageSize()">
|
||||
<option value="10" ${pageSize === 10 ? 'selected' : ''}>10</option>
|
||||
<option value="20" ${pageSize === 20 ? 'selected' : ''}>20</option>
|
||||
|
||||
@@ -7106,7 +7106,7 @@
|
||||
<script src="/static/js/skills.js?v=20261115-ui-drawers"></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=20261115-timestamps"></script>
|
||||
<script src="/static/js/vulnerability.js?v=20261116-record-pagination"></script>
|
||||
<script src="/static/js/vulnerability-workspace.js?v=20261115-timestamps"></script>
|
||||
<script src="/static/js/vulnerability-download.js?v=20261030-2"></script>
|
||||
<script src="/static/js/webshell.js?v=20261011-token-usage"></script>
|
||||
|
||||
Reference in new issue
Block a user