diff --git a/internal/database/database.go b/internal/database/database.go index 62fcaa1e..34bc45a1 100644 --- a/internal/database/database.go +++ b/internal/database/database.go @@ -9,7 +9,7 @@ import ( "sync" "time" - _ "github.com/mattn/go-sqlite3" + "github.com/mattn/go-sqlite3" "go.uber.org/zap" ) @@ -128,9 +128,17 @@ func (db *DB) runPassiveCheckpoint(trigger string) { db.logger.Debug("SQLite PASSIVE checkpoint 完成(成功)", fields...) } +func init() { + sql.Register("cyberstrike-sqlite3", &sqlite3.SQLiteDriver{ + ConnectHook: func(conn *sqlite3.SQLiteConn) error { + return conn.RegisterFunc("vulnerability_target_host", vulnerabilityTargetHost, true) + }, + }) +} + // NewDB 创建数据库连接 func NewDB(dbPath string, logger *zap.Logger) (*DB, error) { - db, err := sql.Open("sqlite3", sqliteOpenDSN(dbPath)) + db, err := sql.Open("cyberstrike-sqlite3", sqliteOpenDSN(dbPath)) if err != nil { return nil, fmt.Errorf("打开数据库失败: %w", err) } diff --git a/internal/database/vulnerability.go b/internal/database/vulnerability.go index 8c7e827f..52847a63 100644 --- a/internal/database/vulnerability.go +++ b/internal/database/vulnerability.go @@ -3,11 +3,14 @@ package database import ( "database/sql" "fmt" + "net/netip" + "net/url" "strings" "time" "github.com/google/uuid" "go.uber.org/zap" + "golang.org/x/net/idna" ) // VulnerabilityListFilter 列表/统计/导出共用的筛选条件 @@ -143,6 +146,7 @@ type Vulnerability struct { Status string `json:"status"` // open, confirmed, fixed, false_positive, ignored Type string `json:"type"` Target string `json:"target"` + TargetHost *string `json:"target_host,omitempty"` Preconditions string `json:"preconditions"` ReproSteps string `json:"reproduction_steps"` Evidence string `json:"evidence"` @@ -234,6 +238,49 @@ 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) +} + +func vulnerabilityTargetHost(target string) string { + target = strings.TrimSpace(target) + if ip, err := netip.ParseAddr(target); err == nil { + return ip.String() + } + scheme, _, hasScheme := strings.Cut(target, "://") + explicitURL := strings.HasPrefix(target, "//") || (hasScheme && !strings.ContainsAny(scheme, "/?#")) + if !explicitURL { + target = "//" + target + } + parsed, err := url.Parse(target) + if err != nil || parsed.Host == "" { + return "" + } + host := parsed.Hostname() + if ip, err := netip.ParseAddr(host); err == nil { + return ip.String() + } + host, err = idna.Lookup.ToASCII(host) + host = strings.ToLower(strings.TrimSuffix(host, ".")) + if err != nil || !validAssetDomain(host) { + return "" + } + // A relative endpoint such as "api/login" does not identify a host. + if !explicitURL && parsed.Port() == "" && host != "localhost" && !strings.Contains(host, ".") { + return "" + } + return host +} + +func (db *DB) listVulnerabilitiesForAccess(limit, offset int, filter VulnerabilityListFilter, access RBACListAccess, byHost bool) ([]*Vulnerability, error) { + hostExpr, order := "NULL", "created_at DESC" + if byHost { + hostExpr = "vulnerability_target_host(target)" + order = "target_host = '', target_host, created_at DESC, id" + } query := ` SELECT id, COALESCE(conversation_id,''), COALESCE(project_id,''), title, description, severity, status, conversation_tag, task_tag, vulnerability_type, target, @@ -241,7 +288,7 @@ func (db *DB) ListVulnerabilitiesForAccess(limit, offset int, filter Vulnerabili 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, - created_at, updated_at + created_at, updated_at, ` + hostExpr + ` AS target_host FROM vulnerabilities WHERE 1=1 ` @@ -249,7 +296,7 @@ func (db *DB) ListVulnerabilitiesForAccess(limit, offset int, filter Vulnerabili query, args = filter.appendWhere(query, args) query, args = appendVulnerabilityAccessFilter(query, args, access) - query += " ORDER BY created_at DESC LIMIT ? OFFSET ?" + query += " ORDER BY " + order + " LIMIT ? OFFSET ?" args = append(args, limit, offset) rows, err := db.Query(query, args...) @@ -266,7 +313,7 @@ func (db *DB) ListVulnerabilitiesForAccess(limit, offset int, filter Vulnerabili &vuln.Severity, &vuln.Status, &vuln.ConversationTag, &vuln.TaskTag, &vuln.Type, &vuln.Target, &vuln.Preconditions, &vuln.ReproSteps, &vuln.Evidence, &vuln.Impact, &vuln.Recommendation, &vuln.RetestNotes, &vuln.RetestLog, &vuln.TaskID, &vuln.TaskQueueID, - &vuln.CreatedAt, &vuln.UpdatedAt, + &vuln.CreatedAt, &vuln.UpdatedAt, &vuln.TargetHost, ) if err != nil { db.logger.Warn("扫描漏洞记录失败", zap.Error(err)) @@ -275,7 +322,7 @@ func (db *DB) ListVulnerabilitiesForAccess(limit, offset int, filter Vulnerabili vulnerabilities = append(vulnerabilities, &vuln) } - return vulnerabilities, nil + return vulnerabilities, rows.Err() } // CountVulnerabilities 统计漏洞总数(支持筛选条件) diff --git a/internal/handler/vulnerability.go b/internal/handler/vulnerability.go index fe7ef833..7b211ff7 100644 --- a/internal/handler/vulnerability.go +++ b/internal/handler/vulnerability.go @@ -184,8 +184,12 @@ func (h *VulnerabilityHandler) ListVulnerabilities(c *gin.Context) { pageStr := c.Query("page") filter := parseVulnerabilityListFilter(c) access := vulnerabilityAccessFromContext(c) + byHost := c.Query("group_by") == "host" limit, _ := strconv.Atoi(limitStr) + if limit <= 0 || limit > 100 { + limit = 20 + } offset, _ := strconv.Atoi(offsetStr) page := 1 @@ -197,9 +201,6 @@ func (h *VulnerabilityHandler) ListVulnerabilities(c *gin.Context) { } } - if limit <= 0 || limit > 100 { - limit = 20 - } if offset < 0 { offset = 0 } @@ -212,14 +213,6 @@ func (h *VulnerabilityHandler) ListVulnerabilities(c *gin.Context) { total = 0 } - // 获取漏洞列表 - vulnerabilities, err := h.db.ListVulnerabilitiesForAccess(limit, offset, filter, access) - if err != nil { - h.logger.Error("获取漏洞列表失败", zap.Error(err)) - c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) - return - } - // 计算总页数 totalPages := (total + limit - 1) / limit if totalPages == 0 { @@ -231,6 +224,21 @@ 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 + } + } + vulnerabilities, err := list(limit, offset, filter, access) + if err != nil { + h.logger.Error("获取漏洞列表失败", zap.Error(err)) + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + return + } + response := ListVulnerabilitiesResponse{ Vulnerabilities: vulnerabilities, Total: total, diff --git a/internal/handler/vulnerability_group_test.go b/internal/handler/vulnerability_group_test.go new file mode 100644 index 00000000..b54fb9ae --- /dev/null +++ b/internal/handler/vulnerability_group_test.go @@ -0,0 +1,88 @@ +package handler + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "path/filepath" + "testing" + "time" + + "cyberstrike-ai/internal/database" + "github.com/gin-gonic/gin" + "go.uber.org/zap" +) + +func TestListVulnerabilitiesGroupedByHost(t *testing.T) { + db, err := database.NewDB(filepath.Join(t.TempDir(), "grouped.db"), zap.NewNop()) + if err != nil { + t.Fatal(err) + } + defer db.Close() + + for i, item := range []struct { + id, target, severity string + }{ + {"domain-old", "HTTPS://Example.COM.:443/login", "high"}, + {"domain-new", "example.com:8443/api", "high"}, + {"subdomain", "https://sub.example.com/api", "high"}, + {"ipv6", "https://[2001:0DB8::1]:8080/", "high"}, + {"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, + CreatedAt: time.Unix(int64(i+1), 0), + }) + if err != nil { + t.Fatal(err) + } + } + + h := NewVulnerabilityHandler(db, zap.NewNop()) + fetch := func(query string) ListVulnerabilitiesResponse { + t.Helper() + w := httptest.NewRecorder() + c, _ := gin.CreateTestContext(w) + c.Request = httptest.NewRequest(http.MethodGet, "/api/vulnerabilities?severity=high&limit=2&"+query, nil) + h.ListVulnerabilities(c) + if w.Code != http.StatusOK { + t.Fatalf("status = %d, body = %s", w.Code, w.Body.String()) + } + var result ListVulnerabilitiesResponse + if err := json.Unmarshal(w.Body.Bytes(), &result); err != nil { + t.Fatal(err) + } + return result + } + + for _, tc := range []struct { + query string + page 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{""}}, + {"page=1", 1, []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) { + t.Fatalf("unexpected pagination: %+v", result) + } + for i, v := range result.Vulnerabilities { + if v.ID != tc.ids[i] { + t.Fatalf("record %d = %q, want %q", i, v.ID, tc.ids[i]) + } + if tc.hosts == nil { + if v.TargetHost != nil { + t.Fatalf("ordinary listing returned target_host for %q", v.ID) + } + } else if v.TargetHost == nil || *v.TargetHost != tc.hosts[i] { + t.Fatalf("target_host for %q = %v, want %q", v.ID, v.TargetHost, tc.hosts[i]) + } + } + }) + } +} diff --git a/web/static/css/style.css b/web/static/css/style.css index 4be481be..163e1f1e 100644 --- a/web/static/css/style.css +++ b/web/static/css/style.css @@ -27456,6 +27456,42 @@ tr.mcp-stats-tool-row[data-tool-name]:focus-visible { margin-bottom: 0; } +.vulnerability-host-group { + min-width: 0; + border: 1px solid var(--border-color); + border-radius: 8px; + background: var(--bg-secondary); +} + +.vulnerability-host-group > summary { + padding: 12px 16px; + cursor: pointer; + overflow-wrap: anywhere; +} + +.vulnerability-host-group > summary:focus-visible { + outline: 2px solid var(--accent-color); + outline-offset: -2px; + border-radius: 8px; +} + +.vulnerability-host-name { + margin-inline-start: 6px; + font-weight: 600; +} + +.vulnerability-host-count { + margin-inline-start: 8px; + color: var(--text-muted); + font-size: 0.8125rem; +} + +.vulnerability-host-cards { + display: grid; + gap: 10px; + padding: 0 12px 12px; +} + .vulnerability-card { background: var(--bg-primary); border: 1px solid var(--border-color); diff --git a/web/static/i18n/ar-SA.json b/web/static/i18n/ar-SA.json index 6f967b6c..101b4600 100644 --- a/web/static/i18n/ar-SA.json +++ b/web/static/i18n/ar-SA.json @@ -2769,6 +2769,8 @@ "loading": "جارٍ التحميل...", "loadListFailed": "فشل التحميل", "noRecords": "لا توجد سجلات ثغرات", + "unknownHost": "مضيف غير معروف", + "hostPageCount": "{{count}} في هذه الصفحة", "batchExport": "تصدير جماعي", "batchDelete": "حذف جماعي", "batchDeleteNoResults": "لا توجد ثغرات تطابق عوامل التصفية الحالية لحذفها", diff --git a/web/static/i18n/en-US.json b/web/static/i18n/en-US.json index 9284f510..80f44786 100644 --- a/web/static/i18n/en-US.json +++ b/web/static/i18n/en-US.json @@ -2912,6 +2912,8 @@ "loading": "Loading...", "loadListFailed": "Failed to load", "noRecords": "No vulnerability records", + "unknownHost": "Unknown host", + "hostPageCount": "{{count}} on this page", "batchExport": "Batch export", "batchDelete": "Batch delete", "batchDeleteNoResults": "No vulnerabilities match the current filters to delete", diff --git a/web/static/i18n/ru-RU.json b/web/static/i18n/ru-RU.json index 3998bccd..66297f83 100644 --- a/web/static/i18n/ru-RU.json +++ b/web/static/i18n/ru-RU.json @@ -2925,6 +2925,8 @@ "loading": "Загрузка...", "loadListFailed": "Не удалось загрузить", "noRecords": "Нет записей об уязвимостях", + "unknownHost": "Неизвестный хост", + "hostPageCount": "На этой странице: {{count}}", "batchExport": "Пакетный экспорт", "batchDelete": "Пакетное удаление", "batchDeleteNoResults": "Нет уязвимостей по текущим фильтрам для удаления", diff --git a/web/static/i18n/zh-CN.json b/web/static/i18n/zh-CN.json index c466c8ac..9de8313c 100644 --- a/web/static/i18n/zh-CN.json +++ b/web/static/i18n/zh-CN.json @@ -2900,6 +2900,8 @@ "loading": "加载中...", "loadListFailed": "加载失败", "noRecords": "暂无漏洞记录", + "unknownHost": "未识别到主机", + "hostPageCount": "本页 {{count}} 条", "batchExport": "批量导出", "batchDelete": "批量删除", "batchDeleteNoResults": "当前筛选条件下没有可删除的漏洞", diff --git a/web/static/js/vulnerability.js b/web/static/js/vulnerability.js index 63ae5e9b..fa22dfde 100644 --- a/web/static/js/vulnerability.js +++ b/web/static/js/vulnerability.js @@ -187,40 +187,13 @@ function vulnerabilityStatusMatchesFilter(status) { return !filterStatus || filterStatus === status; } -function removeVulnerabilityCard(vulnId, options) { - const opts = options || {}; - const card = document.getElementById('vulnerability-card-' + vulnId) || - document.querySelector('.vulnerability-card[data-vuln-id="' + vulnId + '"]'); - if (!card) return; - - const nextCard = card.nextElementSibling; - card.classList.add('vulnerability-card--removing'); - - setTimeout(function () { - card.remove(); - if (opts.decrementTotal !== false) { - vulnerabilityPagination.total = Math.max(0, (vulnerabilityPagination.total || 0) - 1); - vulnerabilityPagination.totalPages = Math.max( - 1, - Math.ceil(vulnerabilityPagination.total / vulnerabilityPagination.pageSize) - ); - renderVulnerabilityPagination(); - } - - const list = document.getElementById('vulnerabilities-list'); - const remaining = list ? list.querySelectorAll('.vulnerability-card').length : 0; - if (remaining === 0) { - if (vulnerabilityPagination.currentPage > 1) { - vulnerabilityPagination.currentPage--; - } - loadVulnerabilities(); - return; - } - - if (opts.focusNext !== false && nextCard && nextCard.classList.contains('vulnerability-card')) { - nextCard.scrollIntoView({ block: 'nearest', behavior: 'smooth' }); - } - }, VULNERABILITY_REMOVE_ANIM_MS); +async function removeVulnerabilityCard(vulnId) { + const card = document.getElementById('vulnerability-card-' + vulnId); + if (card) { + card.classList.add('vulnerability-card--removing'); + await new Promise(resolve => setTimeout(resolve, VULNERABILITY_REMOVE_ANIM_MS)); + } + await loadVulnerabilities(null, { preserveScroll: true, silent: true }); } async function changeVulnerabilityStatus(vulnId, newStatus, pickerEl) { @@ -244,7 +217,7 @@ async function changeVulnerabilityStatus(vulnId, newStatus, pickerEl) { loadVulnerabilityStats(); if (!vulnerabilityStatusMatchesFilter(newStatus)) { - removeVulnerabilityCard(vulnId, { decrementTotal: true, focusNext: true }); + await removeVulnerabilityCard(vulnId); } } catch (error) { console.error('更新漏洞状态失败:', error); @@ -1290,6 +1263,9 @@ 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(); if (!silent) { listContainer.innerHTML = `