diff --git a/internal/app/app.go b/internal/app/app.go index 26c9d859..7fcc74b2 100644 --- a/internal/app/app.go +++ b/internal/app/app.go @@ -1383,9 +1383,12 @@ func setupRoutes( protected.DELETE("/vulnerabilities/batch", vulnerabilityHandler.BatchDeleteVulnerabilities) protected.GET("/vulnerabilities/filter-options", vulnerabilityHandler.GetVulnerabilityFilterOptions) protected.GET("/vulnerabilities/stats", vulnerabilityHandler.GetVulnerabilityStats) + protected.POST("/vulnerabilities/cases", vulnerabilityHandler.MergeVulnerabilities) + protected.POST("/vulnerabilities/cases/:caseID/split", vulnerabilityHandler.DissolveVulnerabilityCase) protected.GET("/vulnerability-alerts/subscription", vulnerabilityHandler.GetMyAlertSubscription) protected.PUT("/vulnerability-alerts/subscription", vulnerabilityHandler.UpdateMyAlertSubscription) protected.GET("/vulnerabilities/:id", vulnerabilityHandler.GetVulnerability) + protected.GET("/vulnerabilities/:id/context", vulnerabilityHandler.VulnerabilityContext) protected.GET("/vulnerabilities/:id/download", vulnerabilityHandler.DownloadVulnerability) protected.POST("/vulnerabilities", vulnerabilityHandler.CreateVulnerability) protected.POST("/vulnerabilities/:id/retest", vulnerabilityHandler.CreateRetest) diff --git a/internal/database/database.go b/internal/database/database.go index 34bc45a1..7430bcb3 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,17 +128,9 @@ 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("cyberstrike-sqlite3", sqliteOpenDSN(dbPath)) + db, err := sql.Open("sqlite3", sqliteOpenDSN(dbPath)) if err != nil { return nil, fmt.Errorf("打开数据库失败: %w", err) } @@ -220,6 +212,9 @@ func (db *DB) initTables() error { if err := db.migrateVulnerabilitiesConversationFK(); err != nil { return fmt.Errorf("迁移漏洞会话外键失败: %w", err) } + if err := db.backfillVulnerabilityTargets(); err != nil { + return fmt.Errorf("回填漏洞目标失败: %w", err) + } if err := db.BackfillModelTokenUsageFromProcessDetails(); err != nil { return fmt.Errorf("回填模型Token用量失败: %w", err) } diff --git a/internal/database/schemas/application.sql b/internal/database/schemas/application.sql index bc30d88a..0338657b 100644 --- a/internal/database/schemas/application.sql +++ b/internal/database/schemas/application.sql @@ -528,6 +528,9 @@ CREATE TABLE vulnerabilities ( status TEXT NOT NULL DEFAULT 'open', vulnerability_type TEXT, target TEXT, + targets_json TEXT NOT NULL DEFAULT '[]', + targets_version INTEGER NOT NULL DEFAULT 0, + case_id TEXT REFERENCES vulnerability_cases(id) ON DELETE SET NULL, preconditions TEXT, reproduction_steps TEXT, evidence TEXT, @@ -573,9 +576,41 @@ CREATE TABLE vulnerability_retests ( source_conversation_id TEXT NOT NULL, vulnerability_id TEXT NOT NULL, source_project_id TEXT NOT NULL DEFAULT '', - pending_prompt TEXT NOT NULL DEFAULT '' + pending_prompt TEXT NOT NULL DEFAULT '', + snapshot_json TEXT NOT NULL DEFAULT '' ); +CREATE TABLE vulnerability_cases ( + id TEXT PRIMARY KEY, + project_id TEXT NOT NULL DEFAULT '', + title TEXT NOT NULL, + reason TEXT NOT NULL, + created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP +); + +CREATE TABLE vulnerability_case_events ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + case_id TEXT NOT NULL, + action TEXT NOT NULL, + actor TEXT NOT NULL, + reason TEXT NOT NULL, + finding_ids TEXT NOT NULL, + created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP +); + +CREATE TABLE vulnerability_retest_results ( + id TEXT PRIMARY KEY, + vulnerability_id TEXT NOT NULL REFERENCES vulnerabilities(id) ON DELETE CASCADE, + conversation_id TEXT NOT NULL, + status TEXT NOT NULL, + evidence TEXT NOT NULL, + created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP +); + +CREATE INDEX idx_vulnerability_case ON vulnerabilities(case_id); +CREATE INDEX idx_vulnerability_case_events ON vulnerability_case_events(case_id); +CREATE INDEX idx_vulnerability_retest_results ON vulnerability_retest_results(vulnerability_id, created_at); + CREATE TABLE webshell_connection_states ( connection_id TEXT PRIMARY KEY, state_json TEXT NOT NULL DEFAULT '{}', diff --git a/internal/database/vulnerability.go b/internal/database/vulnerability.go index eeb9286e..657c6b61 100644 --- a/internal/database/vulnerability.go +++ b/internal/database/vulnerability.go @@ -20,6 +20,8 @@ type VulnerabilityListFilter struct { ID string Search string // 关键词模糊匹配(标题、描述、类型、目标等) HostQuery string + CaseID string + SummaryOnly bool ConversationID string ProjectID string Severity string @@ -43,11 +45,15 @@ func escapeVulnerabilityLikePattern(s string) string { func (f VulnerabilityListFilter) appendWhere(query string, args []interface{}) (string, []interface{}) { if host := strings.TrimSpace(f.HostQuery); host != "" { - query += ` AND vulnerability_target_host(target) LIKE ? ESCAPE '\'` + 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))) } + if f.CaseID != "" { + query += " AND case_id=?" + args = append(args, f.CaseID) + } if f.ID != "" { - query += " AND id = ?" + query += " AND vulnerabilities.id = ?" args = append(args, f.ID) } if f.ConversationID != "" { @@ -82,7 +88,7 @@ func (f VulnerabilityListFilter) appendWhere(query string, args []interface{}) ( if search != "" { pattern := escapeVulnerabilityLikePattern(search) query += ` AND ( - LOWER(id) LIKE LOWER(?) OR + LOWER(vulnerabilities.id) LIKE LOWER(?) OR LOWER(title) LIKE LOWER(?) OR LOWER(COALESCE(description, '')) LIKE LOWER(?) OR LOWER(COALESCE(vulnerability_type, '')) LIKE LOWER(?) OR @@ -140,30 +146,34 @@ func appendVulnerabilityAccessFilter(query string, args []interface{}, access RB // Vulnerability 漏洞 type Vulnerability struct { - ID string `json:"id"` - ConversationID string `json:"conversation_id"` - ProjectID string `json:"project_id,omitempty"` - ConversationTag string `json:"conversation_tag,omitempty"` - TaskTag string `json:"task_tag,omitempty"` - TaskID string `json:"task_id,omitempty"` - TaskQueueID string `json:"task_queue_id,omitempty"` - Title string `json:"title"` - Description string `json:"description"` - Severity string `json:"severity"` // critical, high, medium, low, info - Status string `json:"status"` // open, confirmed, fixed, false_positive, ignored - Type string `json:"type"` - Target string `json:"target"` - TargetHost *string `json:"target_host,omitempty"` - TargetDomain string `json:"target_domain,omitempty"` - Preconditions string `json:"preconditions"` - ReproSteps string `json:"reproduction_steps"` - Evidence string `json:"evidence"` - Impact string `json:"impact"` - Recommendation string `json:"recommendation"` - RetestNotes string `json:"retest_notes"` - RetestLog string `json:"retest_log"` // append-only retest evidence; kept out of retest_notes because the edit form rewrites that field wholesale - CreatedAt time.Time `json:"created_at"` - UpdatedAt time.Time `json:"updated_at"` + ID string `json:"id"` + ConversationID string `json:"conversation_id"` + ProjectID string `json:"project_id,omitempty"` + ConversationTag string `json:"conversation_tag,omitempty"` + TaskTag string `json:"task_tag,omitempty"` + TaskID string `json:"task_id,omitempty"` + TaskQueueID string `json:"task_queue_id,omitempty"` + Title string `json:"title"` + Description string `json:"description"` + Severity string `json:"severity"` // critical, high, medium, low, info + Status string `json:"status"` // open, confirmed, fixed, false_positive, ignored + Type string `json:"type"` + Target string `json:"target"` + TargetHost *string `json:"target_host,omitempty"` + TargetDomain string `json:"target_domain,omitempty"` + Targets []VulnerabilityTarget `json:"targets"` + CaseID string `json:"case_id,omitempty"` + CaseTitle string `json:"case_title,omitempty"` + SummaryOnly bool `json:"summary_only,omitempty"` + Preconditions string `json:"preconditions"` + ReproSteps string `json:"reproduction_steps"` + Evidence string `json:"evidence"` + Impact string `json:"impact"` + Recommendation string `json:"recommendation"` + RetestNotes string `json:"retest_notes"` + RetestLog string `json:"retest_log"` // append-only retest evidence; kept out of retest_notes because the edit form rewrites that field wholesale + CreatedAt time.Time `json:"created_at"` + UpdatedAt time.Time `json:"updated_at"` } // CreateVulnerability 创建漏洞 @@ -190,8 +200,8 @@ func (db *DB) CreateVulnerability(vuln *Vulnerability) (*Vulnerability, error) { INSERT INTO vulnerabilities ( id, conversation_id, project_id, conversation_tag, task_tag, title, description, severity, status, vulnerability_type, target, preconditions, reproduction_steps, evidence, impact, recommendation, retest_notes, - created_at, updated_at - ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) + created_at, updated_at, targets_json, targets_version + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1) ` _, err := db.Exec( @@ -199,26 +209,28 @@ func (db *DB) CreateVulnerability(vuln *Vulnerability) (*Vulnerability, error) { vuln.ID, nullIfEmpty(vuln.ConversationID), nullIfEmpty(vuln.ProjectID), vuln.ConversationTag, vuln.TaskTag, vuln.Title, vuln.Description, vuln.Severity, vuln.Status, vuln.Type, vuln.Target, vuln.Preconditions, vuln.ReproSteps, vuln.Evidence, vuln.Impact, vuln.Recommendation, vuln.RetestNotes, - vuln.CreatedAt, vuln.UpdatedAt, + vuln.CreatedAt, vuln.UpdatedAt, vulnerabilityTargetsJSON(vuln.Target), ) if err != nil { return nil, fmt.Errorf("创建漏洞失败: %w", err) } db.refreshAssetRiskCacheForConversationsBestEffort(vuln.ConversationID) - return vuln, nil + return db.GetVulnerability(vuln.ID) } // GetVulnerability 获取漏洞 func (db *DB) GetVulnerability(id string) (*Vulnerability, error) { var vuln Vulnerability + var targets string query := ` - SELECT id, COALESCE(conversation_id,''), COALESCE(project_id,''), title, description, severity, status, - conversation_tag, task_tag, vulnerability_type, target, + SELECT id, COALESCE(conversation_id,''), COALESCE(project_id,''), title, COALESCE(description,''), severity, status, + COALESCE(conversation_tag,''), COALESCE(task_tag,''), COALESCE(vulnerability_type,''), COALESCE(target,''), COALESCE(preconditions,''), COALESCE(reproduction_steps,''), COALESCE(evidence,''), - impact, recommendation, COALESCE(retest_notes,''), COALESCE(retest_log,''), + COALESCE(impact,''), COALESCE(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, targets_json, COALESCE(case_id,''), + COALESCE((SELECT title FROM vulnerability_cases vc WHERE vc.id=vulnerabilities.case_id),'') FROM vulnerabilities WHERE id = ? ` @@ -228,7 +240,7 @@ func (db *DB) GetVulnerability(id string) (*Vulnerability, error) { &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, &targets, &vuln.CaseID, &vuln.CaseTitle, ) if err != nil { if err == sql.ErrNoRows { @@ -237,7 +249,7 @@ func (db *DB) GetVulnerability(id string) (*Vulnerability, error) { return nil, fmt.Errorf("获取漏洞失败: %w", err) } - return &vuln, nil + return &vuln, scanVulnerabilityTargets(targets, &vuln) } // ListVulnerabilities 列出漏洞 @@ -304,9 +316,13 @@ const vulnerabilitySeverityRankExpr = `CASE severity func vulnerabilityGroupQuery(filter VulnerabilityListFilter, access RBACListAccess, groupBy string) (string, []interface{}) { var key string + join := "" switch groupBy { case "host": - key = "vulnerability_target_host(target)" + key = "COALESCE(json_extract(jt.value,'$.host'),'')" + join = " LEFT JOIN json_each(targets_json) jt ON 1=1" + case "case": + key = "CASE WHEN case_id IS NOT NULL THEN 'case:' || case_id ELSE 'row:' || vulnerabilities.id END" case "task": key = `CASE WHEN ` + vulnerabilityTaskIDExpr + ` <> '' THEN 'id:' || ` + vulnerabilityTaskIDExpr + ` @@ -315,9 +331,13 @@ func vulnerabilityGroupQuery(filter VulnerabilityListFilter, access RBACListAcce default: return "", nil } - query := "SELECT id, created_at, " + vulnerabilitySeverityRankExpr + " AS severity_rank, " + - key + " AS group_key FROM vulnerabilities WHERE 1=1" + query := "SELECT DISTINCT vulnerabilities.id, created_at, " + vulnerabilitySeverityRankExpr + " AS severity_rank, " + + key + " AS group_key FROM vulnerabilities" + join + " WHERE 1=1" query, args := filter.appendWhere(query, nil) + if groupBy == "host" && strings.TrimSpace(filter.HostQuery) != "" { + query += ` AND json_extract(jt.value,'$.host') LIKE ? ESCAPE '\'` + args = append(args, escapeVulnerabilityLikePattern(strings.ToLower(strings.TrimSpace(filter.HostQuery)))) + } return appendVulnerabilityAccessFilter(query, args, access) } @@ -364,14 +384,21 @@ func (db *DB) ListVulnerabilitiesByGroupForAccess(limit, offset int, filter Vuln } else if groupBy == "none" || sortBy != "" { order = itemOrder } + description := "COALESCE(description,'')" + details := `COALESCE(preconditions,''), COALESCE(reproduction_steps,''), COALESCE(evidence,''), + COALESCE(impact,''), COALESCE(recommendation,''), COALESCE(retest_notes,''), COALESCE(retest_log,'')` + if filter.SummaryOnly { + description = "SUBSTR(COALESCE(description,''),1,240)" + details = "'','','','','','',''" + } 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,''), + SELECT vulnerabilities.id, COALESCE(conversation_id,''), COALESCE(project_id,''), title, ` + description + `, severity, status, COALESCE(conversation_tag,''), COALESCE(task_tag,''), + COALESCE(vulnerability_type,''), COALESCE(target,''), + ` + details + `, ` + 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 + created_at, updated_at, ` + hostExpr + ` AS target_host, targets_json, COALESCE(case_id,''), + COALESCE((SELECT title FROM vulnerability_cases vc WHERE vc.id=vulnerabilities.case_id),'') FROM vulnerabilities` + join + ` WHERE 1=1 ` @@ -394,12 +421,13 @@ func (db *DB) ListVulnerabilitiesByGroupForAccess(limit, offset int, filter Vuln vulnerabilities := make([]*Vulnerability, 0) for rows.Next() { var vuln Vulnerability + var targets string err := rows.Scan( &vuln.ID, &vuln.ConversationID, &vuln.ProjectID, &vuln.Title, &vuln.Description, &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.TargetHost, + &vuln.CreatedAt, &vuln.UpdatedAt, &vuln.TargetHost, &targets, &vuln.CaseID, &vuln.CaseTitle, ) if err != nil { db.logger.Warn("扫描漏洞记录失败", zap.Error(err)) @@ -413,6 +441,10 @@ func (db *DB) ListVulnerabilitiesByGroupForAccess(limit, offset int, filter Vuln } } } + if err := scanVulnerabilityTargets(targets, &vuln); err != nil { + return nil, err + } + vuln.SummaryOnly = filter.SummaryOnly vulnerabilities = append(vulnerabilities, &vuln) } @@ -449,19 +481,30 @@ func (db *DB) UpdateVulnerability(id string, vuln *Vulnerability) error { UPDATE vulnerabilities SET project_id = ?, conversation_tag = ?, task_tag = ?, title = ?, description = ?, severity = ?, status = ?, vulnerability_type = ?, target = ?, preconditions = ?, reproduction_steps = ?, evidence = ?, impact = ?, - recommendation = ?, retest_notes = ?, updated_at = ? + recommendation = ?, retest_notes = ?, updated_at = ?, targets_json = ?, targets_version=1 WHERE id = ? ` - _, err := db.Exec( + tx, err := db.Begin() + if err != nil { + return err + } + defer tx.Rollback() + if err := detachVulnerabilityCaseOnProjectChange(tx, id, vuln.ProjectID); err != nil { + return err + } + _, err = tx.Exec( query, nullIfEmpty(vuln.ProjectID), vuln.ConversationTag, vuln.TaskTag, vuln.Title, vuln.Description, vuln.Severity, vuln.Status, vuln.Type, vuln.Target, vuln.Preconditions, vuln.ReproSteps, vuln.Evidence, vuln.Impact, - vuln.Recommendation, vuln.RetestNotes, vuln.UpdatedAt, id, + vuln.Recommendation, vuln.RetestNotes, vuln.UpdatedAt, vulnerabilityTargetsJSON(vuln.Target), id, ) if err != nil { return fmt.Errorf("更新漏洞失败: %w", err) } + if err := tx.Commit(); err != nil { + return err + } db.refreshAssetRiskCacheForConversationsBestEffort(oldConversationID, vuln.ConversationID) return nil @@ -574,6 +617,11 @@ func (db *DB) GetVulnerabilityStatsForAccess(filter VulnerabilityListFilter, acc return nil, fmt.Errorf("获取总漏洞数失败: %w", err) } stats["total"] = totalCount + var distinctCount int + if err := db.QueryRow("SELECT COUNT(DISTINCT CASE WHEN case_id IS NULL THEN 'row:'||id ELSE 'case:'||case_id END) FROM vulnerabilities "+where, args...).Scan(&distinctCount); err != nil { + return nil, err + } + stats["distinct"] = distinctCount // 按严重程度统计 severityQuery := "SELECT severity, COUNT(*) FROM vulnerabilities " + where + " GROUP BY severity" diff --git a/internal/database/vulnerability_retest.go b/internal/database/vulnerability_retest.go index a219d3ad..539fea9e 100644 --- a/internal/database/vulnerability_retest.go +++ b/internal/database/vulnerability_retest.go @@ -1,7 +1,9 @@ package database import ( + "crypto/sha256" "database/sql" + "encoding/json" "fmt" "strings" "time" @@ -106,7 +108,11 @@ func (db *DB) CreateVulnerabilityRetest(v *Vulnerability, meta ConversationCreat return nil, err } } - if _, err = tx.Exec(`INSERT INTO vulnerability_retests (conversation_id, source_conversation_id, vulnerability_id, source_project_id) VALUES (?,?,?,?)`, id, v.ConversationID, v.ID, conv.ProjectID); err != nil { + snapshot, err := json.Marshal(v) + if err != nil { + return nil, err + } + if _, err = tx.Exec(`INSERT INTO vulnerability_retests (conversation_id, source_conversation_id, vulnerability_id, source_project_id, snapshot_json) VALUES (?,?,?,?,?)`, id, v.ConversationID, v.ID, conv.ProjectID, string(snapshot)); err != nil { return nil, err } // Preserve the source's approval policy without copying live interrupts. @@ -131,8 +137,23 @@ func (db *DB) CreateVulnerabilityRetest(v *Vulnerability, meta ConversationCreat // UpdateVulnerabilityRetestResult appends evidence to retest_log; retest_notes stays operator-owned. func (db *DB) UpdateVulnerabilityRetestResult(id, status, notes, conversationID string) error { + tx, err := db.Begin() + if err != nil { + return err + } + defer tx.Rollback() + key := fmt.Sprintf("%x", sha256.Sum256([]byte(id+"\x00"+conversationID+"\x00"+status+"\x00"+notes))) + insert, err := tx.Exec("INSERT OR IGNORE INTO vulnerability_retest_results(id,vulnerability_id,conversation_id,status,evidence) VALUES(?,?,?,?,?)", key, id, conversationID, status, notes) + if err != nil { + return err + } + if n, err := insert.RowsAffected(); err != nil { + return err + } else if n == 0 { + return nil + } entry := fmt.Sprintf("\n\n[复测 %s | 对话 %s | 状态 %s]\n%s", time.Now().Format(time.RFC3339), conversationID, status, notes) - result, err := db.Exec(`UPDATE vulnerabilities SET status=?, retest_log=COALESCE(retest_log,'') || ?, updated_at=? WHERE id=?`, status, entry, time.Now(), id) + result, err := tx.Exec(`UPDATE vulnerabilities SET status=?, retest_log=COALESCE(retest_log,'') || ?, updated_at=? WHERE id=?`, status, entry, time.Now(), id) if err != nil { return err } @@ -143,6 +164,9 @@ func (db *DB) UpdateVulnerabilityRetestResult(id, status, notes, conversationID if n != 1 { return fmt.Errorf("漏洞不存在") } + if err := tx.Commit(); err != nil { + return err + } if v, err := db.GetVulnerability(id); err == nil { db.refreshAssetRiskCacheForConversationsBestEffort(v.ConversationID) } diff --git a/internal/database/vulnerability_workspace.go b/internal/database/vulnerability_workspace.go new file mode 100644 index 00000000..c48e7a8a --- /dev/null +++ b/internal/database/vulnerability_workspace.go @@ -0,0 +1,288 @@ +package database + +import ( + "database/sql" + "encoding/json" + "errors" + "fmt" + "net/netip" + "net/url" + "regexp" + "strings" + "time" + + "github.com/google/uuid" + "golang.org/x/net/publicsuffix" +) + +type VulnerabilityTarget struct { + Raw string `json:"raw"` + Host string `json:"host"` + Domain string `json:"domain"` + Scheme string `json:"scheme,omitempty"` + Port string `json:"port,omitempty"` + Path string `json:"path,omitempty"` +} + +var vulnerabilityTargetPattern = regexp.MustCompile(`(?i)(?:[a-z][a-z0-9+.-]*://|//)[^\s<>"',;,;、()]+|(?:\[[0-9a-f:]+\]|(?:[\p{L}\p{N}][\p{L}\p{N}.-]*\.)+[\p{L}\p{N}-]+|localhost)(?::[0-9]+)?(?:/[^\s<>"',;,;、()]*)?`) + +func vulnerabilityTargetsJSON(raw string) string { + targets := []VulnerabilityTarget{} + seen := map[string]bool{} + matches := vulnerabilityTargetPattern.FindAllStringIndex(raw, -1) + if len(matches) == 0 { + matches = [][]int{{0, len(raw)}} + } + for _, match := range matches { + candidate := strings.TrimSpace(raw[match[0]:match[1]]) + if match[0] > 0 && strings.ContainsRune("/@", rune(raw[match[0]-1])) && !strings.Contains(candidate, "://") { + continue + } + candidate = strings.TrimRight(candidate, ".,;:!?)\x60") + host := vulnerabilityTargetHost(candidate) + if host == "" { + continue + } + if _, err := netip.ParseAddr(host); err != nil && strings.Trim(host, "0123456789.") == "" { + continue + } + target := VulnerabilityTarget{Raw: candidate, Host: host, Domain: host} + if _, err := netip.ParseAddr(host); err != nil { + if domain, err := publicsuffix.EffectiveTLDPlusOne(host); err == nil { + target.Domain = domain + } + } + value := candidate + if !strings.Contains(value, "://") && !strings.HasPrefix(value, "//") { + value = "//" + value + } + if parsed, err := url.Parse(value); err == nil { + target.Scheme = strings.ToLower(parsed.Scheme) + target.Port = parsed.Port() + target.Path = parsed.EscapedPath() + } + key := target.Host + "|" + target.Scheme + "|" + target.Port + "|" + target.Path + if seen[key] { + continue + } + seen[key] = true + targets = append(targets, target) + } + data, _ := json.Marshal(targets) + return string(data) +} + +func (db *DB) backfillVulnerabilityTargets() error { + tx, err := db.Begin() + if err != nil { + return err + } + defer tx.Rollback() + rows, err := tx.Query("SELECT id, COALESCE(target,'') FROM vulnerabilities WHERE targets_version=0") + if err != nil { + return err + } + targets := map[string]string{} + for rows.Next() { + var id, raw string + if err := rows.Scan(&id, &raw); err != nil { + rows.Close() + return err + } + targets[id] = vulnerabilityTargetsJSON(raw) + } + err = rows.Err() + rows.Close() + if err != nil { + return err + } + for id, raw := range targets { + if _, err := tx.Exec("UPDATE vulnerabilities SET targets_json=?,targets_version=1 WHERE id=?", raw, id); err != nil { + return err + } + } + return tx.Commit() +} + +type VulnerabilityLinkedAsset struct { + ID string `json:"id"` + Host string `json:"host"` + Port int `json:"port"` +} + +func (db *DB) VulnerabilityLinkedAssets(v *Vulnerability, access RBACListAccess) ([]VulnerabilityLinkedAsset, error) { + query, args := appendAssetAccess(`SELECT assets.id, assets.host, COALESCE(assets.port,0) + FROM assets WHERE COALESCE(assets.project_id,'')=? AND EXISTS ( + SELECT 1 FROM json_each(?) jt WHERE + json_extract(jt.value,'$.host')=LOWER(COALESCE(NULLIF(assets.domain,''),NULLIF(assets.ip,''),assets.host)) + AND (COALESCE(assets.port,0)=0 OR CAST(json_extract(jt.value,'$.port') AS INTEGER)=assets.port + OR (COALESCE(json_extract(jt.value,'$.port'),'')='' AND + ((json_extract(jt.value,'$.scheme')='https' AND assets.port=443) + OR (json_extract(jt.value,'$.scheme')='http' AND assets.port=80)))) + )`, []interface{}{v.ProjectID, vulnerabilityTargetsJSON(v.Target)}, access, "assets") + rows, err := db.Query(query, args...) + if err != nil { + return nil, err + } + defer rows.Close() + assets := []VulnerabilityLinkedAsset{} + for rows.Next() { + var a VulnerabilityLinkedAsset + if err := rows.Scan(&a.ID, &a.Host, &a.Port); err != nil { + return nil, err + } + assets = append(assets, a) + } + return assets, rows.Err() +} + +// MergeVulnerabilities preserves original reports. The transaction reserves the +// writer before checking membership, ownership and project boundaries. +func (db *DB) MergeVulnerabilities(ids []string, title, reason, actor string, access RBACListAccess) (string, error) { + if len(ids) < 2 || len(ids) > 100 || strings.TrimSpace(title) == "" || strings.TrimSpace(reason) == "" { + return "", errors.New("请选择 2–100 条记录,并填写漏洞名称和归并理由") + } + tx, err := db.Begin() + if err != nil { + return "", err + } + defer tx.Rollback() + seen := map[string]bool{} + project := "" + for i, id := range ids { + if seen[id] { + return "", errors.New("重复的漏洞 ID") + } + seen[id] = true + query, args := appendVulnerabilityAccessFilter("SELECT COALESCE(project_id,''), COALESCE(case_id,'') FROM vulnerabilities WHERE id=?", []interface{}{id}, access) + var pid, cid string + if err := tx.QueryRow(query, args...).Scan(&pid, &cid); err != nil { + return "", errors.New("漏洞不存在或无权归并") + } + if cid != "" { + return "", errors.New("记录已归并,请先拆分原归并组") + } + if i == 0 { + project = pid + } else if project != pid { + return "", errors.New("归并记录必须属于同一项目") + } + } + id := uuid.NewString() + if _, err := tx.Exec("INSERT INTO vulnerability_cases(id,project_id,title,reason) VALUES(?,?,?,?)", id, project, strings.TrimSpace(title), strings.TrimSpace(reason)); err != nil { + return "", err + } + for _, member := range ids { + if _, err := tx.Exec("UPDATE vulnerabilities SET case_id=? WHERE id=?", id, member); err != nil { + return "", err + } + } + rawIDs, _ := json.Marshal(ids) + if _, err := tx.Exec("INSERT INTO vulnerability_case_events(case_id,action,actor,reason,finding_ids) VALUES(?,?,?,?,?)", + id, "merge", actor, strings.TrimSpace(reason), string(rawIDs)); err != nil { + return "", err + } + return id, tx.Commit() +} + +func (db *DB) DissolveVulnerabilityCase(id, reason, actor string, access RBACListAccess) error { + if strings.TrimSpace(reason) == "" { + return errors.New("请填写拆分理由") + } + tx, err := db.Begin() + if err != nil { + return err + } + defer tx.Rollback() + var all, allowed int + if err = tx.QueryRow("SELECT COUNT(*) FROM vulnerabilities WHERE case_id=?", id).Scan(&all); err != nil { + return err + } + query, args := appendVulnerabilityAccessFilter("SELECT COUNT(*) FROM vulnerabilities WHERE case_id=?", []interface{}{id}, access) + if err = tx.QueryRow(query, args...).Scan(&allowed); err != nil { + return err + } + if all == 0 || all != allowed { + return errors.New("归并组不存在或无权修改全部成员") + } + if _, err = tx.Exec(`INSERT INTO vulnerability_case_events(case_id,action,actor,reason,finding_ids) + SELECT ?, 'split', ?, ?, json_group_array(id) FROM vulnerabilities WHERE case_id=?`, id, actor, reason, id); err != nil { + return err + } + if _, err = tx.Exec("UPDATE vulnerabilities SET case_id=NULL WHERE case_id=?", id); err != nil { + return err + } + if _, err = tx.Exec("DELETE FROM vulnerability_cases WHERE id=?", id); err != nil { + return err + } + return tx.Commit() +} + +type VulnerabilityHistoryItem struct { + Kind string `json:"kind"` + ConversationID string `json:"conversation_id,omitempty"` + Status string `json:"status,omitempty"` + Evidence string `json:"evidence,omitempty"` + Actor string `json:"actor,omitempty"` + CreatedAt time.Time `json:"created_at"` + Snapshot *Vulnerability `json:"snapshot,omitempty"` +} + +func (db *DB) VulnerabilityHistory(id string) ([]VulnerabilityHistoryItem, error) { + rows, err := db.Query(` + SELECT 'retest',conversation_id,status,evidence,'',created_at, + COALESCE((SELECT snapshot_json FROM vulnerability_retests vr WHERE vr.conversation_id=vulnerability_retest_results.conversation_id),'') + FROM vulnerability_retest_results WHERE vulnerability_id=? + UNION ALL + SELECT action,'','',reason,actor,created_at,'' FROM vulnerability_case_events + WHERE EXISTS (SELECT 1 FROM json_each(finding_ids) WHERE value=?) + UNION ALL + SELECT 'retest_started',vr.conversation_id,'','','',c.created_at,vr.snapshot_json + FROM vulnerability_retests vr JOIN conversations c ON c.id=vr.conversation_id + WHERE vr.vulnerability_id=? AND NOT EXISTS ( + SELECT 1 FROM vulnerability_retest_results r WHERE r.vulnerability_id=vr.vulnerability_id AND r.conversation_id=vr.conversation_id) + ORDER BY created_at DESC`, id, id, id) + if err != nil { + return nil, err + } + defer rows.Close() + items := []VulnerabilityHistoryItem{} + for rows.Next() { + var item VulnerabilityHistoryItem + var snapshot string + if err := rows.Scan(&item.Kind, &item.ConversationID, &item.Status, &item.Evidence, &item.Actor, &item.CreatedAt, &snapshot); err != nil { + return nil, err + } + if snapshot != "" { + if err := json.Unmarshal([]byte(snapshot), &item.Snapshot); err != nil { + return nil, err + } + } + items = append(items, item) + } + return items, rows.Err() +} + +func scanVulnerabilityTargets(raw string, v *Vulnerability) error { + if err := json.Unmarshal([]byte(raw), &v.Targets); err != nil { + return fmt.Errorf("读取漏洞目标失败: %w", err) + } + return nil +} + +// Keep project changes from silently carrying a cross-project merge relation. +func detachVulnerabilityCaseOnProjectChange(tx *sql.Tx, id, projectID string) error { + var oldProject, caseID string + if err := tx.QueryRow("SELECT COALESCE(project_id,''),COALESCE(case_id,'') FROM vulnerabilities WHERE id=?", id).Scan(&oldProject, &caseID); err != nil { + return err + } + if caseID == "" || oldProject == projectID { + return nil + } + raw, _ := json.Marshal([]string{id}) + if _, err := tx.Exec("INSERT INTO vulnerability_case_events(case_id,action,actor,reason,finding_ids) VALUES(?,'detach','system','项目归属变更',?)", caseID, string(raw)); err != nil { + return err + } + _, err := tx.Exec("UPDATE vulnerabilities SET case_id=NULL WHERE id=?", id) + return err +} diff --git a/internal/database/vulnerability_workspace_test.go b/internal/database/vulnerability_workspace_test.go new file mode 100644 index 00000000..21b1cad1 --- /dev/null +++ b/internal/database/vulnerability_workspace_test.go @@ -0,0 +1,153 @@ +package database + +import ( + "encoding/json" + "strings" + "testing" +) + +func TestVulnerabilityWorkspaceTargetsAndLegacyUpgrade(t *testing.T) { + db := newRBACTestDB(t) + v, err := db.CreateVulnerability(&Vulnerability{Title: "multiple", Severity: "high", Target: "https://api.example.co.uk/login;https://store.example.co.uk:8443/orders, http://192.0.2.5:8080/"}) + if err != nil { + t.Fatal(err) + } + if len(v.Targets) != 3 || v.Targets[0].Domain != "example.co.uk" || v.Targets[2].Domain != "192.0.2.5" { + t.Fatalf("targets: %+v", v.Targets) + } + if _, err := db.Exec("UPDATE vulnerabilities SET targets_json='[]',targets_version=0 WHERE id=?", v.ID); err != nil { + t.Fatal(err) + } + for i := 0; i < 2; i++ { + if err := db.initTables(); err != nil { + t.Fatal(err) + } + } + count, err := db.CountVulnerabilityGroupsForAccess(VulnerabilityListFilter{}, RBACListAccess{}, "host") + if err != nil || count != 3 { + t.Fatalf("host count: %d %v", count, err) + } + rows, err := db.ListVulnerabilitiesByGroupForAccess(2, 0, VulnerabilityListFilter{SummaryOnly: true}, RBACListAccess{}, "host", "") + if err != nil || len(rows) != 2 || rows[0].ID != v.ID || rows[1].ID != v.ID { + t.Fatalf("group page: %+v %v", rows, err) + } + matched, err := db.ListVulnerabilitiesByGroupForAccess(20, 0, VulnerabilityListFilter{ID: v.ID, HostQuery: "store."}, RBACListAccess{}, "host", "") + if err != nil || len(matched) != 1 || *matched[0].TargetHost != "store.example.co.uk" { + t.Fatalf("host search: %+v %v", matched, err) + } +} + +func TestVulnerabilityTargetParserIgnoresRelativeEndpoints(t *testing.T) { + if got := vulnerabilityTargetsJSON("GET /api/config.php HTTP/1.1"); got != "[]" { + t.Fatalf("relative endpoint parsed as host: %s", got) + } + var targets []VulnerabilityTarget + if err := json.Unmarshal([]byte(vulnerabilityTargetsJSON("https://a.example.com/a,https://b.example.com/b")), &targets); err != nil || len(targets) != 2 { + t.Fatalf("comma-separated targets: %+v %v", targets, err) + } +} + +func TestVulnerabilityWorkspaceMergeSplitAndScope(t *testing.T) { + db := newRBACTestDB(t) + a, _ := db.CreateVulnerability(&Vulnerability{Title: "report A", Severity: "high", Evidence: "request A"}) + b, _ := db.CreateVulnerability(&Vulnerability{Title: "report B", Severity: "medium", Evidence: "request B"}) + if _, err := db.MergeVulnerabilities([]string{a.ID, b.ID}, "issue", "same root cause", "reader", RBACListAccess{UserID: "outsider", Scope: RBACScopeAssigned}); err == nil { + t.Fatal("unauthorized merge") + } + id, err := db.MergeVulnerabilities([]string{a.ID, b.ID}, "issue", "same root cause", "operator", RBACListAccess{}) + if err != nil { + t.Fatal(err) + } + rows, err := db.ListVulnerabilitiesByGroupForAccess(1, 0, VulnerabilityListFilter{SummaryOnly: true}, RBACListAccess{}, "case", "") + if err != nil || len(rows) != 2 || rows[0].CaseID != id || rows[0].Evidence != "" || !rows[0].SummaryOnly { + t.Fatalf("case summaries: %+v %v", rows, err) + } + stats, err := db.GetVulnerabilityStats(VulnerabilityListFilter{}) + if err != nil || stats["distinct"] != 1 || stats["total"] != 2 { + t.Fatalf("stats: %+v %v", stats, err) + } + got, err := db.GetVulnerability(a.ID) + if err != nil || got.Evidence != "request A" { + t.Fatal("original evidence changed", err) + } + if _, err := db.MergeVulnerabilities([]string{a.ID, b.ID}, "again", "retry", "operator", RBACListAccess{}); err == nil { + t.Fatal("accepted already merged records") + } + if err := db.DissolveVulnerabilityCase(id, "different causes", "outsider", RBACListAccess{UserID: "outsider", Scope: RBACScopeAssigned}); err == nil { + t.Fatal("unauthorized split") + } + if err := db.DissolveVulnerabilityCase(id, "different causes", "operator", RBACListAccess{}); err != nil { + t.Fatal(err) + } + got, _ = db.GetVulnerability(a.ID) + if got.CaseID != "" || got.Evidence != "request A" { + t.Fatal("split damaged original") + } + history, err := db.VulnerabilityHistory(a.ID) + if err != nil || len(history) != 2 { + t.Fatalf("history: %+v %v", history, err) + } +} + +func TestVulnerabilityWorkspaceRetestIdempotencyAndSnapshot(t *testing.T) { + db := newRBACTestDB(t) + source, _ := db.CreateConversation("source", ConversationCreateMeta{}) + v, _ := db.CreateVulnerability(&Vulnerability{Title: "finding", Evidence: "original proof", Severity: "high", ConversationID: source.ID}) + branch, err := db.CreateVulnerabilityRetest(v, ConversationCreateMeta{}) + if err != nil { + t.Fatal(err) + } + var raw string + if err := db.QueryRow("SELECT snapshot_json FROM vulnerability_retests WHERE conversation_id=?", branch.ID).Scan(&raw); err != nil { + t.Fatal(err) + } + var snapshot Vulnerability + if err := json.Unmarshal([]byte(raw), &snapshot); err != nil || snapshot.Evidence != "original proof" { + t.Fatal("snapshot", err) + } + if err := db.UpdateVulnerabilityRetestResult(v.ID, "fixed", "403 verified", branch.ID); err != nil { + t.Fatal(err) + } + v.Status = "confirmed" + v.Evidence = "new proof" + if err := db.UpdateVulnerability(v.ID, v); err != nil { + t.Fatal(err) + } + if err := db.UpdateVulnerabilityRetestResult(v.ID, "fixed", "403 verified", branch.ID); err != nil { + t.Fatal(err) + } + got, _ := db.GetVulnerability(v.ID) + if got.Status != "confirmed" || strings.Count(got.RetestLog, "403 verified") != 1 { + t.Fatalf("retry changed state: %+v", got) + } + history, err := db.VulnerabilityHistory(v.ID) + if err != nil || len(history) != 1 || history[0].Status != "fixed" { + t.Fatalf("history: %+v %v", history, err) + } +} + +func TestVulnerabilityWorkspaceProjectBoundary(t *testing.T) { + db := newRBACTestDB(t) + p1, _ := db.CreateProject(&Project{Name: "one"}) + p2, _ := db.CreateProject(&Project{Name: "two"}) + a, _ := db.CreateVulnerability(&Vulnerability{Title: "a", Severity: "high", ProjectID: p1.ID}) + b, _ := db.CreateVulnerability(&Vulnerability{Title: "b", Severity: "high", ProjectID: p2.ID}) + if _, err := db.MergeVulnerabilities([]string{a.ID, b.ID}, "issue", "similar", "op", RBACListAccess{}); err == nil { + t.Fatal("cross project merge") + } + b.ProjectID = p1.ID + if err := db.UpdateVulnerability(b.ID, b); err != nil { + t.Fatal(err) + } + if _, err := db.MergeVulnerabilities([]string{a.ID, b.ID}, "issue", "same", "op", RBACListAccess{}); err != nil { + t.Fatal(err) + } + b.ProjectID = p2.ID + if err := db.UpdateVulnerability(b.ID, b); err != nil { + t.Fatal(err) + } + got, _ := db.GetVulnerability(b.ID) + if got.CaseID != "" { + t.Fatal("project move retained case") + } +} diff --git a/internal/handler/vulnerability.go b/internal/handler/vulnerability.go index 7d54a73a..52e68e5f 100644 --- a/internal/handler/vulnerability.go +++ b/internal/handler/vulnerability.go @@ -169,6 +169,7 @@ func parseVulnerabilityListFilter(c *gin.Context) database.VulnerabilityListFilt ID: c.Query("id"), Search: q, HostQuery: c.Query("host_q"), + CaseID: c.Query("case_id"), ConversationID: c.Query("conversation_id"), Severity: c.Query("severity"), Status: c.Query("status"), @@ -184,6 +185,7 @@ func (h *VulnerabilityHandler) ListVulnerabilities(c *gin.Context) { offsetStr := c.DefaultQuery("offset", "0") pageStr := c.Query("page") filter := parseVulnerabilityListFilter(c) + filter.SummaryOnly = c.Query("summary") == "true" access := vulnerabilityAccessFromContext(c) groupBy := c.Query("group_by") sortBy := c.Query("sort") @@ -230,7 +232,7 @@ func (h *VulnerabilityHandler) ListVulnerabilities(c *gin.Context) { page = (offset / limit) + 1 } - if (groupBy == "host" || groupBy == "task" || groupBy == "none") && page > totalPages { + if (groupBy == "host" || groupBy == "task" || groupBy == "none" || groupBy == "case") && page > totalPages { page = totalPages offset = (page - 1) * limit } diff --git a/internal/handler/vulnerability_group_test.go b/internal/handler/vulnerability_group_test.go index 5ada4cdb..6fd6677f 100644 --- a/internal/handler/vulnerability_group_test.go +++ b/internal/handler/vulnerability_group_test.go @@ -74,8 +74,8 @@ func TestListVulnerabilitiesGroupedViews(t *testing.T) { page, total, pages int ids, hosts []string }{ - {"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=host&page=1", 1, 5, 3, []string{"ipv6", "domain-new", "domain-old"}, []string{"2001:db8::1", "example.com", "example.com"}}, + {"group_by=host&page=4", 3, 5, 3, []string{"unknown"}, []string{""}}, {"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}, @@ -117,8 +117,8 @@ func TestListVulnerabilitiesGroupedViews(t *testing.T) { query string ids []string }{ - {"group_by=host&sort=severity&page=1", []string{"domain-old", "domain-new", "filtered", "unknown"}}, - {"group_by=host&sort=severity&page=2", []string{"subdomain", "ipv6"}}, + {"group_by=host&sort=severity&page=1", []string{"domain-old", "domain-new", "filtered", "domain-old"}}, + {"group_by=host&sort=severity&page=2", []string{"unknown", "subdomain"}}, {"group_by=task&sort=severity&page=1", []string{"domain-old", "subdomain", "unknown"}}, {"group_by=task&sort=severity&page=2", []string{"domain-new", "filtered", "ipv6"}}, {"group_by=host&sort=latest", []string{"filtered", "domain-new", "domain-old", "unknown"}}, diff --git a/internal/handler/vulnerability_workspace.go b/internal/handler/vulnerability_workspace.go new file mode 100644 index 00000000..eb12046c --- /dev/null +++ b/internal/handler/vulnerability_workspace.go @@ -0,0 +1,79 @@ +package handler + +import ( + "cyberstrike-ai/internal/database" + "cyberstrike-ai/internal/security" + "github.com/gin-gonic/gin" + "net/http" +) + +func (h *VulnerabilityHandler) VulnerabilityContext(c *gin.Context) { + v, err := h.db.GetVulnerability(c.Param("id")) + if err != nil { + c.JSON(http.StatusNotFound, gin.H{"error": "漏洞不存在"}) + return + } + history, err := h.db.VulnerabilityHistory(v.ID) + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + return + } + members := []*database.Vulnerability{} + if v.CaseID != "" { + members, err = h.db.ListVulnerabilitiesForAccess(100, 0, database.VulnerabilityListFilter{CaseID: v.CaseID, SummaryOnly: true}, vulnerabilityAccessFromContext(c)) + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + return + } + } + assets := []database.VulnerabilityLinkedAsset{} + if session, ok := security.CurrentSession(c); ok && security.SessionHasPermission(c, "asset:read") { + assets, err = h.db.VulnerabilityLinkedAssets(v, database.RBACListAccess{UserID: session.UserID, Scope: session.ScopeFor("asset:read")}) + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + return + } + } + c.JSON(http.StatusOK, gin.H{"vulnerability": v, "history": history, "members": members, "assets": assets}) +} + +func (h *VulnerabilityHandler) MergeVulnerabilities(c *gin.Context) { + var req struct { + IDs []string `json:"ids" binding:"required"` + Title string `json:"title" binding:"required"` + Reason string `json:"reason" binding:"required"` + } + if err := c.ShouldBindJSON(&req); err != nil || len(req.Title) > 500 || len(req.Reason) > 4000 { + c.JSON(http.StatusBadRequest, gin.H{"error": "请提供选中记录、名称和归并理由"}) + return + } + access := vulnerabilityAccessFromContext(c) + id, err := h.db.MergeVulnerabilities(req.IDs, req.Title, req.Reason, access.UserID, access) + if err != nil { + c.JSON(http.StatusConflict, gin.H{"error": err.Error()}) + return + } + if h.audit != nil { + h.audit.RecordOK(c, "vulnerability", "merge", "归并漏洞上报", "vulnerability_case", id, map[string]interface{}{"ids": req.IDs}) + } + c.JSON(http.StatusOK, gin.H{"id": id}) +} + +func (h *VulnerabilityHandler) DissolveVulnerabilityCase(c *gin.Context) { + var req struct { + Reason string `json:"reason" binding:"required"` + } + if err := c.ShouldBindJSON(&req); err != nil || len(req.Reason) > 4000 { + c.JSON(http.StatusBadRequest, gin.H{"error": "请填写拆分理由"}) + return + } + access := vulnerabilityAccessFromContext(c) + if err := h.db.DissolveVulnerabilityCase(c.Param("caseID"), req.Reason, access.UserID, access); err != nil { + c.JSON(http.StatusConflict, gin.H{"error": err.Error()}) + return + } + if h.audit != nil { + h.audit.RecordOK(c, "vulnerability", "split", "拆分漏洞归并组", "vulnerability_case", c.Param("caseID"), nil) + } + c.JSON(http.StatusOK, gin.H{"ok": true}) +} diff --git a/internal/handler/vulnerability_workspace_test.go b/internal/handler/vulnerability_workspace_test.go new file mode 100644 index 00000000..b1285d22 --- /dev/null +++ b/internal/handler/vulnerability_workspace_test.go @@ -0,0 +1,78 @@ +package handler + +import ( + "bytes" + "encoding/json" + "net/http" + "net/http/httptest" + "path/filepath" + "testing" + + "cyberstrike-ai/internal/database" + "github.com/gin-gonic/gin" + "go.uber.org/zap" +) + +func TestVulnerabilityWorkspaceHTTPFlow(t *testing.T) { + db, err := database.NewDB(filepath.Join(t.TempDir(), "workspace.db"), zap.NewNop()) + if err != nil { + t.Fatal(err) + } + defer db.Close() + h := NewVulnerabilityHandler(db, zap.NewNop()) + router := gin.New() + router.POST("/vulnerabilities/cases", h.MergeVulnerabilities) + router.POST("/vulnerabilities/cases/:caseID/split", h.DissolveVulnerabilityCase) + router.GET("/vulnerabilities/:id/context", h.VulnerabilityContext) + router.GET("/vulnerabilities", h.ListVulnerabilities) + a, _ := db.CreateVulnerability(&database.Vulnerability{Title: "one", Severity: "high", Target: "https://a.example.com", Evidence: "full proof"}) + b, _ := db.CreateVulnerability(&database.Vulnerability{Title: "two", Severity: "high", Target: "https://b.example.com", Evidence: "other proof"}) + request := func(method, path string, payload any) map[string]json.RawMessage { + t.Helper() + body, _ := json.Marshal(payload) + req := httptest.NewRequest(method, path, bytes.NewReader(body)) + req.Header.Set("Content-Type", "application/json") + rec := httptest.NewRecorder() + router.ServeHTTP(rec, req) + if rec.Code != http.StatusOK { + t.Fatalf("status %d: %s", rec.Code, rec.Body) + } + var result map[string]json.RawMessage + if err := json.Unmarshal(rec.Body.Bytes(), &result); err != nil { + t.Fatal(err) + } + return result + } + result := request("POST", "/vulnerabilities/cases", map[string]any{"ids": []string{a.ID, b.ID}, "title": "shared issue", "reason": "same root cause"}) + var id string + json.Unmarshal(result["id"], &id) + if id == "" { + t.Fatal("missing case ID") + } + result = request("GET", "/vulnerabilities?group_by=case&limit=1&summary=true", nil) + var list []*database.Vulnerability + if err := json.Unmarshal(result["vulnerabilities"], &list); err != nil { + t.Fatal(err) + } + if len(list) != 2 || list[0].Evidence != "" { + t.Fatal("summary response includes evidence") + } + context := request("GET", "/vulnerabilities/"+a.ID+"/context", nil) + var detail database.Vulnerability + json.Unmarshal(context["vulnerability"], &detail) + if detail.Evidence != "full proof" || detail.CaseID != id { + t.Fatalf("detail: %+v", detail) + } + var members []database.Vulnerability + json.Unmarshal(context["members"], &members) + if len(members) != 2 { + t.Fatalf("members: %d", len(members)) + } + request("POST", "/vulnerabilities/cases/"+id+"/split", map[string]string{"reason": "distinct causes"}) + context = request("GET", "/vulnerabilities/"+a.ID+"/context", nil) + var history []database.VulnerabilityHistoryItem + json.Unmarshal(context["history"], &history) + if len(history) != 2 { + t.Fatalf("history: %+v", history) + } +} diff --git a/web/static/css/vulnerability-workspace.css b/web/static/css/vulnerability-workspace.css new file mode 100644 index 00000000..ae144d3c --- /dev/null +++ b/web/static/css/vulnerability-workspace.css @@ -0,0 +1,182 @@ +#page-vulnerabilities { + --vuln-panel: var(--bg-primary); + --vuln-surface: var(--bg-secondary); +} + +#page-vulnerabilities > .page-header { + padding: 18px 24px; + background: var(--vuln-panel); + box-shadow: none; +} + +#page-vulnerabilities .page-content { padding: 20px 24px; } +#page-vulnerabilities .vulnerability-header-start { gap: 20px; } +#page-vulnerabilities .vulnerability-view-switch { border: 0; padding: 4px; } +#page-vulnerabilities .vulnerability-view-switch button { padding: 7px 13px; } + +.vulnerability-workspace-caption { + display: flex; + justify-content: space-between; + flex-wrap: wrap; + gap: 8px; + margin-bottom: 12px; + font-size: 13px; + color: var(--text-secondary); +} + +#vulnerability-distinct-count { font-weight: 600; color: var(--text-primary); } + +#page-vulnerabilities .dashboard-stats { + grid-template-columns: repeat(6,minmax(0,1fr)); + gap: 12px; +} + +#page-vulnerabilities .stat-card { + min-height: 110px; + padding: 16px 18px; + border: 1px solid var(--border-color); + border-radius: 12px; + background: var(--vuln-panel) !important; + box-shadow: none; + text-align: start; +} + +#page-vulnerabilities .stat-card.is-active { + border-color: var(--accent-color); + box-shadow: 0 0 0 1px var(--accent-color); +} + +#page-vulnerabilities .stat-value { + font-size: 30px; + line-height: 1.3; + font-weight: 650; + font-variant-numeric: tabular-nums; + margin: 6px 0 2px; + color: var(--text-primary); +} + +#page-vulnerabilities .stat-label { font-size: 12px; color: var(--text-secondary); } +#page-vulnerabilities .stat-pct { font-size: 11px; } +#page-vulnerabilities .stat-stacked-bar { margin-top: 10px; } +#page-vulnerabilities .vulnerability-filter-panel { border-radius: 12px; box-shadow: none; } +#page-vulnerabilities .vulnerability-list-toolbar { margin: 16px 0 12px; } +#page-vulnerabilities .vulnerability-host-browser { grid-template-columns: 248px minmax(0,1fr); gap: 20px; } +#page-vulnerabilities .vulnerability-host-sidebar { border-radius: 12px; padding: 12px; } +#page-vulnerabilities .vulnerability-host-option { padding: 10px 8px; } +#page-vulnerabilities .vulnerability-host-option[aria-pressed="true"] { background: color-mix(in srgb,var(--accent-color) 9%,transparent); } +#page-vulnerabilities .vulnerability-domain-branch > .vulnerability-host-option { padding-inline-start: 22px; } +#page-vulnerabilities .vulnerability-host-overview { min-height: 36px; margin-bottom: 12px; } +#page-vulnerabilities .vulnerability-host-results-heading h3 { font-size: 16px; font-weight: 600; } +#page-vulnerabilities .vulnerability-host-table { min-width: 880px; font-size: 13px; } +#page-vulnerabilities .vulnerability-host-table th { font-size: 12px; padding: 12px; } +#page-vulnerabilities .vulnerability-host-table td { padding: 16px 12px; } +#page-vulnerabilities .vulnerability-table-item:hover { background: color-mix(in srgb,var(--accent-color) 3%,var(--vuln-panel)); } +#page-vulnerabilities .vulnerability-row-toggle { font-size: 14px; line-height: 1.5; padding: 0; } +#page-vulnerabilities .vulnerability-table-title p { margin-top: 6px; font-size: 12px; } +#page-vulnerabilities .vulnerability-table-target { font-size: 12px; } +#page-vulnerabilities .vulnerability-table-actions { gap: 6px 10px; } +#page-vulnerabilities .vulnerability-group { border-radius: 12px; background: var(--vuln-panel); } +#page-vulnerabilities .vulnerability-group > summary { padding: 16px; } +#page-vulnerabilities .vulnerability-group-cards { padding: 0 16px 16px; } +#page-vulnerabilities .vulnerability-card { box-shadow: none; padding: 16px; } +#page-vulnerabilities .vulnerability-title { font-size: 15px; } +#page-vulnerabilities .pagination-fixed { margin-top: 16px; border-radius: 10px; } + +.vulnerability-select-record { + width: 15px; + height: 15px; + accent-color: var(--accent-color); + margin-inline-end: 8px; + vertical-align: middle; + cursor: pointer; +} + +.vulnerability-select-record:disabled { opacity: 0.35; cursor: default; } +.vulnerability-case-badge { + display: inline-block; + margin-top: 6px; + padding: 2px 7px; + border: 1px solid var(--border-color); + border-radius: 5px; + font-size: 11px; + color: var(--text-secondary); +} +.vulnerability-case-split { justify-self: end; } + +#vulnerability-inspector { z-index: 1040; background: rgba(15,23,42,.25); } +#vulnerability-inspector .vulnerability-inspector-panel { + position: absolute; + inset-block: 0; + inset-inline-end: 0; + width: min(820px,95vw); + max-width: none; + max-height: none; + height: 100%; + margin: 0; + padding: 0; + border-radius: 16px 0 0 16px; + background: var(--bg-primary); + box-shadow: -12px 0 48px rgba(15,23,42,.16); + display: flex; + flex-direction: column; +} + +.vulnerability-inspector-header { + display: flex; + align-items: start; + justify-content: space-between; + gap: 20px; + padding: 24px 28px 20px; + border-bottom: 1px solid var(--border-color); +} +.vulnerability-inspector-header .modal-close { position: static; flex-shrink: 0; } +.vulnerability-inspector-eyebrow { color: var(--text-muted); font-size: 12px; } +.vulnerability-inspector-header h2 { font-size: 21px; line-height: 1.5; margin: 6px 0 0; overflow-wrap: anywhere; } +#vulnerability-inspector-body { padding: 20px 28px 32px; overflow-y: auto; flex: 1; } +.vulnerability-inspector-meta, +.vulnerability-inspector-actions { display: flex; align-items: center; flex-wrap: wrap; gap: 10px; margin-bottom: 18px; } +.vulnerability-inspector-meta { font-size: 12px; color: var(--text-secondary); } +.vulnerability-inspector-tabs { display: flex; gap: 24px; border-bottom: 1px solid var(--border-color); margin: 22px 0; } +.vulnerability-inspector-tabs button { border: 0; border-bottom: 2px solid transparent; padding: 10px 0; font: inherit; font-size: 14px; background: transparent; color: var(--text-secondary); cursor: pointer; } +.vulnerability-inspector-tabs button[aria-pressed="true"] { color: var(--accent-color); border-bottom-color: var(--accent-color); font-weight: 600; } +[data-inspector-panel][hidden] { display: none; } +[data-inspector-panel] h3 { margin: 24px 0 12px; font-size: 14px; } +.vulnerability-inspector-description { white-space: pre-wrap; line-height: 1.8; font-size: 14px; } +.vulnerability-target-list { list-style: none; padding: 0; margin: 0; border: 1px solid var(--border-color); border-radius: 10px; overflow: hidden; } +.vulnerability-target-list li { display: flex; flex-direction: column; gap: 5px; padding: 13px 16px; background: var(--bg-secondary); border-bottom: 1px solid var(--border-color); overflow-wrap: anywhere; } +.vulnerability-target-list li:last-child { border-bottom: 0; } +.vulnerability-target-list strong { font-size: 13px; } +.vulnerability-target-list code { font-size: 12px; color: var(--text-secondary); white-space: pre-wrap; } +.vulnerability-timeline { list-style: none; padding: 0 0 0 16px; border-inline-start: 1px solid var(--border-color); margin: 0; } +.vulnerability-timeline-event { position: relative; padding: 0 0 24px 12px; } +.vulnerability-timeline-event::before { content: ''; position: absolute; left: -21px; top: 5px; width: 8px; height: 8px; background: var(--accent-color); border-radius: 50%; } +.vulnerability-timeline-event > div { display: flex; justify-content: space-between; flex-wrap: wrap; gap: 8px; } +.vulnerability-timeline-event time { font-size: 11px; color: var(--text-muted); } +.vulnerability-timeline-event p { white-space: pre-wrap; overflow-wrap: anywhere; font-size: 13px; margin: 8px 0; } +.vulnerability-member-link { display: flex; justify-content: space-between; gap: 12px; width: 100%; padding: 12px; margin: 6px 0; background: var(--bg-secondary); color: var(--text-primary); border: 1px solid var(--border-color); border-radius: 8px; text-align: start; cursor: pointer; } +.vulnerability-member-link span:last-child { color: var(--text-secondary); flex-shrink: 0; } +#vulnerability-merge-modal { z-index: 1050; } +.vulnerability-merge-panel { max-width: 540px; background: var(--bg-primary); } +.vulnerability-merge-panel label { display: flex; flex-direction: column; gap: 8px; margin-top: 18px; font-size: 13px; } +.vulnerability-merge-panel label[hidden] { display: none; } +.vulnerability-merge-panel input,.vulnerability-merge-panel textarea { width: 100%; padding: 10px 12px; background: var(--bg-secondary); color: var(--text-primary); border: 1px solid var(--border-color); border-radius: 8px; font: inherit; } +#vulnerability-merge-description { color: var(--text-secondary); font-size: 13px; line-height: 1.7; } +#vulnerability-merge-error { color: var(--error-color); margin-top: 12px; font-size: 13px; } +#vulnerability-modal,#vulnerability-retest-modal { z-index: 1050; } + +@media (max-width: 1100px) { + #page-vulnerabilities .dashboard-stats { grid-template-columns: repeat(3,minmax(0,1fr)); } + #page-vulnerabilities .stat-card-total { grid-column: auto; } +} +@media (max-width: 900px) { + #page-vulnerabilities .vulnerability-host-browser { grid-template-columns: minmax(0,1fr); } +} +@media (max-width: 600px) { + #page-vulnerabilities > .page-header,#page-vulnerabilities .page-content { padding: 14px; } + #page-vulnerabilities .dashboard-stats { grid-template-columns: repeat(3,minmax(0,1fr)); gap: 8px; } + #page-vulnerabilities .stat-card { padding: 12px; min-height: 92px; } + #page-vulnerabilities .stat-value { font-size: 24px; } + #vulnerability-inspector .vulnerability-inspector-panel { width: 100%; border-radius: 0; } + .vulnerability-inspector-header { padding: 18px; } + #vulnerability-inspector-body { padding: 18px; } +} diff --git a/web/static/i18n/ar-SA.json b/web/static/i18n/ar-SA.json index 5039ea8d..9ef50189 100644 --- a/web/static/i18n/ar-SA.json +++ b/web/static/i18n/ar-SA.json @@ -2721,6 +2721,34 @@ "errorGeneric": "حدث خطأ ما. يُرجى المحاولة مرة أخرى." }, "vulnerabilityPage": { + "statReports": "تقارير الثغرات", + "history_retest_started": "تم إنشاء فرع إعادة الاختبار", + "retestSnapshot": "لقطة الأدلة عند إعادة الاختبار", + "viewCases": "ثغرات مستقلة", + "distinctCount": "{{count}} ثغرة مستقلة", + "workspaceSubtitle": "الأصول والتقارير والمعالجة", + "mergeSelected": "دمج المحدد", + "mergeCount": "دمج المحدد ({{count}})", + "splitCase": "فصل المجموعة", + "mergeReason": "السبب", + "mergeHint": "ربط {{count}} تقريراً كثغرة واحدة. تحقق من المشروع ونقاط الوصول والسبب الجذري ثم وضح سبب الدمج.", + "splitHint": "يعيد الفصل عرض التقارير بشكل مستقل مع الاحتفاظ بالسجل.", + "inspectorTitle": "مساحة عمل الثغرة", + "inspector_overview": "نظرة عامة", + "inspector_evidence": "الأدلة", + "inspector_history": "السجل", + "affectedTargets": "الأهداف المتأثرة", + "linkedAssets": "أصول مطابقة", + "mergedRecord": "مدمج", + "targetCount": "{{count}} هدفاً", + "selectRecord": "تحديد {{title}}", + "casePagination": "عرض {{start}}–{{end}} من {{total}} ثغرة مستقلة", + "history_retest": "نتيجة إعادة الاختبار", + "history_merge": "دمج التقارير", + "history_split": "فصل المجموعة", + "history_detach": "إزالة الارتباط", + "openRetestChat": "فتح محادثة الاختبار", + "noHistory": "لا يوجد سجل منظم بعد", "exportVisibleHosts": "تصدير النتائج المعروضة", "tableDownload": "تنزيل", "pageAllHosts": "جميع مضيفي هذه الصفحة", diff --git a/web/static/i18n/en-US.json b/web/static/i18n/en-US.json index a713df55..fc5c0155 100644 --- a/web/static/i18n/en-US.json +++ b/web/static/i18n/en-US.json @@ -2864,6 +2864,34 @@ "errorGeneric": "Something went wrong. Please try again." }, "vulnerabilityPage": { + "statReports": "Reported findings", + "history_retest_started": "Retest branch created", + "retestSnapshot": "Evidence snapshot at retest", + "viewCases": "Distinct findings", + "distinctCount": "{{count}} distinct findings", + "workspaceSubtitle": "Assets, reports and remediation", + "mergeSelected": "Merge selected", + "mergeCount": "Merge selected ({{count}})", + "splitCase": "Split finding group", + "mergeReason": "Reason", + "mergeHint": "Link {{count}} reports as one finding. Verify the project, affected endpoints and root cause, then explain the merge.", + "splitHint": "Splitting restores individual reports and retains the event history.", + "inspectorTitle": "Finding workspace", + "inspector_overview": "Overview", + "inspector_evidence": "Evidence", + "inspector_history": "History", + "affectedTargets": "Affected targets", + "linkedAssets": "Matching inventory assets", + "mergedRecord": "Merged", + "targetCount": "{{count}} targets", + "selectRecord": "Select {{title}}", + "casePagination": "Showing {{start}}–{{end}} of {{total}} distinct findings", + "history_retest": "Retest result", + "history_merge": "Reports merged", + "history_split": "Group split", + "history_detach": "Association removed", + "openRetestChat": "Open retest chat", + "noHistory": "No structured history yet", "exportVisibleHosts": "Export displayed findings", "tableDownload": "Download", "pageAllHosts": "All hosts on this page", diff --git a/web/static/i18n/ru-RU.json b/web/static/i18n/ru-RU.json index d5a907b7..f50dfa38 100644 --- a/web/static/i18n/ru-RU.json +++ b/web/static/i18n/ru-RU.json @@ -2877,6 +2877,34 @@ "errorGeneric": "Что-то пошло не так. Повторите попытку." }, "vulnerabilityPage": { + "statReports": "Отчёты об уязвимостях", + "history_retest_started": "Создана ветка проверки", + "retestSnapshot": "Снимок доказательств при проверке", + "viewCases": "Уникальные", + "distinctCount": "Уникальных уязвимостей: {{count}}", + "workspaceSubtitle": "Активы, отчёты и устранение", + "mergeSelected": "Объединить", + "mergeCount": "Объединить ({{count}})", + "splitCase": "Разделить группу", + "mergeReason": "Причина", + "mergeHint": "Объединить {{count}} отчётов в одну уязвимость. Проверьте проект, точки входа и первопричину, затем укажите причину.", + "splitHint": "После разделения отчёты отображаются отдельно. История сохраняется.", + "inspectorTitle": "Работа с уязвимостью", + "inspector_overview": "Обзор", + "inspector_evidence": "Доказательства", + "inspector_history": "История", + "affectedTargets": "Затронутые цели", + "linkedAssets": "Совпадения в активах", + "mergedRecord": "Объединено", + "targetCount": "Целей: {{count}}", + "selectRecord": "Выбрать {{title}}", + "casePagination": "Показано {{start}}–{{end}} из {{total}} уникальных уязвимостей", + "history_retest": "Результат проверки", + "history_merge": "Отчёты объединены", + "history_split": "Группа разделена", + "history_detach": "Связь удалена", + "openRetestChat": "Открыть чат проверки", + "noHistory": "Структурированной истории пока нет", "exportVisibleHosts": "Экспорт показанных записей", "tableDownload": "Скачать", "pageAllHosts": "Все хосты на странице", diff --git a/web/static/i18n/zh-CN.json b/web/static/i18n/zh-CN.json index 23077e88..5451746c 100644 --- a/web/static/i18n/zh-CN.json +++ b/web/static/i18n/zh-CN.json @@ -2852,6 +2852,34 @@ "errorGeneric": "操作失败,请稍后重试。" }, "vulnerabilityPage": { + "statReports": "上报记录", + "history_retest_started": "复测分支已创建", + "retestSnapshot": "复测时的证据快照", + "viewCases": "独立漏洞", + "distinctCount": "{{count}} 个独立漏洞", + "workspaceSubtitle": "资产、上报与处置进展", + "mergeSelected": "归并所选", + "mergeCount": "归并所选({{count}})", + "splitCase": "拆分归并组", + "mergeReason": "操作理由", + "mergeHint": "将所选 {{count}} 条上报关联为一个独立漏洞。请核对项目、受影响接口和根因,并填写归并理由。", + "splitHint": "拆分后,各条上报恢复独立展示,历史操作记录可以继续查阅。", + "inspectorTitle": "漏洞工作台", + "inspector_overview": "概览", + "inspector_evidence": "复现与证据", + "inspector_history": "处置历史", + "affectedTargets": "受影响目标", + "linkedAssets": "资产库匹配", + "mergedRecord": "已归并", + "targetCount": "{{count}} 个目标", + "selectRecord": "选择 {{title}}", + "casePagination": "显示 {{start}}–{{end}} / 共 {{total}} 个独立漏洞", + "history_retest": "复测结果", + "history_merge": "归并上报", + "history_split": "拆分归并组", + "history_detach": "解除关联", + "openRetestChat": "打开复测对话", + "noHistory": "暂无结构化处置记录", "exportVisibleHosts": "导出右侧列表", "tableDownload": "下载", "pageAllHosts": "本页全部域名", diff --git a/web/static/js/vulnerability-workspace.js b/web/static/js/vulnerability-workspace.js new file mode 100644 index 00000000..31c663da --- /dev/null +++ b/web/static/js/vulnerability-workspace.js @@ -0,0 +1,210 @@ +// Vulnerability selection, review and evidence workspace. +let vulnerabilityWorkspaceRows = new Map(); +let vulnerabilityWorkspaceSelected = new Set(); +let vulnerabilityMergeCaseID = ''; +let vulnerabilityMergeIDs = []; +let vulnerabilityMergeBusy = false; +let vulnerabilityInspectorID = ''; +let vulnerabilityInspectorRequest = 0; + +function setVulnerabilityWorkspaceRows(rows) { + vulnerabilityWorkspaceRows = new Map(rows.map(row => [row.id, row])); + vulnerabilityWorkspaceSelected = new Set(Array.from(vulnerabilityWorkspaceSelected).filter(id => + vulnerabilityWorkspaceRows.has(id) && !vulnerabilityWorkspaceRows.get(id).case_id)); + updateVulnerabilityWorkspaceSelection(); +} + +function vulnerabilitySelectionInput(vuln) { + return ``; +} + +function selectVulnerabilityRecord(id, checked) { + if (checked) vulnerabilityWorkspaceSelected.add(id); + else vulnerabilityWorkspaceSelected.delete(id); + updateVulnerabilityWorkspaceSelection(); +} + +function updateVulnerabilityWorkspaceSelection() { + const button = document.getElementById('vulnerability-merge-selected'); + if (!button) return; + const count = vulnerabilityWorkspaceSelected.size; + button.disabled = count < 2; + button.textContent = count + ? vulnT('vulnerabilityPage.mergeCount', {count}) + : vulnT('vulnerabilityPage.mergeSelected'); + document.querySelectorAll('[data-select-vulnerability]').forEach(input => { + input.checked = vulnerabilityWorkspaceSelected.has(input.dataset.selectVulnerability); + }); +} + +function openVulnerabilityMergeDialog(caseID = '') { + if (vulnerabilityMergeBusy) return; + vulnerabilityMergeCaseID = caseID; + vulnerabilityMergeIDs = Array.from(vulnerabilityWorkspaceSelected); + if (!caseID && vulnerabilityMergeIDs.length < 2) return; + const rows = vulnerabilityMergeIDs.map(id => vulnerabilityWorkspaceRows.get(id)); + document.getElementById('vulnerability-merge-title').textContent = + vulnT(caseID ? 'vulnerabilityPage.splitCase' : 'vulnerabilityPage.mergeSelected'); + document.getElementById('vulnerability-merge-description').textContent = + vulnT(caseID ? 'vulnerabilityPage.splitHint' : 'vulnerabilityPage.mergeHint', {count:rows.length}); + document.getElementById('vulnerability-merge-name-label').hidden = Boolean(caseID); + const name = document.getElementById('vulnerability-merge-name'); + name.required = !caseID; + name.value = rows[0]?.title || ''; + document.getElementById('vulnerability-merge-reason').value = ''; + document.getElementById('vulnerability-merge-error').textContent = ''; + openAppModal('vulnerability-merge-modal'); +} + +async function saveVulnerabilityMerge() { + if (vulnerabilityMergeBusy) return; + const title = document.getElementById('vulnerability-merge-name').value.trim(); + const reason = document.getElementById('vulnerability-merge-reason').value.trim(); + if (!reason || (!vulnerabilityMergeCaseID && !title)) return; + const button = document.getElementById('vulnerability-merge-save'); + vulnerabilityMergeBusy = true; + button.disabled = true; + try { + const url = vulnerabilityMergeCaseID + ? '/api/vulnerabilities/cases/' + encodeURIComponent(vulnerabilityMergeCaseID) + '/split' + : '/api/vulnerabilities/cases'; + const response = await apiFetch(url, { + method:'POST', headers:{'Content-Type':'application/json'}, + body:JSON.stringify({ids:vulnerabilityMergeIDs,title,reason}) + }); + const data = await response.json(); + if (!response.ok) throw new Error(data.error || vulnT('vulnerabilityPage.saveFailed')); + vulnerabilityWorkspaceSelected.clear(); + closeAppModal('vulnerability-merge-modal'); + closeAppModal('vulnerability-inspector'); + refreshVulnerabilities(); + } catch(error) { + document.getElementById('vulnerability-merge-error').textContent = error.message; + } finally { + vulnerabilityMergeBusy = false; + button.disabled = false; + } +} + +function switchVulnerabilityInspectorTab(tab) { + const root = document.getElementById('vulnerability-inspector-body'); + root.querySelectorAll('[data-inspector-tab]').forEach(button => { + button.setAttribute('aria-pressed', String(button.dataset.inspectorTab === tab)); + }); + root.querySelectorAll('[data-inspector-panel]').forEach(panel => { + panel.hidden = panel.dataset.inspectorPanel !== tab; + }); +} + +async function openVulnerabilityInspector(id) { + vulnerabilityInspectorID = id; + const request = ++vulnerabilityInspectorRequest; + const title = document.getElementById('vulnerability-inspector-title'); + const body = document.getElementById('vulnerability-inspector-body'); + title.textContent = vulnerabilityWorkspaceRows.get(id)?.title || vulnT('vulnerabilityPage.inspectorTitle'); + body.innerHTML = `
${escapeHtml(vulnT('vulnerabilityPage.loading'))}
`; + openAppModal('vulnerability-inspector'); + document.querySelector('#vulnerability-inspector .modal-close').focus(); + try { + const response = await apiFetch('/api/vulnerabilities/' + encodeURIComponent(id) + '/context'); + if (!response.ok) throw new Error(vulnT('vulnerabilityPage.fetchFailed')); + const context = await response.json(); + if (request !== vulnerabilityInspectorRequest) return; + const v = context.vulnerability; + title.textContent = v.title; + const jsID = escapeJsStringAttr(v.id); + const targets = (v.targets || []).map(target => ` +
  • ${escapeHtml(target.host)} + ${escapeHtml([target.scheme, target.port, target.path].filter(Boolean).join(' · ') || target.raw)} +
  • `).join(''); + const history = (context.history || []).map(event => ` +
  • +
    ${escapeHtml(vulnT('vulnerabilityPage.history_' + event.kind))} +
    + ${event.status ? `${escapeHtml(vulnStatusLabel(event.status))}` : ''} +

    ${escapeHtml(event.evidence || '')}

    + ${event.snapshot ? `
    ${escapeHtml(vulnT('vulnerabilityPage.retestSnapshot'))} + ${vulnNarrativeSection(vulnT('vulnerabilityPage.detailReproductionSteps'),event.snapshot.reproduction_steps)} + ${vulnNarrativeSection(vulnT('vulnerabilityPage.detailEvidence'),event.snapshot.evidence,{code:true})}
    ` : ''} + ${event.conversation_id ? `` : ''} +
  • `).join(''); + const members = (context.members || []).map(member => ` + `).join(''); + const assets = (context.assets || []).map(asset => + `
  • ${escapeHtml(asset.host)}${escapeHtml(asset.id)}${asset.port ? ' · ' + asset.port : ''}
  • `).join(''); + body.innerHTML = ` +
    + ${escapeHtml(vulnSeverityLabel(v.severity))} + ${buildVulnerabilityStatusPicker(v)} + ${escapeHtml(v.type || '')} + ${escapeHtml(new Date(v.created_at).toLocaleString(vulnDateLocale()))} +
    +
    + + + +
    +
    + ${['overview','evidence','history'].map(tab => ``).join('')} +
    +
    +

    ${escapeHtml(v.description || '')}

    + ${vulnDetailProjectField(v)} + ${vulnDetailField(vulnT('vulnerabilityPage.detailVulnId'),v.id,true)} + ${vulnDetailConversationField(v.conversation_id)} + ${v.task_id ? vulnDetailField(vulnT('vulnerabilityPage.detailTaskId'),v.task_id,true) : ''} + ${vulnNarrativeSection(vulnT('vulnerabilityPage.detailImpact'),v.impact)} + ${vulnNarrativeSection(vulnT('vulnerabilityPage.detailRecommendation'),v.recommendation)} +

    ${escapeHtml(vulnT('vulnerabilityPage.affectedTargets'))}

    + + ${assets ? `

    ${escapeHtml(vulnT('vulnerabilityPage.linkedAssets'))}

    ` : ''} + ${members ? `

    ${escapeHtml(v.case_title)}

    ${members} +
    ` : ''} + +
    + + `; + initVulnerabilityStatusPickers(body); + initVulnerabilityProjectBindSelects(body); + if (typeof rbacAfterDynamicRender === 'function') rbacAfterDynamicRender(body); + loadVulnerabilityRelatedFacts(v.id).catch(console.warn); + } catch(error) { + if (request === vulnerabilityInspectorRequest) body.innerHTML = `
    ${escapeHtml(error.message)}
    `; + } +} + +function refreshVulnerabilityInspector(id) { + if (vulnerabilityInspectorID === id && isAppModalOpen('vulnerability-inspector')) openVulnerabilityInspector(id); +} + +['vulnerability-inspector','vulnerability-merge-modal'].forEach(id => { + const dialog = document.getElementById(id); + if (!dialog) return; + dialog.addEventListener('keydown', event => { + if (event.key === 'Escape' && !vulnerabilityMergeBusy) { + closeAppModal(id); + event.stopPropagation(); + } + if (event.key !== 'Tab') return; + const controls = Array.from(dialog.querySelectorAll('button,input,textarea,select,[tabindex="0"]')) + .filter(el => !el.disabled && el.getClientRects().length); + const first = controls[0], last = controls[controls.length-1]; + if (event.shiftKey && document.activeElement === first) { event.preventDefault(); last?.focus(); } + else if (!event.shiftKey && document.activeElement === last) { event.preventDefault(); first?.focus(); } + }); +}); diff --git a/web/static/js/vulnerability.js b/web/static/js/vulnerability.js index afc7a5b5..d5f7cdcb 100644 --- a/web/static/js/vulnerability.js +++ b/web/static/js/vulnerability.js @@ -218,6 +218,7 @@ async function changeVulnerabilityStatus(vulnId, newStatus, pickerEl) { } updateVulnerabilityStatusPicker(pickerEl, newStatus); + if (typeof refreshVulnerabilityInspector === 'function') refreshVulnerabilityInspector(vulnId); loadVulnerabilityStats(); if (!vulnerabilityStatusMatchesFilter(newStatus)) { @@ -258,7 +259,7 @@ let vulnerabilityPagination = { total: 0, totalPages: 1 }; -const VULNERABILITY_VIEWS = ['host', 'task', 'none']; +const VULNERABILITY_VIEWS = ['host', 'task', 'case', 'none']; const savedVulnerabilityView = localStorage.getItem('vulnerabilityListView'); let vulnerabilityView = VULNERABILITY_VIEWS.includes(savedVulnerabilityView) ? savedVulnerabilityView : 'host'; let vulnerabilityListRequest = 0; @@ -1274,6 +1275,8 @@ function updateVulnerabilityStats(stats) { totalEl.textContent = String(total); totalEl.classList.toggle('is-zero', total === 0); } + const distinctEl = document.getElementById('vulnerability-distinct-count'); + if (distinctEl) distinctEl.textContent = vulnT('vulnerabilityPage.distinctCount', { count: stats.distinct ?? total }); VULN_STAT_SEVERITIES.forEach(function (sev) { const count = bySeverity[sev] || 0; @@ -1335,6 +1338,7 @@ async function loadVulnerabilities(page = null, options = {}) { const params = buildVulnerabilityFilterParams(); params.append('group_by', view); + params.append('summary', 'true'); if (vulnerabilitySort) params.append('sort', vulnerabilitySort); if (view === 'host' && vulnerabilityHostQuery) params.append('host_q', vulnerabilityHostQuery); params.append('page', vulnerabilityPagination.currentPage.toString()); @@ -1399,6 +1403,7 @@ async function loadVulnerabilities(page = null, options = {}) { function renderVulnerabilities(vulnerabilities, renderOptions) { const opts = renderOptions && typeof renderOptions === 'object' ? renderOptions : {}; const listContainer = document.getElementById('vulnerabilities-list'); + if (typeof setVulnerabilityWorkspaceRows === 'function') setVulnerabilityWorkspaceRows(vulnerabilities || []); if (opts.view === 'host') { renderVulnerabilityHostBrowser(Array.isArray(vulnerabilities) ? vulnerabilities : [], opts); return; @@ -1426,7 +1431,11 @@ function renderVulnerabilities(vulnerabilities, renderOptions) { window.applyTranslations(listContainer); } if (typeof rbacAfterDynamicRender === 'function') rbacAfterDynamicRender(listContainer); - restoreExpandedVulnerabilityDetails(expandedIds); + if (exactMatch && vulnerabilities[0].summary_only && typeof openVulnerabilityInspector === 'function') { + openVulnerabilityInspector(exactMatch); + } else { + restoreExpandedVulnerabilityDetails(expandedIds); + } listContainer.querySelectorAll('.vulnerability-group').forEach(group => { group.addEventListener('toggle', updateVulnerabilityGroupControls); }); @@ -1453,12 +1462,12 @@ function updateVulnerabilityGroupControls() { if (!list || !toolbar) return; const groups = Array.from(list.querySelectorAll('.vulnerability-group')); const count = vulnerabilityView === 'host' && list.querySelector('.vulnerability-host-browser') - ? vulnerabilityHostRows.length + ? new Set(vulnerabilityHostRows.map(vuln => vuln.id)).size : list.querySelectorAll('.vulnerability-card, .vulnerability-table-item').length; document.getElementById('vulnerability-page-summary').textContent = count ? vulnT('vulnerabilityPage.pageFindings', { count }) : ''; const controls = document.getElementById('vulnerability-group-controls'); - controls.hidden = vulnerabilityView !== 'task'; + controls.hidden = !['task','case'].includes(vulnerabilityView); document.getElementById('vulnerability-expand-groups').disabled = !groups.some(group => !group.open); document.getElementById('vulnerability-collapse-groups').disabled = !groups.some(group => group.open); } @@ -1474,6 +1483,9 @@ function renderVulnerabilityGroups(vulnerabilities, opts) { label = vuln.task_id ? vulnT('vulnerabilityPage.viewTaskGroup', { id: vuln.task_id }) : taskTag || vulnT('vulnerabilityPage.viewNoTask'); + } else if (opts.view === 'case') { + key = vuln.case_id ? 'case:' + vuln.case_id : 'row:' + vuln.id; + label = vuln.case_title || vuln.title; } if (!groups.has(key)) groups.set(key, { label, items: [] }); groups.get(key).items.push(vuln); @@ -1504,7 +1516,10 @@ function renderVulnerabilityGroups(vulnerabilities, opts) { ${escapeHtml(vulnT('vulnerabilityPage.groupPending', { count: pending }))} ${tags ? `${escapeHtml(tags)}` : ''} -
    ${items.map(renderVulnerabilityCard).join('')}
    +
    + ${opts.view === 'case' && items[0].case_id ? `` : ''} + ${items.map(renderVulnerabilityCard).join('')} +
    `; }).join(''); @@ -1527,7 +1542,7 @@ function renderVulnerabilityHostBrowser(vulnerabilities, opts) { ${renderVulnerabilityHostRiskDot(items)}${escapeHtml(label)}${count} `; const tree = Array.from(domains, ([domain, hosts]) => { - const count = Array.from(hosts.values()).reduce((sum, n) => sum + n, 0); + const count = new Set(vulnerabilities.filter(vuln => (vuln.target_domain || vuln.target_host || '') === domain).map(vuln => vuln.id)).size; if (hosts.size === 1 && hosts.has(domain)) { return button('host:' + domain, domain || vulnT('vulnerabilityPage.unknownHost'), count, vulnerabilities.filter(vuln => (vuln.target_host || '') === domain)); @@ -1548,7 +1563,7 @@ function renderVulnerabilityHostBrowser(vulnerabilities, opts) { aria-label="${escapeAttr(vulnT('vulnerabilityPage.hostSearch'))}" placeholder="${escapeAttr(vulnT('vulnerabilityPage.hostSearch'))}" value="${escapeAttr(vulnerabilityHostQuery)}"> @@ -1595,16 +1610,26 @@ function renderVulnerabilityHostBrowser(vulnerabilities, opts) { function getVisibleVulnerabilityHostItems() { const selection = vulnerabilityHostSelection; - return vulnerabilityHostRows.filter(vuln => !selection || + const items = vulnerabilityHostRows.filter(vuln => !selection || selection === 'host:' + (vuln.target_host || '') || selection === 'domain:' + (vuln.target_domain || vuln.target_host || '')); + return Array.from(new Map(items.map(vuln => [vuln.id,vuln])).values()); } -function exportVisibleVulnerabilityHosts() { +async function exportVisibleVulnerabilityHosts() { const items = getVisibleVulnerabilityHostItems(); if (!items.length) return; - const content = items.map(formatVulnerabilityAsMarkdown).join('\n\n---\n\n'); - triggerTextDownload('vulnerabilities-hosts-' + new Date().toISOString().slice(0, 10) + '.md', content); + try { + const full = []; + for (const item of items) { + if (!item.summary_only) { full.push(item); continue; } + const response = await apiFetch('/api/vulnerabilities/' + encodeURIComponent(item.id)); + if (!response.ok) throw new Error(vulnT('vulnerabilityPage.exportFailed')); + full.push(await response.json()); + } + const content = full.map(formatVulnerabilityAsMarkdown).join('\n\n---\n\n'); + triggerTextDownload('vulnerabilities-hosts-' + new Date().toISOString().slice(0, 10) + '.md', content); + } catch(error) { alert(error.message); } } function renderVulnerabilityHostRiskDot(items) { @@ -1646,7 +1671,8 @@ function renderVulnerabilityHostTable(expandedIds) { initVulnerabilityProjectBindSelects(container); if (typeof rbacAfterDynamicRender === 'function') rbacAfterDynamicRender(container); const exact = items.find(vuln => vulnerabilityFilters.id === vuln.id); - restoreExpandedVulnerabilityDetails(exact ? [exact.id] : expandedIds); + if (exact?.summary_only && typeof openVulnerabilityInspector === 'function') openVulnerabilityInspector(exact.id); + else restoreExpandedVulnerabilityDetails(exact ? [exact.id] : expandedIds); updateVulnerabilityGroupControls(); } @@ -1654,19 +1680,25 @@ function renderVulnerabilityTableItem(vuln) { const id = escapeAttr(vuln.id); const jsID = escapeJsStringAttr(vuln.id); const task = vuln.task_tag || vuln.task_id || vulnT('vulnerabilityPage.viewNoTask'); + const targetHosts = Array.from(new Map((vuln.targets || []).map(target => [target.host,target])).values()); const created = new Date(vuln.created_at); return ` - ${escapeHtml(vulnSeverityLabel(vuln.severity))} + ${typeof vulnerabilitySelectionInput === 'function' ? vulnerabilitySelectionInput(vuln) : ''}${escapeHtml(vulnSeverityLabel(vuln.severity))}

    ${escapeHtml((vuln.description || '').slice(0, 160))}

    + ${vuln.case_id ? `${escapeHtml(vulnT('vulnerabilityPage.mergedRecord'))}` : ''} + + ${targetHosts.length ? targetHosts.slice(0,2).map(target => + `${escapeHtml(target.host)}`).join('') + : `${escapeHtml(vuln.target_host || vuln.target || '—')}`} + ${(vuln.targets || []).length > 1 ? `${escapeHtml(vulnT('vulnerabilityPage.targetCount', {count:vuln.targets.length}))}` : ''} - ${escapeHtml(vuln.target_host || vuln.target || '—')} ${buildVulnerabilityStatusPicker(vuln)} ${escapeHtml(task)} ${escapeHtml(created.toLocaleString(vulnDateLocale(), { @@ -1679,7 +1711,7 @@ function renderVulnerabilityTableItem(vuln) { - ${renderVulnerabilityDetailsContent(vuln)} + ${vuln.summary_only ? '' : `${renderVulnerabilityDetailsContent(vuln)}`} `; } @@ -1700,13 +1732,14 @@ function renderVulnerabilityCard(vuln) { return `
    -
    +

    ${escapeHtml(vuln.title)}

    + ${typeof vulnerabilitySelectionInput === 'function' ? vulnerabilitySelectionInput(vuln) : ''}
    ${severityText} @@ -1737,7 +1770,7 @@ function renderVulnerabilityCard(vuln) {
    - ${renderVulnerabilityDetailsContent(vuln)} + ${vuln.summary_only ? '' : renderVulnerabilityDetailsContent(vuln)}
    `; } @@ -1782,6 +1815,7 @@ function renderVulnerabilityPagination() { const paginationLabel = { host: 'vulnerabilityPage.hostPagination', task: 'vulnerabilityPage.taskPagination', + case: 'vulnerabilityPage.casePagination', none: 'vulnerabilityPage.recordPagination' }[vulnerabilityView]; @@ -2036,6 +2070,7 @@ async function saveVulnerability() { } const updated = await response.json(); + if (typeof refreshVulnerabilityInspector === 'function') refreshVulnerabilityInspector(currentVulnerabilityId); const editedId = currentVulnerabilityId; const isEdit = !!editedId; const expandedIds = isEdit ? getExpandedVulnerabilityIds() : []; @@ -2714,6 +2749,7 @@ async function bindVulnerabilityProject(vulnId, projectId, silent) { const err = await response.json().catch(() => ({})); throw new Error(err.error || vulnT('vulnerabilityPage.projectBindFailed')); } + if (typeof refreshVulnerabilityInspector === 'function') refreshVulnerabilityInspector(vulnId); if (!silent) { alert(vulnT('vulnerabilityPage.projectBindOk')); } diff --git a/web/templates/index.html b/web/templates/index.html index b0f91666..f93d1120 100644 --- a/web/templates/index.html +++ b/web/templates/index.html @@ -48,6 +48,7 @@ + @@ -2701,6 +2702,7 @@ aria-label="漏洞视图" data-i18n="vulnerabilityPage.viewLabel" data-i18n-attr="aria-label"> +
    @@ -2714,10 +2716,14 @@
    +
    + 资产、上报与处置进展 + +
    -
    总漏洞数
    +
    上报记录
    -