diff --git a/.github/workflows/deep-assessments.yml b/.github/workflows/deep-assessments.yml index 2d488451..ec31d093 100644 --- a/.github/workflows/deep-assessments.yml +++ b/.github/workflows/deep-assessments.yml @@ -1,9 +1,9 @@ name: Deep assessments on: push: - paths: ['internal/deepassessment/**', 'internal/handler/deep_assessment*', 'internal/multiagent/**', 'internal/agentruntime/**', 'runtime/pi/**', 'web/static/js/deep-assessments.js', 'web/static/js/deep-assessment-graph.js', 'web/static/css/deep-assessments.css', 'web/templates/index.html', 'scripts/deep-assessments-browser.test.cjs', '.github/workflows/deep-assessments.yml'] + paths: ['internal/deepassessment/**', 'internal/database/vulnerability*', 'internal/handler/vulnerability*', 'internal/handler/deep_assessment*', 'internal/multiagent/**', 'internal/agentruntime/**', 'runtime/pi/**', 'web/static/js/deep-assessments.js', 'web/static/js/deep-assessment-graph.js', 'web/static/js/assessment-finding-links.js', 'web/static/js/vulnerability*.js', 'web/static/css/deep-assessments.css', 'web/templates/index.html', 'scripts/deep-assessments-browser.test.cjs', 'scripts/assessment-findings-browser.test.cjs', '.github/workflows/deep-assessments.yml'] pull_request: - paths: ['internal/deepassessment/**', 'internal/handler/deep_assessment*', 'internal/multiagent/**', 'internal/agentruntime/**', 'runtime/pi/**', 'web/static/js/deep-assessments.js', 'web/static/js/deep-assessment-graph.js', 'web/static/css/deep-assessments.css', 'web/templates/index.html', 'scripts/deep-assessments-browser.test.cjs', '.github/workflows/deep-assessments.yml'] + paths: ['internal/deepassessment/**', 'internal/database/vulnerability*', 'internal/handler/vulnerability*', 'internal/handler/deep_assessment*', 'internal/multiagent/**', 'internal/agentruntime/**', 'runtime/pi/**', 'web/static/js/deep-assessments.js', 'web/static/js/deep-assessment-graph.js', 'web/static/js/assessment-finding-links.js', 'web/static/js/vulnerability*.js', 'web/static/css/deep-assessments.css', 'web/templates/index.html', 'scripts/deep-assessments-browser.test.cjs', 'scripts/assessment-findings-browser.test.cjs', '.github/workflows/deep-assessments.yml'] permissions: contents: read jobs: @@ -27,4 +27,4 @@ jobs: npm install --prefix "$RUNNER_TEMP/assessment-ui-deps" --no-save --ignore-scripts --package-lock=false playwright@1.65.0 "$RUNNER_TEMP/assessment-ui-deps/node_modules/.bin/playwright" install --with-deps chromium - name: Independent assessment and unchanged batch UI - run: NODE_PATH="$RUNNER_TEMP/assessment-ui-deps/node_modules" node --test scripts/deep-assessments-browser.test.cjs scripts/batch-tasks-browser.test.cjs + run: NODE_PATH="$RUNNER_TEMP/assessment-ui-deps/node_modules" node --test scripts/deep-assessments-browser.test.cjs scripts/assessment-findings-browser.test.cjs scripts/batch-tasks-browser.test.cjs diff --git a/CHANGELOG.md b/CHANGELOG.md index 3e0b6a55..15591333 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,11 @@ # Changelog +## 2026-11-14 · 深度测评漏洞关联 + +- 已登记漏洞自动绑定来源测评与步骤,漏洞管理按测评名称分组,支持测评名称搜索及测评 ID 筛选;批量任务的 ID、队列和分组语义保持不变。 +- 测评详情新增关联漏洞入口;漏洞详情可跳回具体步骤及复现证据,支持跨分页和刷新定位。 +- 补建已有记录的可信来源关联,分别校验漏洞与测评权限;删除测评后保留漏洞及来源快照。 + ## 2026-11-14 · 持续探索与图记忆 - 深度测评取消任务时间、累计 Token、规划轮数、总步骤及累计分段次数上限;保留用量统计和手动暂停/停止。旧预算耗尽记录迁移为暂停,可直接继续。 diff --git a/docs/zh-CN/deep-assessments.md b/docs/zh-CN/deep-assessments.md index b6ed5127..52be4733 100644 --- a/docs/zh-CN/deep-assessments.md +++ b/docs/zh-CN/deep-assessments.md @@ -45,6 +45,18 @@ Agent 可调用: - `assessment_checkpoint`:保存当前观察,同时保留 Pi 原生自定义条目。 - `assessment_result`:提交 completed、blocked 或 continue;完成需引用本任务真实成功调用的回执。 +## 漏洞管理关联 + +执行过程中通过 `record_vulnerability` 成功登记的漏洞,按实际执行会话自动关联测评 ID、测评名称、步骤 ID 和步骤标题。只写在检查点或摘要中的观察不会自动生成漏洞。工具和权限沿用当前角色配置。 + +- **测评 → 漏洞**:在详情抽屉的「关联漏洞」中查看本次测评已登记的漏洞,打开漏洞管理详情,或在测评中查看其复现步骤、证据和来源步骤回执。 +- **漏洞 → 测评**:漏洞详情显示来源测评和步骤,提供「返回测评步骤」「查看步骤与复现证据」入口。链接会定位具体步骤,不受步骤清单当前分页影响。 +- **按任务分组**:漏洞管理的任务视图以测评名称展示,内部以测评 ID 分组;同名测评及相同 ID 的批量任务不会混组。任务名称搜索同时支持测评名称,原 `task_id` 参数仍保留批量任务语义;测评可用 `assessment_id` 筛选。 + +升级会按已有的可信执行会话补建历史关联,不按标题或标签猜测。关联快照随漏洞保存;删除测评或执行会话后,漏洞及其复现内容仍保留,已删除的测评不提供返回入口。 + +读取测评和读取漏洞分别检查权限。仅分享测评不会自动分享所有漏洞;仅分享漏洞也不会授予来源测评的访问或执行权限。 + ## Pi 与宿主的分工 Pi `SessionManager` 管理会话上下文、原生压缩、工具搜索、Skills、重试和生命周期。固定目标与步骤职责随每段执行保留,最新图态势作为有界自定义消息提供,更多历史通过图工具按需读取。结构化工具桥保留参数/输出 schema、结构化结果、annotations、namespace 和暴露策略,权限与实际执行仍由 Go 宿主处理。 @@ -63,7 +75,7 @@ Pi `SessionManager` 管理会话上下文、原生压缩、工具搜索、Skills 当前调度面向单服务进程。允许范围文字会传给规划与执行,实际工具权限继承角色、平台权限、HITL 和调用拦截;范围文字本身不是网络隔离沙箱。 -新数据包括 `deep_assessments`、`deep_assessment_events`、`deep_assessment_calls`、`deep_assessment_nodes`、`deep_assessment_edges` 和 `deep_assessment_sessions`。已有深度测评记录会补建图与会话索引,不恢复已撤回旧模块的 `assessments`/`long_tasks` 历史任务。删除测评按外键清理这些业务记录,执行会话仍按原有会话保留策略处理。 +新数据包括 `deep_assessments`、`deep_assessment_events`、`deep_assessment_calls`、`deep_assessment_nodes`、`deep_assessment_edges`、`deep_assessment_sessions` 和 `vulnerability_assessment_sources`。已有深度测评记录会补建图与会话索引,不恢复已撤回旧模块的 `assessments`/`long_tasks` 历史任务。删除测评会清理其任务、图和调度记录;漏洞来源快照随漏洞保留,执行会话仍按原有会话保留策略处理。 ## API 与权限 @@ -78,6 +90,9 @@ Pi `SessionManager` 管理会话上下文、原生压缩、工具搜索、Skills | `POST /api/deep-assessments/:id/control/:action` | start、pause、cancel、guidance、answer、retry | | `GET /api/deep-assessments/:id/graph?scope=&limit=80&offset=0` | 折叠图或展开指定节点 | | `GET /api/deep-assessments/:id/graph/node?node_id=…&offset=0` | 节点原文 | +| `GET /api/deep-assessments/:id/vulnerabilities?limit=20&offset=0` | 当前账号可读的关联漏洞 | +| `GET /api/deep-assessments/:id/vulnerabilities/:vulnerabilityId` | 属于该测评的漏洞详情和来源步骤 | +| `GET /api/deep-assessments/:id/steps/:stepId` | 单个步骤,用于跨分页定位 | | `GET /api/deep-assessments/:id/events?after=0` | 增量事件 | | `GET /api/deep-assessments/:id/receipts?offset=0` | 工具回执 | | `GET /api/deep-assessments/:id/report` | 包含当前状态及缺口的阶段报告 | diff --git a/internal/app/app.go b/internal/app/app.go index 7085db9f..448f35bf 100644 --- a/internal/app/app.go +++ b/internal/app/app.go @@ -1117,6 +1117,9 @@ func setupRoutes( protected.GET("/deep-assessments/:id", agentHandler.GetDeepAssessment) protected.GET("/deep-assessments/:id/graph", agentHandler.DeepAssessmentGraph) protected.GET("/deep-assessments/:id/graph/node", agentHandler.DeepAssessmentNode) + protected.GET("/deep-assessments/:id/vulnerabilities", agentHandler.DeepAssessmentFindings) + protected.GET("/deep-assessments/:id/vulnerabilities/:vulnerabilityId", agentHandler.DeepAssessmentFinding) + protected.GET("/deep-assessments/:id/steps/:stepId", agentHandler.DeepAssessmentStep) protected.GET("/deep-assessments/:id/events", agentHandler.DeepAssessmentEvents) protected.GET("/deep-assessments/:id/receipts", agentHandler.DeepAssessmentReceipts) protected.GET("/deep-assessments/:id/report", agentHandler.DeepAssessmentReport) diff --git a/internal/database/database.go b/internal/database/database.go index 7430bcb3..033aaae0 100644 --- a/internal/database/database.go +++ b/internal/database/database.go @@ -215,6 +215,9 @@ func (db *DB) initTables() error { if err := db.backfillVulnerabilityTargets(); err != nil { return fmt.Errorf("回填漏洞目标失败: %w", err) } + if err := db.backfillAssessmentVulnerabilitySources(); err != nil { + return fmt.Errorf("backfill assessment finding sources: %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 87020e7e..a14f93c0 100644 --- a/internal/database/schemas/application.sql +++ b/internal/database/schemas/application.sql @@ -942,3 +942,14 @@ CREATE TABLE IF NOT EXISTS deep_assessment_sessions ( PRIMARY KEY(task_id,step_id,conversation_id) ); CREATE INDEX IF NOT EXISTS idx_deep_assessment_sessions_conversation ON deep_assessment_sessions(conversation_id,task_id); + +-- Source snapshots survive deletion of an assessment or its execution conversation. +CREATE TABLE IF NOT EXISTS vulnerability_assessment_sources ( + vulnerability_id TEXT PRIMARY KEY REFERENCES vulnerabilities(id) ON DELETE CASCADE, + assessment_id TEXT NOT NULL, + assessment_name TEXT NOT NULL, + step_id TEXT NOT NULL, + step_title TEXT NOT NULL, + conversation_id TEXT NOT NULL +); +CREATE INDEX IF NOT EXISTS idx_vulnerability_assessment_sources_task ON vulnerability_assessment_sources(assessment_id,step_id); diff --git a/internal/database/vulnerability.go b/internal/database/vulnerability.go index 45cdee27..2285582e 100644 --- a/internal/database/vulnerability.go +++ b/internal/database/vulnerability.go @@ -17,19 +17,21 @@ import ( // VulnerabilityListFilter 列表/统计/导出共用的筛选条件 type VulnerabilityListFilter struct { - ID string - Search string // 关键词模糊匹配(标题、描述、类型、目标等) - HostQuery string - TaskQuery string - CaseID string - SummaryOnly bool - ConversationID string - ProjectID string - Severity string - Status string - TaskID string - ConversationTag string - TaskTag string + AssessmentID string + AssessmentStepID string + ID string + Search string // 关键词模糊匹配(标题、描述、类型、目标等) + HostQuery string + TaskQuery string + CaseID string + SummaryOnly bool + ConversationID string + ProjectID string + Severity string + Status string + TaskID string + ConversationTag string + TaskTag string } type RBACListAccess struct { @@ -57,9 +59,9 @@ func (f VulnerabilityListFilter) appendWhere(query string, args []interface{}) ( query += ` AND (COALESCE(task_tag,'') LIKE ? ESCAPE '\' OR EXISTS ( SELECT 1 FROM batch_tasks bt LEFT JOIN batch_task_queues bq ON bq.id=bt.queue_id WHERE bt.conversation_id=vulnerabilities.conversation_id - AND (bt.id LIKE ? ESCAPE '\' OR bt.queue_id LIKE ? ESCAPE '\' OR COALESCE(bq.title,'') LIKE ? ESCAPE '\')))` + AND (bt.id LIKE ? ESCAPE '\' OR bt.queue_id LIKE ? ESCAPE '\' OR COALESCE(bq.title,'') LIKE ? ESCAPE '\')) OR EXISTS(SELECT 1 FROM vulnerability_assessment_sources src LEFT JOIN deep_assessments d ON d.id=src.assessment_id WHERE src.vulnerability_id=vulnerabilities.id AND (COALESCE(d.name,src.assessment_name) LIKE ? ESCAPE '\' OR src.assessment_id LIKE ? ESCAPE '\')))` pattern := escapeVulnerabilityLikePattern(q) - args = append(args, pattern, pattern, pattern, pattern) + args = append(args, pattern, pattern, pattern, pattern, pattern, pattern) } if f.ID != "" { query += " AND vulnerabilities.id = ?" @@ -73,6 +75,14 @@ func (f VulnerabilityListFilter) appendWhere(query string, args []interface{}) ( query += " AND project_id = ?" args = append(args, f.ProjectID) } + if f.AssessmentID != "" { + query += ` AND EXISTS(SELECT 1 FROM vulnerability_assessment_sources src WHERE src.vulnerability_id=vulnerabilities.id AND src.assessment_id=?)` + args = append(args, f.AssessmentID) + } + if f.AssessmentStepID != "" { + query += ` AND EXISTS(SELECT 1 FROM vulnerability_assessment_sources src WHERE src.vulnerability_id=vulnerabilities.id AND src.step_id=?)` + args = append(args, f.AssessmentStepID) + } if f.TaskID != "" { query += " AND EXISTS (SELECT 1 FROM batch_tasks bt WHERE bt.conversation_id = vulnerabilities.conversation_id AND (bt.id = ? OR bt.queue_id = ?))" args = append(args, f.TaskID, f.TaskID) @@ -155,35 +165,41 @@ 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"` - TaskQueueTitle string `json:"task_queue_title,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"` + AssessmentID string `json:"assessment_id,omitempty"` + AssessmentName string `json:"assessment_name,omitempty"` + AssessmentStepID string `json:"assessment_step_id,omitempty"` + AssessmentStepTitle string `json:"assessment_step_title,omitempty"` + AssessmentDeleted bool `json:"assessment_deleted,omitempty"` + AssessmentCanOpen bool `json:"assessment_can_open,omitempty"` + 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"` + TaskQueueTitle string `json:"task_queue_title,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 创建漏洞 @@ -214,7 +230,12 @@ func (db *DB) CreateVulnerability(vuln *Vulnerability) (*Vulnerability, error) { ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ` - _, err := db.Exec( + tx, err := db.Begin() + if err != nil { + return nil, err + } + defer tx.Rollback() + _, err = tx.Exec( query, vuln.ID, nullIfEmpty(vuln.ConversationID), nullIfEmpty(vuln.ProjectID), vuln.ConversationTag, vuln.TaskTag, vuln.Title, vuln.Description, vuln.Severity, vuln.Status, vuln.Type, vuln.Target, @@ -224,6 +245,12 @@ func (db *DB) CreateVulnerability(vuln *Vulnerability) (*Vulnerability, error) { if err != nil { return nil, fmt.Errorf("创建漏洞失败: %w", err) } + if err = linkAssessmentVulnerability(tx, vuln.ID); err != nil { + return nil, fmt.Errorf("link assessment finding: %w", err) + } + if err = tx.Commit(); err != nil { + return nil, err + } db.refreshAssetRiskCacheForConversationsBestEffort(vuln.ConversationID) return db.GetVulnerability(vuln.ID) } @@ -240,7 +267,7 @@ func (db *DB) GetVulnerability(id string) (*Vulnerability, error) { 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, targets_json, COALESCE(case_id,''), - COALESCE((SELECT title FROM vulnerability_cases vc WHERE vc.id=vulnerabilities.case_id),'') + COALESCE((SELECT title FROM vulnerability_cases vc WHERE vc.id=vulnerabilities.case_id),''), ` + vulnerabilityAssessmentColumns + ` FROM vulnerabilities WHERE id = ? ` @@ -251,6 +278,7 @@ func (db *DB) GetVulnerability(id string) (*Vulnerability, error) { &vuln.Preconditions, &vuln.ReproSteps, &vuln.Evidence, &vuln.Impact, &vuln.Recommendation, &vuln.RetestNotes, &vuln.RetestLog, &vuln.TaskID, &vuln.TaskQueueID, &vuln.CreatedAt, &vuln.UpdatedAt, &targets, &vuln.CaseID, &vuln.CaseTitle, + &vuln.AssessmentID, &vuln.AssessmentName, &vuln.AssessmentStepID, &vuln.AssessmentStepTitle, &vuln.AssessmentDeleted, ) if err != nil { if err == sql.ErrNoRows { @@ -338,6 +366,7 @@ func vulnerabilityGroupQuery(filter VulnerabilityListFilter, access RBACListAcce case "task": key = `CASE WHEN ` + vulnerabilityTaskIDExpr + ` <> '' THEN 'id:' || ` + vulnerabilityTaskIDExpr + ` + WHEN ` + vulnerabilityAssessmentIDExpr + ` <> '' THEN 'assessment:' || ` + vulnerabilityAssessmentIDExpr + ` WHEN TRIM(task_tag) <> '' THEN 'tag:' || TRIM(task_tag) ELSE '' END` default: @@ -414,7 +443,7 @@ func (db *DB) ListVulnerabilitiesByGroupForAccess(limit, offset int, filter Vuln 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, COALESCE((SELECT bq.title FROM batch_tasks bt JOIN batch_task_queues bq ON bq.id=bt.queue_id WHERE bt.conversation_id=vulnerabilities.conversation_id ORDER BY bt.id LIMIT 1),''), 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),'') + COALESCE((SELECT title FROM vulnerability_cases vc WHERE vc.id=vulnerabilities.case_id),''), ` + vulnerabilityAssessmentColumns + ` FROM vulnerabilities` + join + ` WHERE 1=1 ` @@ -444,6 +473,7 @@ func (db *DB) ListVulnerabilitiesByGroupForAccess(limit, offset int, filter Vuln &vuln.Preconditions, &vuln.ReproSteps, &vuln.Evidence, &vuln.Impact, &vuln.Recommendation, &vuln.RetestNotes, &vuln.RetestLog, &vuln.TaskID, &vuln.TaskQueueID, &vuln.TaskQueueTitle, &vuln.CreatedAt, &vuln.UpdatedAt, &vuln.TargetHost, &targets, &vuln.CaseID, &vuln.CaseTitle, + &vuln.AssessmentID, &vuln.AssessmentName, &vuln.AssessmentStepID, &vuln.AssessmentStepTitle, &vuln.AssessmentDeleted, ) if err != nil { db.logger.Warn("扫描漏洞记录失败", zap.Error(err)) @@ -728,6 +758,10 @@ func (db *DB) GetVulnerabilityFilterOptionsForAccess(access RBACListAccess) (map if err != nil { return nil, fmt.Errorf("查询队列ID建议失败: %w", err) } + assessmentIDs, err := collect(`SELECT DISTINCT `+vulnerabilityAssessmentIDExpr+` FROM vulnerabilities `+where+` ORDER BY created_at DESC LIMIT 500`, accessArgs...) + if err != nil { + return nil, fmt.Errorf("query assessment suggestions: %w", err) + } conversationTags, err := collect(`SELECT DISTINCT conversation_tag FROM vulnerabilities `+where+` AND conversation_tag IS NOT NULL AND conversation_tag <> '' ORDER BY conversation_tag LIMIT 500`, accessArgs...) if err != nil { return nil, fmt.Errorf("查询对话标签建议失败: %w", err) @@ -747,6 +781,7 @@ func (db *DB) GetVulnerabilityFilterOptionsForAccess(access RBACListAccess) (map "project_ids": projectIDs, "task_ids": taskIDs, "queue_ids": queueIDs, + "assessment_ids": assessmentIDs, "conversation_tags": conversationTags, "task_tags": taskTags, }, nil diff --git a/internal/database/vulnerability_assessment.go b/internal/database/vulnerability_assessment.go new file mode 100644 index 00000000..d76f1fbb --- /dev/null +++ b/internal/database/vulnerability_assessment.go @@ -0,0 +1,53 @@ +package database + +import "database/sql" + +// Origins are inferred from host-owned execution sessions, never supplied by an +// agent's report arguments or guessed from a title/tag. Ambiguous sessions and +// existing batch-task sessions retain their previous behavior. +const assessmentSourceSelect = `SELECT v.id,d.id,d.name,s.step_id, + COALESCE(NULLIF(COALESCE((SELECT n.title FROM deep_assessment_nodes n WHERE n.task_id=d.id AND n.id='step:'||s.step_id),(SELECT json_extract(st.value,'$.title') FROM json_each(CASE WHEN json_valid(d.payload) THEN d.payload ELSE '{}' END,'$.steps') st WHERE json_extract(st.value,'$.id')=s.step_id LIMIT 1)),''),s.step_id),v.conversation_id + FROM vulnerabilities v JOIN deep_assessment_sessions s ON s.conversation_id=v.conversation_id + JOIN deep_assessments d ON d.id=s.task_id + WHERE COALESCE(v.conversation_id,'')<>'' + AND NOT EXISTS(SELECT 1 FROM vulnerability_assessment_sources bound WHERE bound.vulnerability_id=v.id) + AND (SELECT COUNT(*) FROM deep_assessment_sessions all_s WHERE all_s.conversation_id=v.conversation_id)=1 + AND NOT EXISTS(SELECT 1 FROM batch_tasks bt WHERE bt.conversation_id=v.conversation_id)` + +func linkAssessmentVulnerability(tx *sql.Tx, id string) error { + _, err := tx.Exec(`INSERT OR IGNORE INTO vulnerability_assessment_sources(vulnerability_id,assessment_id,assessment_name,step_id,step_title,conversation_id) `+assessmentSourceSelect+` AND v.id=?`, id) + return err +} + +// Backfill both pre-graph execution attempts and existing findings on upgrade. +// This records provenance only; it never starts tasks or changes findings. +func (db *DB) backfillAssessmentVulnerabilitySources() error { + tx, err := db.Begin() + if err != nil { + return err + } + defer tx.Rollback() + for _, query := range []string{ + `INSERT OR IGNORE INTO deep_assessment_sessions(task_id,step_id,conversation_id) + SELECT d.id,json_extract(st.value,'$.id'),json_extract(st.value,'$.conversation_id') + FROM deep_assessments d,json_each(CASE WHEN json_valid(d.payload) THEN d.payload ELSE '{}' END,'$.steps') st + WHERE COALESCE(json_extract(st.value,'$.id'),'')<>'' AND COALESCE(json_extract(st.value,'$.conversation_id'),'')<>''`, + `INSERT OR IGNORE INTO deep_assessment_sessions(task_id,step_id,conversation_id) + SELECT d.id,json_extract(st.value,'$.id'),c.value + FROM deep_assessments d,json_each(CASE WHEN json_valid(d.payload) THEN d.payload ELSE '{}' END,'$.steps') st,json_each(st.value,'$.conversations') c + WHERE COALESCE(json_extract(st.value,'$.id'),'')<>'' AND c.type='text' AND c.value<>''`, + `INSERT OR IGNORE INTO vulnerability_assessment_sources(vulnerability_id,assessment_id,assessment_name,step_id,step_title,conversation_id) ` + assessmentSourceSelect, + } { + if _, err = tx.Exec(query); err != nil { + return err + } + } + return tx.Commit() +} + +const vulnerabilityAssessmentIDExpr = `COALESCE((SELECT src.assessment_id FROM vulnerability_assessment_sources src WHERE src.vulnerability_id=vulnerabilities.id),'')` +const vulnerabilityAssessmentNameExpr = `COALESCE((SELECT COALESCE(d.name,src.assessment_name) FROM vulnerability_assessment_sources src LEFT JOIN deep_assessments d ON d.id=src.assessment_id WHERE src.vulnerability_id=vulnerabilities.id),'')` +const vulnerabilityAssessmentColumns = vulnerabilityAssessmentIDExpr + `, ` + vulnerabilityAssessmentNameExpr + `, + COALESCE((SELECT src.step_id FROM vulnerability_assessment_sources src WHERE src.vulnerability_id=vulnerabilities.id),''), + COALESCE((SELECT src.step_title FROM vulnerability_assessment_sources src WHERE src.vulnerability_id=vulnerabilities.id),''), + EXISTS(SELECT 1 FROM vulnerability_assessment_sources src WHERE src.vulnerability_id=vulnerabilities.id AND NOT EXISTS(SELECT 1 FROM deep_assessments d WHERE d.id=src.assessment_id))` diff --git a/internal/database/vulnerability_assessment_test.go b/internal/database/vulnerability_assessment_test.go new file mode 100644 index 00000000..d3a3828e --- /dev/null +++ b/internal/database/vulnerability_assessment_test.go @@ -0,0 +1,125 @@ +package database + +import ( + "encoding/json" + "testing" + "time" +) + +func assessmentSourceFixture(t *testing.T, db *DB, id, name, owner string, convs ...string) { + t.Helper() + steps := []map[string]any{} + for i, conv := range convs { + steps = append(steps, map[string]any{"id": []string{"one", "two", "three"}[i], "title": "Step " + conv, "conversation_id": conv, "conversations": []string{conv}, "status": "completed"}) + } + payload, _ := json.Marshal(map[string]any{"id": id, "owner_id": owner, "name": name, "status": "paused", "steps": steps}) + if _, err := db.Exec(`INSERT INTO deep_assessments(id,owner_user_id,project_id,name,status,payload,updated_at) VALUES(?,?,'',?,'paused',?,?)`, id, owner, name, string(payload), time.Now()); err != nil { + t.Fatal(err) + } + if err := db.backfillAssessmentVulnerabilitySources(); err != nil { + t.Fatal(err) + } +} +func TestAssessmentFindingsGroupByIdentityAndLeaveBatchTasksUnchanged(t *testing.T) { + db := newRBACTestDB(t) + first, _ := db.CreateConversation("first", ConversationCreateMeta{}) + second, _ := db.CreateConversation("second", ConversationCreateMeta{}) + batch, _ := db.CreateConversation("batch", ConversationCreateMeta{}) + other, _ := db.CreateConversation("other", ConversationCreateMeta{}) + assessmentSourceFixture(t, db, "same-id", "域名深度测评", "", first.ID, second.ID) + assessmentSourceFixture(t, db, "other-assessment", "域名深度测评", "", other.ID) + if err := db.CreateBatchQueue("queue", "Original batch queue", "", "single", "manual", "", nil, "", 1, []map[string]interface{}{{"id": "same-id", "message": "batch fixture"}}); err != nil { + t.Fatal(err) + } + if err := db.UpdateBatchTaskStatus("queue", "same-id", "completed", batch.ID, "", ""); err != nil { + t.Fatal(err) + } + for _, item := range []struct{ id, conv string }{{"a", first.ID}, {"b", second.ID}, {"batch", batch.ID}, {"other", other.ID}} { + if _, err := db.CreateVulnerability(&Vulnerability{ID: item.id, ConversationID: item.conv, Title: item.id, Severity: "high", ReproSteps: "reproduction", Evidence: "original evidence"}); err != nil { + t.Fatal(err) + } + } + v, err := db.GetVulnerability("a") + if err != nil || v.AssessmentID != "same-id" || v.AssessmentName != "域名深度测评" || v.AssessmentStepID != "one" || v.TaskID != "" { + t.Fatal(v, err) + } + v, _ = db.GetVulnerability("batch") + if v.TaskID != "same-id" || v.TaskQueueID != "queue" || v.AssessmentID != "" { + t.Fatal("batch association changed", v) + } + count, err := db.CountVulnerabilityGroupsForAccess(VulnerabilityListFilter{}, RBACListAccess{}, "task") + if err != nil || count != 3 { + t.Fatal(count, err) + } + for _, tc := range []struct { + filter VulnerabilityListFilter + want int + }{{VulnerabilityListFilter{AssessmentID: "same-id"}, 2}, {VulnerabilityListFilter{TaskID: "same-id"}, 1}, {VulnerabilityListFilter{TaskQuery: "域名深度"}, 3}, {VulnerabilityListFilter{TaskQuery: "Original batch"}, 1}, {VulnerabilityListFilter{AssessmentID: "same-id", AssessmentStepID: "two"}, 1}} { + count, err := db.CountVulnerabilitiesForAccess(tc.filter, RBACListAccess{}) + if err != nil || count != tc.want { + t.Fatal(tc.filter, count, err) + } + } + rows, err := db.ListVulnerabilitiesByGroupForAccess(1, 0, VulnerabilityListFilter{AssessmentID: "same-id"}, RBACListAccess{}, "task", "") + if err != nil || len(rows) != 2 { + t.Fatal(rows, err) + } + for _, v := range rows { + if v.AssessmentName != "域名深度测评" || v.AssessmentStepTitle == "" { + t.Fatal(v) + } + } +} +func TestAssessmentSourceBackfillAndDeletionKeepOriginalEvidence(t *testing.T) { + db := newRBACTestDB(t) + conv, _ := db.CreateConversation("old attempt", ConversationCreateMeta{}) + if _, err := db.CreateVulnerability(&Vulnerability{ID: "legacy", ConversationID: conv.ID, Title: "legacy finding", Severity: "high", Evidence: "original proof", ReproSteps: "original reproduction"}); err != nil { + t.Fatal(err) + } + // Model a pre-graph task whose finding belongs to an earlier attempt. + raw, _ := json.Marshal(map[string]any{"id": "legacy-task", "steps": []map[string]any{{"id": "original-step", "title": "Original step", "conversation_id": "later-attempt", "conversations": []string{conv.ID, "later-attempt"}}}}) + if _, err := db.Exec(`INSERT INTO deep_assessments(id,owner_user_id,project_id,name,status,payload,updated_at) VALUES('legacy-task','','','Legacy assessment','paused',?,?)`, string(raw), time.Now()); err != nil { + t.Fatal(err) + } + for i := 0; i < 2; i++ { + if err := db.backfillAssessmentVulnerabilitySources(); err != nil { + t.Fatal(err) + } + } + v, err := db.GetVulnerability("legacy") + if err != nil || v.AssessmentID != "legacy-task" || v.AssessmentStepID != "original-step" { + t.Fatal(v, err) + } + if _, err = db.Exec(`DELETE FROM deep_assessments WHERE id='legacy-task'`); err != nil { + t.Fatal(err) + } + if _, err = db.Exec(`DELETE FROM conversations WHERE id=?`, conv.ID); err != nil { + t.Fatal(err) + } + v, err = db.GetVulnerability("legacy") + if err != nil || !v.AssessmentDeleted || v.AssessmentName != "Legacy assessment" || v.Evidence != "original proof" || v.ReproSteps != "original reproduction" { + t.Fatal(v, err) + } +} +func TestAssessmentFindingLinkIsAtomicAndDoesNotGuessAmbiguousSessions(t *testing.T) { + db := newRBACTestDB(t) + conv, _ := db.CreateConversation("source", ConversationCreateMeta{}) + assessmentSourceFixture(t, db, "one", "one", "", conv.ID) + if _, err := db.Exec(`CREATE TRIGGER reject_assessment_source BEFORE INSERT ON vulnerability_assessment_sources BEGIN SELECT RAISE(FAIL,'fixture failure'); END`); err != nil { + t.Fatal(err) + } + if _, err := db.CreateVulnerability(&Vulnerability{ID: "failed", ConversationID: conv.ID, Title: "failed", Severity: "high"}); err == nil { + t.Fatal("source write failure ignored") + } + var n int + db.QueryRow(`SELECT COUNT(*) FROM vulnerabilities WHERE id='failed'`).Scan(&n) + if n != 0 { + t.Fatal("unlinked partial finding committed") + } + db.Exec(`DROP TRIGGER reject_assessment_source`) + assessmentSourceFixture(t, db, "two", "two", "", conv.ID) + v, err := db.CreateVulnerability(&Vulnerability{ConversationID: conv.ID, Title: "ambiguous", Severity: "high"}) + if err != nil || v.AssessmentID != "" { + t.Fatal("ambiguous source guessed", v, err) + } +} diff --git a/internal/handler/deep_assessment.go b/internal/handler/deep_assessment.go index 7cd2aeee..8b7dc4a7 100644 --- a/internal/handler/deep_assessment.go +++ b/internal/handler/deep_assessment.go @@ -43,7 +43,19 @@ func (h *AgentHandler) DeepAssessmentReceipts(c *gin.Context) { if offset < 0 { offset = 0 } - rows, err := h.db.Query(`SELECT id,step_id,tool,arguments,status,execution_id,result FROM deep_assessment_calls WHERE task_id=? ORDER BY updated_at DESC,id LIMIT 50 OFFSET ?`, c.Param("id"), offset) + stepID := c.Query("step_id") + if stepID != "" { + task, err := h.deepAssessments.Store.Get(c.Param("id")) + if err != nil { + deepAssessmentError(c, err) + return + } + if task.Step(stepID) == nil { + deepAssessmentError(c, sql.ErrNoRows) + return + } + } + rows, err := h.db.Query(`SELECT id,step_id,tool,arguments,status,execution_id,result FROM deep_assessment_calls WHERE task_id=? AND (?='' OR step_id=?) ORDER BY updated_at DESC,id LIMIT 50 OFFSET ?`, c.Param("id"), stepID, stepID, offset) if err != nil { deepAssessmentError(c, err) return diff --git a/internal/handler/deep_assessment_findings.go b/internal/handler/deep_assessment_findings.go new file mode 100644 index 00000000..fb1d61ef --- /dev/null +++ b/internal/handler/deep_assessment_findings.go @@ -0,0 +1,84 @@ +package handler + +import ( + "cyberstrike-ai/internal/database" + "cyberstrike-ai/internal/security" + "database/sql" + "github.com/gin-gonic/gin" + "strconv" +) + +func decorateAssessmentNavigation(db *database.DB, c *gin.Context, v *database.Vulnerability) { + if v == nil || v.AssessmentID == "" || v.AssessmentDeleted { + return + } + session, ok := security.CurrentSession(c) + v.AssessmentCanOpen = ok && security.SessionHasPermission(c, "assessments:read") && db.UserCanAccessResource(session.UserID, session.ScopeFor("assessments:read"), "deep_assessment", v.AssessmentID) +} +func (h *AgentHandler) DeepAssessmentFindings(c *gin.Context) { + if !security.SessionHasPermission(c, "vulnerability:read") { + c.JSON(403, gin.H{"error": "缺少漏洞读取权限"}) + return + } + if _, err := h.deepAssessments.Store.Get(c.Param("id")); err != nil { + deepAssessmentError(c, err) + return + } + limit, _ := strconv.Atoi(c.DefaultQuery("limit", "20")) + if limit < 1 || limit > 100 { + limit = 20 + } + offset, _ := strconv.Atoi(c.Query("offset")) + if offset < 0 { + offset = 0 + } + session, _ := security.CurrentSession(c) + access := database.RBACListAccess{UserID: session.UserID, Scope: session.ScopeFor("vulnerability:read")} + filter := database.VulnerabilityListFilter{AssessmentID: c.Param("id"), SummaryOnly: true} + total, err := h.db.CountVulnerabilitiesForAccess(filter, access) + if err != nil { + deepAssessmentError(c, err) + return + } + items, err := h.db.ListVulnerabilitiesByGroupForAccess(limit, offset, filter, access, "none", "latest") + if err != nil { + deepAssessmentError(c, err) + return + } + for _, v := range items { + decorateAssessmentNavigation(h.db, c, v) + } + c.JSON(200, gin.H{"vulnerabilities": items, "total": total, "next_offset": offset + len(items), "has_more": offset+len(items) < total}) +} +func (h *AgentHandler) DeepAssessmentFinding(c *gin.Context) { + session, ok := security.CurrentSession(c) + if !ok || !security.SessionHasPermission(c, "vulnerability:read") || !h.db.UserCanAccessResource(session.UserID, session.ScopeFor("vulnerability:read"), "vulnerability", c.Param("vulnerabilityId")) { + c.JSON(403, gin.H{"error": "无权读取该漏洞"}) + return + } + task, err := h.deepAssessments.Store.Get(c.Param("id")) + if err != nil { + deepAssessmentError(c, err) + return + } + v, err := h.db.GetVulnerability(c.Param("vulnerabilityId")) + if err != nil || v.AssessmentID != task.ID { + deepAssessmentError(c, sql.ErrNoRows) + return + } + decorateAssessmentNavigation(h.db, c, v) + c.JSON(200, gin.H{"vulnerability": v, "step": task.Step(v.AssessmentStepID)}) +} +func (h *AgentHandler) DeepAssessmentStep(c *gin.Context) { + task, err := h.deepAssessments.Store.Get(c.Param("id")) + if err != nil { + deepAssessmentError(c, err) + return + } + step := task.Step(c.Param("stepId")) + if step == nil { + deepAssessmentError(c, sql.ErrNoRows) + return + } + c.JSON(200, gin.H{"step": step}) +} diff --git a/internal/handler/deep_assessment_findings_test.go b/internal/handler/deep_assessment_findings_test.go new file mode 100644 index 00000000..107d9783 --- /dev/null +++ b/internal/handler/deep_assessment_findings_test.go @@ -0,0 +1,98 @@ +package handler + +import ( + "encoding/json" + "net/http/httptest" + "testing" + + "cyberstrike-ai/internal/database" + "cyberstrike-ai/internal/deepassessment" + "cyberstrike-ai/internal/security" + "github.com/gin-gonic/gin" + "go.uber.org/zap" +) + +func assessmentFindingRouter(h *AgentHandler, user string, permissions map[string]bool) *gin.Engine { + r := gin.New() + r.Use(func(c *gin.Context) { + c.Set(security.ContextSessionKey, security.Session{UserID: user, Scope: database.RBACScopeOwn, Permissions: permissions}) + }) + r.Use(security.RBACMiddleware(h.db)) + r.GET("/api/deep-assessments/:id/vulnerabilities", h.DeepAssessmentFindings) + r.GET("/api/deep-assessments/:id/vulnerabilities/:vulnerabilityId", h.DeepAssessmentFinding) + r.GET("/api/deep-assessments/:id/steps/:stepId", h.DeepAssessmentStep) + r.GET("/api/deep-assessments/:id/receipts", h.DeepAssessmentReceipts) + vh := NewVulnerabilityHandler(h.db, zap.NewNop()) + r.GET("/api/vulnerabilities/:id/context", vh.VulnerabilityContext) + return r +} +func TestDeepAssessmentFindingLinksRespectBothResourceScopes(t *testing.T) { + h, task := deepAssessmentFixture(t) + conv, _ := h.db.CreateConversation("step", database.ConversationCreateMeta{}) + h.db.SetResourceOwner("conversation", conv.ID, task.OwnerID) + if err := h.deepAssessments.Store.Change(task.ID, "", "checkpoint", "source", func(v *deepassessment.Task) error { + v.Steps = []deepassessment.Step{{ID: "one", Title: "Origin step", Status: "completed", ConversationID: conv.ID, Summary: "proof"}} + return nil + }); err != nil { + t.Fatal(err) + } + v, err := h.db.CreateVulnerability(&database.Vulnerability{ID: "finding", ConversationID: conv.ID, Title: "Finding", Severity: "high", ReproSteps: "original steps", Evidence: "original proof"}) + if err != nil { + t.Fatal(err) + } + if v.AssessmentID != task.ID { + t.Fatal(v) + } + owner := assessmentFindingRouter(h, task.OwnerID, map[string]bool{"assessments:read": true, "vulnerability:read": true}) + for _, path := range []string{"/api/deep-assessments/task/vulnerabilities", "/api/deep-assessments/task/vulnerabilities/finding", "/api/deep-assessments/task/steps/one", "/api/deep-assessments/task/receipts?step_id=one", "/api/vulnerabilities/finding/context"} { + w := httptest.NewRecorder() + owner.ServeHTTP(w, httptest.NewRequest("GET", path, nil)) + if w.Code != 200 { + t.Fatal(path, w.Code, w.Body.String()) + } + if path == "/api/vulnerabilities/finding/context" { + var data struct { + Vulnerability database.Vulnerability `json:"vulnerability"` + } + json.Unmarshal(w.Body.Bytes(), &data) + if !data.Vulnerability.AssessmentCanOpen || data.Vulnerability.AssessmentStepTitle != "Origin step" { + t.Fatal(w.Body.String()) + } + } + } + other, _ := h.db.CreateRBACUser("source-reader", "Source reader", "hash", true, nil) + h.db.AssignResourceToUser(other.ID, "deep_assessment", task.ID) + reader := assessmentFindingRouter(h, other.ID, map[string]bool{"assessments:read": true, "vulnerability:read": true}) + w := httptest.NewRecorder() + reader.ServeHTTP(w, httptest.NewRequest("GET", "/api/deep-assessments/task/vulnerabilities", nil)) + var list struct { + Total int `json:"total"` + } + json.Unmarshal(w.Body.Bytes(), &list) + if w.Code != 200 || list.Total != 0 { + t.Fatal("task read leaked findings", w.Code, w.Body.String()) + } + w = httptest.NewRecorder() + reader.ServeHTTP(w, httptest.NewRequest("GET", "/api/deep-assessments/task/vulnerabilities/finding", nil)) + if w.Code != 403 { + t.Fatal(w.Code, w.Body.String()) + } + // Sharing just the finding does not grant access to its assessment. + findingReader, _ := h.db.CreateRBACUser("finding-reader", "Finding reader", "hash", true, nil) + h.db.AssignResourceToUser(findingReader.ID, "vulnerability", v.ID) + r := assessmentFindingRouter(h, findingReader.ID, map[string]bool{"assessments:read": true, "vulnerability:read": true}) + w = httptest.NewRecorder() + r.ServeHTTP(w, httptest.NewRequest("GET", "/api/vulnerabilities/finding/context", nil)) + var ctx struct { + Vulnerability database.Vulnerability `json:"vulnerability"` + } + json.Unmarshal(w.Body.Bytes(), &ctx) + if w.Code != 200 || ctx.Vulnerability.AssessmentCanOpen { + t.Fatal(w.Code, w.Body.String()) + } + w = httptest.NewRecorder() + r.ServeHTTP(w, httptest.NewRequest("GET", "/api/deep-assessments/task/steps/one", nil)) + if w.Code != 403 { + t.Fatal(w.Code, w.Body.String()) + } +} diff --git a/internal/handler/deep_assessment_runtime.go b/internal/handler/deep_assessment_runtime.go index c2b29859..7e5e809c 100644 --- a/internal/handler/deep_assessment_runtime.go +++ b/internal/handler/deep_assessment_runtime.go @@ -287,7 +287,7 @@ func (r *deepAssessmentRuntime) Run(ctx context.Context, t *deepassessment.Task, return out, err } contract := fmt.Sprintf("Assessment mandate (authoritative user task):\nGoal: %s\nScope: %s\nAcceptance: %s\nThis step [%s]: %s\n%s", t.Objective, t.Scope, t.Criteria, step.ID, step.Title, step.Instruction) - message := "继续当前测评步骤,先核对已有结果与未完成项。" + message := "继续当前测评步骤,先核对已有结果与未完成项。可用工具和权限允许时,验证出可复现漏洞后及时调用 record_vulnerability 登记完整复现步骤和证据;平台会按本次执行会话自动关联测评与步骤。检查点里的描述不等同于已登记漏洞。" message += "\n\n用 assessment_memory 检索其他步骤的结果和执行过程,复用已有证据。重要进展调用 assessment_checkpoint。最终必须调用 assessment_result 提交 completed 或 blocked、事实结论、证据回执 IDs(工具结果底部 Execution receipt)和未完成项;需要跨段继续时提交 continue。不能把阶段回复当成整个目标完成。" var roleTools []string if t.Role != "" { diff --git a/internal/handler/vulnerability.go b/internal/handler/vulnerability.go index 0833c321..ba591126 100644 --- a/internal/handler/vulnerability.go +++ b/internal/handler/vulnerability.go @@ -147,6 +147,7 @@ func (h *VulnerabilityHandler) GetVulnerability(c *gin.Context) { return } + decorateAssessmentNavigation(h.db, c, vuln) c.JSON(http.StatusOK, vuln) } @@ -165,18 +166,20 @@ func parseVulnerabilityListFilter(c *gin.Context) database.VulnerabilityListFilt q = strings.TrimSpace(c.Query("search")) } return database.VulnerabilityListFilter{ - ProjectID: c.Query("project_id"), - ID: c.Query("id"), - Search: q, - HostQuery: c.Query("host_q"), - TaskQuery: c.Query("task_q"), - CaseID: c.Query("case_id"), - ConversationID: c.Query("conversation_id"), - Severity: c.Query("severity"), - Status: c.Query("status"), - TaskID: c.Query("task_id"), - ConversationTag: c.Query("conversation_tag"), - TaskTag: c.Query("task_tag"), + ProjectID: c.Query("project_id"), + ID: c.Query("id"), + Search: q, + HostQuery: c.Query("host_q"), + TaskQuery: c.Query("task_q"), + CaseID: c.Query("case_id"), + ConversationID: c.Query("conversation_id"), + Severity: c.Query("severity"), + Status: c.Query("status"), + TaskID: c.Query("task_id"), + AssessmentID: c.Query("assessment_id"), + AssessmentStepID: c.Query("assessment_step_id"), + ConversationTag: c.Query("conversation_tag"), + TaskTag: c.Query("task_tag"), } } @@ -495,7 +498,11 @@ func (h *VulnerabilityHandler) ExportVulnerabilities(c *gin.Context) { key = strings.TrimSpace(v.ConversationTag) } } else { - key = firstNonEmpty(v.TaskTag, v.TaskID, v.TaskQueueID, "unassigned-task") + if v.AssessmentID != "" && v.TaskID == "" { + key = "assessment:" + v.AssessmentID + " · " + v.AssessmentName + } else { + key = firstNonEmpty(v.TaskTag, v.TaskID, v.TaskQueueID, "unassigned-task") + } } grouped[key] = append(grouped[key], v) } @@ -567,6 +574,9 @@ func appendVulnerabilityMarkdown(b *strings.Builder, v *database.Vulnerability, if v.ConversationTag != "" { b.WriteString(fmt.Sprintf("- 对话标签: %s\n", v.ConversationTag)) } + if v.AssessmentID != "" { + fmt.Fprintf(b, "- 深度测评: %s (`%s`)\n- 来源步骤: %s (`%s`)\n", v.AssessmentName, v.AssessmentID, v.AssessmentStepTitle, v.AssessmentStepID) + } if v.TaskTag != "" { b.WriteString(fmt.Sprintf("- 任务标签: %s\n", v.TaskTag)) } diff --git a/internal/handler/vulnerability_workspace.go b/internal/handler/vulnerability_workspace.go index eb12046c..e3f9163c 100644 --- a/internal/handler/vulnerability_workspace.go +++ b/internal/handler/vulnerability_workspace.go @@ -34,6 +34,7 @@ func (h *VulnerabilityHandler) VulnerabilityContext(c *gin.Context) { return } } + decorateAssessmentNavigation(h.db, c, v) c.JSON(http.StatusOK, gin.H{"vulnerability": v, "history": history, "members": members, "assets": assets}) } diff --git a/scripts/assessment-findings-browser.test.cjs b/scripts/assessment-findings-browser.test.cjs new file mode 100644 index 00000000..a9524e62 --- /dev/null +++ b/scripts/assessment-findings-browser.test.cjs @@ -0,0 +1,101 @@ +const {test}=require('node:test'); +const assert=require('node:assert/strict'); +const fs=require('node:fs'); +const path=require('node:path'); +const http=require('node:http'); +const {chromium}=require('playwright'); +const root=path.join(__dirname,'..'); +const read=file=>fs.readFileSync(path.join(root,file),'utf8'); +const template=read('web/templates/index.html'); +function div(id){ + const start=template.indexOf(`
=0,id); + const tags=/<\/?div\b[^>]*>/g;tags.lastIndex=start;let depth=0,m; + while((m=tags.exec(template))){depth+=m[0].startsWith('',impact:'fixture impact',recommendation:'fixture fix',created_at:now,updated_at:now,targets:[{host:'example.test',raw:'https://example.test/account',domain:'example.test'}]}; + const batch={id:'batch-finding',title:'批量任务原有漏洞',severity:'medium',status:'open',description:'batch fixture',target:'https://batch.example.test',task_id:'same-id',task_queue_id:'batch-queue',task_queue_title:'原批量队列',created_at:now,updated_at:now}; + const state={task,sourceStep,finding,batch,requests:[],errors:[],canOpen:true}; + const locale=JSON.stringify(JSON.parse(read('web/static/i18n/zh-CN.json'))).replaceAll('<','\\u003c'); + const scripts=['router','auth','modal','vulnerability','assessment-finding-links','vulnerability-workspace','deep-assessment-graph','deep-assessments'].map(x=>``).join(''); + const styles=['style','mobile','vulnerability-workspace','vulnerability-list','deep-assessments'].map(x=>``).join(''); + const html=`${styles}
${div('page-deep-assessments')}${div('page-vulnerabilities')}
${div('vulnerability-inspector')}${scripts}`; + const server=http.createServer(async(req,res)=>{ + const url=new URL(req.url,'http://fixture'); + const send=(code,data)=>{res.statusCode=code;res.setHeader('Content-Type','application/json; charset=utf-8');res.end(JSON.stringify(data));}; + try{ + if(url.pathname.startsWith('/static/')){res.setHeader('Content-Type',url.pathname.endsWith('.css')?'text/css':'text/javascript');return res.end(read('web'+url.pathname));} + if(url.pathname==='/'){res.setHeader('Content-Type','text/html; charset=utf-8');return res.end(html);} + if(url.pathname==='/favicon.ico'){res.statusCode=204;return res.end();} + state.requests.push({path:url.pathname,query:Object.fromEntries(url.searchParams),method:req.method}); + if(req.headers.authorization!=='Bearer fixture-token')return send(401,{error:'authentication missing'}); + if(url.pathname==='/api/projects')return send(200,{projects:[]}); + if(url.pathname==='/api/deep-assessments')return send(200,{tasks:[task],has_more:false}); + if(url.pathname==='/api/deep-assessments/same-id')return send(200,{task,step_total:101,step_next_offset:50,step_has_more:true}); + if(url.pathname==='/api/deep-assessments/same-id/graph')return send(200,{nodes:[{id:'goal',kind:'goal',state:'completed',title:task.name,body:'',source:{}}],edges:[],total:0,folded:0,has_more:false}); + if(url.pathname==='/api/deep-assessments/same-id/steps/early-step')return send(200,{step:sourceStep}); + if(url.pathname==='/api/deep-assessments/same-id/vulnerabilities')return send(200,{vulnerabilities:[finding],total:1,next_offset:1,has_more:false}); + if(url.pathname==='/api/deep-assessments/same-id/vulnerabilities/finding-1')return send(200,{vulnerability:finding,step:sourceStep}); + if(url.pathname==='/api/deep-assessments/same-id/receipts')return send(200,{receipts:[{id:'receipt-1',execution_id:'execution-1',step_id:'early-step',tool:'fixture_read',arguments:'{}',result:'original-execution-evidence',status:'completed'}],next_offset:1,has_more:false}); + if(url.pathname==='/api/deep-assessments/same-id/events')return send(200,{events:[]}); + if(url.pathname==='/api/vulnerabilities/filter-options')return send(200,{vulnerability_ids:['finding-1','batch-finding'],task_ids:['same-id'],queue_ids:['batch-queue'],assessment_ids:['same-id'],conversation_ids:[],conversation_tags:[],task_tags:[]}); + let items=[finding,batch];if(url.searchParams.get('assessment_id'))items=items.filter(v=>v.assessment_id===url.searchParams.get('assessment_id'));if(url.searchParams.get('id'))items=items.filter(v=>v.id===url.searchParams.get('id')); + if(url.pathname==='/api/vulnerabilities/stats')return send(200,{total:items.length,by_severity:{high:items.filter(v=>v.severity==='high').length,medium:items.filter(v=>v.severity==='medium').length},by_status:{open:items.length}}); + if(url.pathname==='/api/vulnerabilities')return send(200,{vulnerabilities:items,total:items.length,page:1,page_size:20,total_pages:1}); + if(url.pathname==='/api/vulnerabilities/finding-1/context')return send(200,{vulnerability:{...finding,assessment_can_open:state.canOpen},history:[],members:[],assets:[]}); + if(url.pathname==='/api/vulnerabilities/finding-1')return send(200,{...finding,assessment_can_open:state.canOpen}); + return send(404,{error:'unhandled fixture route '+url.pathname}); + }catch(error){send(500,{error:error.message});} + }); + await new Promise(resolve=>server.listen(0,'127.0.0.1',resolve)); + const executablePath=process.env.CHROME_PATH||(process.platform==='darwin'?'/Applications/Google Chrome.app/Contents/MacOS/Google Chrome':undefined); + const browser=await chromium.launch(executablePath?{executablePath}:{}); + t.after(async()=>{await browser.close();server.closeAllConnections();await new Promise(resolve=>server.close(resolve));}); + const page=await browser.newPage({viewport:{width:1440,height:1000}});page.setDefaultTimeout(6000);page.on('pageerror',e=>state.errors.push(e.message));page.on('dialog',d=>d.accept()); + await page.goto(`http://127.0.0.1:${server.address().port}/#deep-assessments`);await page.locator('[data-da-action="select"]').waitFor(); + return {page,state}; +} + +test('assessment findings round-trip through vulnerability management to exact evidence',async t=>{ + const {page,state}=await fixture(t); + await page.locator('[data-da-action="select"]').click();await page.locator('[data-da-action="tab"][data-tab="findings"]').click(); + await page.locator('.da-finding').waitFor();assert.match(await page.locator('.da-finding').innerText(),/权限校验问题/); + await page.locator('.da-finding [data-da-action="open-finding"]').click(); + await page.locator('#vulnerability-inspector a[data-assessment-jump]').first().waitFor(); + assert.match(await page.locator('.vulnerability-assessment-source').innerText(),/域名深度测评/); + await page.locator('#vulnerability-inspector a[data-assessment-jump]').first().click(); + await page.locator('#da-inspector .da-step[data-step="early-step"][open]').waitFor(); + assert.match(page.url(),/assessment_id=same-id/);assert.match(page.url(),/step_id=early-step/); + assert.match(await page.locator('.da-source-banner').innerText(),/权限校验问题/); + await page.reload();await page.locator('#da-inspector .da-step[data-step="early-step"][open]').waitFor(); + await page.locator('.da-source-banner [data-da-action="open-finding"]').click(); + await page.locator('#vulnerability-inspector a[data-assessment-jump]').last().waitFor();await page.locator('#vulnerability-inspector a[data-assessment-jump]').last().click(); + await page.waitForFunction(()=>document.querySelector('.da-source-banner')?.textContent.includes('original-proof')); + assert.match(page.url(),/tab=evidence/);assert.equal(await page.locator('.da-source-banner img').count(),0);assert.equal(await page.evaluate(()=>window.injected),undefined); + assert.ok(state.requests.some(r=>r.path.endsWith('/receipts')&&r.query.step_id==='early-step')); + await page.setViewportSize({width:390,height:844});assert.ok(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth+1)); + await page.waitForFunction(()=>document.getElementById('da-inspector').getAnimations().every(a=>a.playState==='finished')); + assert.equal(await page.locator('#vulnerability-inspector').isVisible(),false);assert.equal(await page.locator('dialog[open]').count(),1); + const box=await page.locator('#da-inspector').boundingBox();assert.ok(Math.abs(box.x)<1&&Math.abs(box.y)<1&&Math.abs(box.width-390)<1); + assert.ok(state.requests.every(r=>r.method==='GET')); + assert.deepEqual(state.errors,[]); + const dir=process.env.CSAI_SCREENSHOT_DIR;if(dir){fs.mkdirSync(dir,{recursive:true});await page.screenshot({path:path.join(dir,'assessment-finding-evidence.png'),fullPage:true});} +}); + +test('task grouping separates assessment IDs from batch IDs and disabled source links',async t=>{ + const {page,state}=await fixture(t); + await page.evaluate(()=>{location.hash='vulnerabilities?view=task';}); + await page.locator('#vulnerabilities-list [data-host-key="assessment:same-id"]').waitFor(); + assert.match(await page.locator('[data-host-key="assessment:same-id"]').innerText(),/域名深度测评/); + assert.match(await page.locator('[data-host-key="queue:batch-queue"]').innerText(),/原批量队列/); + await page.locator('[data-host-key="assessment:same-id"]').click();await page.waitForFunction(()=>document.querySelectorAll('#vulnerability-host-table [data-vuln-id]').length>0); + assert.equal(await page.locator('#vulnerability-host-table #vulnerability-card-batch-finding').count(),0); + state.canOpen=false; + await page.locator('#vulnerability-host-table #vulnerability-card-finding-1 .vulnerability-record-main').click(); + await page.locator('.vulnerability-assessment-source').waitFor();assert.equal(await page.locator('.vulnerability-assessment-source a').count(),0); + assert.deepEqual(state.errors,[]); +}); diff --git a/web/static/css/deep-assessments.css b/web/static/css/deep-assessments.css index f7fb9757..fd7fc87b 100644 --- a/web/static/css/deep-assessments.css +++ b/web/static/css/deep-assessments.css @@ -161,3 +161,4 @@ body.da-drawer-open { overflow: hidden; } } .da-graph-toolbar,.da-graph-legend{display:flex;align-items:center;gap:8px;flex-wrap:wrap}.da-graph-toolbar{margin:12px 0}.da-graph-toolbar button{font-size:12px;padding:7px 10px}#da-graph-meta{font-size:12px;color:var(--text-secondary);margin-left:auto}.da-graph-legend{margin:12px 0;font-size:11px;color:var(--text-secondary)}.da-graph-legend span::before{content:'';display:inline-block;width:8px;height:8px;border-radius:2px;margin-right:5px;background:var(--graph-color)}.da-kind-goal{--graph-color:#6366f1}.da-kind-step{--graph-color:#3b82f6}.da-kind-observation{--graph-color:#14b8a6}.da-kind-receipt{--graph-color:#64748b}.da-kind-memory{--graph-color:#a855f7}.da-kind-digest{--graph-color:#d97706}.da-kind-guidance{--graph-color:#0891b2}.da-graph-workspace{display:grid;grid-template-columns:minmax(0,1fr) 260px;border:1px solid var(--border-color);border-radius:8px;overflow:hidden}#da-graph-canvas{min-width:0;height:440px;background:var(--bg-secondary)}#da-graph-node{padding:14px;border-left:1px solid var(--border-color);overflow:auto;max-height:440px;min-width:0}#da-graph-node h4{margin:10px 0;overflow-wrap:anywhere}#da-graph-node code{font-size:11px;overflow-wrap:anywhere}#da-graph-node pre{font-size:12px}#da-graph-pages{margin-top:12px}@media(max-width:650px){.da-graph-workspace{grid-template-columns:1fr}#da-graph-canvas{height:340px}#da-graph-node{border-left:0;border-top:1px solid var(--border-color);max-height:300px}#da-graph-meta{margin-left:0;width:100%}} #da-graph-select{margin:10px 0} +.da-finding,.da-source-banner{border:1px solid var(--border-color);border-radius:8px;padding:14px;margin:14px 0;overflow-wrap:anywhere}.da-finding h4{margin:0 0 10px}.da-source-banner{border-left:3px solid var(--accent-color);background:var(--bg-secondary)}.da-source-banner h4{margin:14px 0 8px}.vulnerability-assessment-source{border:1px solid var(--border-color);border-radius:8px;padding:14px;margin:16px 0;overflow-wrap:anywhere}.vulnerability-assessment-source p{margin:10px 0}.vulnerability-assessment-source a{text-decoration:none} diff --git a/web/static/i18n/en-US.json b/web/static/i18n/en-US.json index f299c5a9..ba9db900 100644 --- a/web/static/i18n/en-US.json +++ b/web/static/i18n/en-US.json @@ -3016,7 +3016,9 @@ "detailRetestLog": "Retest log", "downloadOkTitle": "Downloaded", "exportFailedMessage": "Export failed", - "downloadFailed": "Download failed" + "downloadFailed": "Download failed", + "assessmentTask": "Deep assessment", + "assessmentStep": "Assessment step" }, "tasksPage": { "statusFilter": "Status filter", @@ -5373,6 +5375,23 @@ "note": "Recorded observation", "user": "User supplied", "folded": "Folded" - } + }, + "findings": "Findings", + "noFindings": "No registered findings yet.", + "openFinding": "Open in vulnerability management", + "allFindings": "View this assessment in vulnerability management", + "reproduction": "Reproduction steps", + "findingEvidence": "Reproduction evidence", + "sourceStep": "Source step", + "allSteps": "Show all steps and receipts", + "sourceFinding": "Related finding" + }, + "assessmentFindingLinks": { + "source": "Source assessment", + "step": "Source step", + "openStep": "Return to assessment step", + "evidence": "View step and reproduction evidence", + "deleted": "Assessment deleted; finding retained", + "unavailable": "This account cannot open the source assessment" } } diff --git a/web/static/i18n/ru-RU.json b/web/static/i18n/ru-RU.json index 96909c31..b5e5a246 100644 --- a/web/static/i18n/ru-RU.json +++ b/web/static/i18n/ru-RU.json @@ -3029,7 +3029,9 @@ "detailRetestLog": "Журнал повторных проверок", "downloadOkTitle": "Скачано", "exportFailedMessage": "Экспорт не удался", - "downloadFailed": "Загрузка не удалась" + "downloadFailed": "Загрузка не удалась", + "assessmentTask": "Глубокая оценка", + "assessmentStep": "Шаг оценки" }, "tasksPage": { "statusFilter": "Фильтр статуса", @@ -5386,6 +5388,23 @@ "note": "Наблюдение", "user": "От пользователя", "folded": "Свернуто" - } + }, + "findings": "Уязвимости", + "noFindings": "Уязвимости пока не зарегистрированы.", + "openFinding": "Открыть управление уязвимостями", + "allFindings": "Все уязвимости этой оценки", + "reproduction": "Шаги воспроизведения", + "findingEvidence": "Доказательства", + "sourceStep": "Исходный шаг", + "allSteps": "Все шаги и результаты", + "sourceFinding": "Связанная уязвимость" + }, + "assessmentFindingLinks": { + "source": "Исходная оценка", + "step": "Исходный шаг", + "openStep": "Открыть шаг оценки", + "evidence": "Шаг и доказательства воспроизведения", + "deleted": "Оценка удалена; уязвимость сохранена", + "unavailable": "Нет доступа к исходной оценке" } } diff --git a/web/static/i18n/zh-CN.json b/web/static/i18n/zh-CN.json index 3077d926..f333fdd4 100644 --- a/web/static/i18n/zh-CN.json +++ b/web/static/i18n/zh-CN.json @@ -3004,7 +3004,9 @@ "detailRetestLog": "复测记录", "downloadOkTitle": "下载成功", "exportFailedMessage": "导出失败", - "downloadFailed": "下载失败" + "downloadFailed": "下载失败", + "assessmentTask": "深度测评", + "assessmentStep": "测评步骤" }, "tasksPage": { "statusFilter": "状态筛选", @@ -5361,6 +5363,23 @@ "note": "观察记录", "user": "用户提供", "folded": "已折叠" - } + }, + "findings": "关联漏洞", + "noFindings": "暂未登记漏洞。", + "openFinding": "在漏洞管理查看", + "allFindings": "在漏洞管理查看本次测评", + "reproduction": "复现步骤", + "findingEvidence": "复现证据", + "sourceStep": "来源步骤", + "allSteps": "显示全部步骤与回执", + "sourceFinding": "关联漏洞" + }, + "assessmentFindingLinks": { + "source": "来源深度测评", + "step": "来源步骤", + "openStep": "返回测评步骤", + "evidence": "查看步骤与复现证据", + "deleted": "测评已删除,漏洞记录仍保留", + "unavailable": "当前账号不能打开关联测评" } } diff --git a/web/static/js/assessment-finding-links.js b/web/static/js/assessment-finding-links.js new file mode 100644 index 00000000..10640344 --- /dev/null +++ b/web/static/js/assessment-finding-links.js @@ -0,0 +1,43 @@ +/* Navigation uses stable assessment/step IDs; names and tags are display only. */ +(function () { + 'use strict'; + const labels = { source: '来源深度测评', step: '来源步骤', openStep: '返回测评步骤', evidence: '查看步骤与复现证据', deleted: '测评已删除,漏洞记录仍保留', unavailable: '当前账号不能打开关联测评' }; + const t = key => { const path = 'assessmentFindingLinks.' + key; const text = typeof window.t === 'function' ? window.t(path) : ''; return text && text !== path ? text : labels[key]; }; + const escape = value => String(value ?? '').replace(/[&<>"']/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c]); + function href(v, tab = 'plan') { + return '#deep-assessments?' + new URLSearchParams({ assessment_id: v.assessment_id, step_id: v.assessment_step_id || '', tab, vulnerability_id: v.id }); + } + function render(v) { + if (!v.assessment_id) return ''; + const links = v.assessment_can_open && !v.assessment_deleted + ? `
${escape(t('openStep'))}${escape(t('evidence'))}
` + : `

${escape(t(v.assessment_deleted ? 'deleted' : 'unavailable'))}

`; + return `
${escape(t('source'))}:${escape(v.assessment_name || v.assessment_id)}

${escape(t('step'))}:${escape(v.assessment_step_title || v.assessment_step_id)}

${links}
`; + } + function openFinding(id, assessmentID = '') { + const params = new URLSearchParams({ view: 'task' }); + if (id) params.set('id', id); + if (assessmentID) params.set('assessment_id', assessmentID); + const alreadyOpen = document.getElementById('page-vulnerabilities')?.classList.contains('active'); + history.replaceState(null, '', '#vulnerabilities?' + params); + if (typeof window.switchPage === 'function') window.switchPage('vulnerabilities'); + // New-page initialization loads once and opens the exact finding. When + // already on this page, update its filters and let that same path run. + if (alreadyOpen) { + if (typeof window.syncVulnerabilityFiltersFromLocationHash === 'function') window.syncVulnerabilityFiltersFromLocationHash(); + if (typeof window.refreshVulnerabilities === 'function') window.refreshVulnerabilities(); + } + } + document.addEventListener('click', event => { + const link = event.target.closest?.('a[data-assessment-jump]'); + if (!link || event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return; + event.preventDefault(); + if (typeof window.closeVulnerabilityInspectorForNavigation === 'function') window.closeVulnerabilityInspectorForNavigation(); + else if (typeof window.closeAppModal === 'function') window.closeAppModal('vulnerability-inspector'); + history.replaceState(null, '', link.hash); + const alreadyOpen = document.getElementById('page-deep-assessments')?.classList.contains('active'); + if (typeof window.switchPage === 'function') window.switchPage('deep-assessments'); + if (alreadyOpen) window.DeepAssessments?.fromLocation(); + }); + window.AssessmentFindingLinks = { href, render, openFinding }; +})(); diff --git a/web/static/js/deep-assessments.js b/web/static/js/deep-assessments.js index 42e69d53..95ccc224 100644 --- a/web/static/js/deep-assessments.js +++ b/web/static/js/deep-assessments.js @@ -1,8 +1,8 @@ /* Independent assessment workspace. Batch task routes and controllers are untouched. */ (function () { 'use strict'; - const S = { id: '', task: null, tab: 'graph', graph: null, graphScope: '', graphOffset: 0, graphNode: null, nodeOffset: 0, nodeMore: false, nodeRequest: 0, stepOffset: 0, stepTotal: 0, stepMore: false, page: 0, more: false, busy: false, epoch: 0, timer: null, mounted: false, drawerEpoch: 0, events: [], receipts: [], receiptOffset: 0, receiptMore: false }; - const labels = { graph: '探索图', continuous: '持续执行', mode: '运行模式', elapsed: '已运行', graphHint: '摘要用于续接;原始观察和执行回执可随时展开。', graphVisible: '当前页节点', graphFolded: '已折叠节点', graphHome: '全图概览', graphExpand: '展开关联节点', graphFit: '适应画布', graphSelect: '点击节点查看原始内容与来源。', graphMore: '继续读取原文', status: '状态', updatedAt: '更新时间', loading: '正在读取测评…', contextUsage:'上下文 / 窗口', toolDefinitions:'工具定义', title: '深度测评', subtitle: '围绕一个目标持续探索,保存证据与进度,跨会话继续执行。', create: '新建测评', refresh: '刷新', search: '搜索测评名称', all: '全部状态', empty: '暂无测评,先创建一个目标。', select: '选择测评,查看探索进度与证据。', previous: '上一页', next: '下一页', name: '测评名称', objective: '目标', scope: '允许范围与排除项', criteria: '验收条件', model: '模型渠道', project: '关联项目', role: '角色', default: '系统默认', none: '不关联', tokens: '累计 Token', rounds: '规划轮次', concurrency: '并行步骤', autoResume: '服务重启后自动恢复结果明确的步骤', save: '保存草稿', close: '关闭', start: '开始 / 继续', pause: '暂停', cancel: '停止', delete: '删除', report: '下载报告', overview: '概览', plan: '步骤清单', evidence: '证据回执', activity: '运行记录', quality: '上下文与用量', guidance: '补充线索或调整方向', send: '提交方向', answer: '答复并继续', retry: '恢复此步骤', conversation: '查看执行会话', unknown: '请先核对回执,确认上次操作结果及执行资源状态。', reconcile: '我已核对上次调用结果,允许从原会话继续', confirmStop: '停止后将保留已有结果,结束本次测评。', confirmDelete: '删除本条测评?关联执行会话仍保留。', strategy: '当前路线', summary: '当前结论 / 缺口', question: '待补充信息', dependencies: '前置步骤', segments: '执行分段', evidenceIDs: '证据引用', noSteps: '开始后由规划器逐步生成探索方向。', noRecords: '暂无记录', calls: '工具调用', compactions: '上下文压缩', activeTools: '当前可见工具', session: '会话', tokenNote: '累计用量包含 Pi 压缩,不作为任务自动结束条件。', recoveryNote: '结果不明的调用会暂停等待核对,已完成步骤不会自动重做。', saved: '已保存', updated: '已更新', retryNote: '恢复会保留原 Pi 会话及历史证据。' }; + const S = { routeKey: '', focusStepId: '', focusedStep: null, originFindingId: '', originFinding: null, findings: [], findingOffset: 0, findingMore: false, findingTotal: 0, id: '', task: null, tab: 'graph', graph: null, graphScope: '', graphOffset: 0, graphNode: null, nodeOffset: 0, nodeMore: false, nodeRequest: 0, stepOffset: 0, stepTotal: 0, stepMore: false, page: 0, more: false, busy: false, epoch: 0, timer: null, mounted: false, drawerEpoch: 0, events: [], receipts: [], receiptOffset: 0, receiptMore: false }; + const labels = { findings: '关联漏洞', noFindings: '暂未登记漏洞。', openFinding: '在漏洞管理查看', allFindings: '在漏洞管理查看本次测评', reproduction: '复现步骤', findingEvidence: '复现证据', sourceStep: '来源步骤', allSteps: '显示全部步骤与回执', sourceFinding: '关联漏洞', graph: '探索图', continuous: '持续执行', mode: '运行模式', elapsed: '已运行', graphHint: '摘要用于续接;原始观察和执行回执可随时展开。', graphVisible: '当前页节点', graphFolded: '已折叠节点', graphHome: '全图概览', graphExpand: '展开关联节点', graphFit: '适应画布', graphSelect: '点击节点查看原始内容与来源。', graphMore: '继续读取原文', status: '状态', updatedAt: '更新时间', loading: '正在读取测评…', contextUsage:'上下文 / 窗口', toolDefinitions:'工具定义', title: '深度测评', subtitle: '围绕一个目标持续探索,保存证据与进度,跨会话继续执行。', create: '新建测评', refresh: '刷新', search: '搜索测评名称', all: '全部状态', empty: '暂无测评,先创建一个目标。', select: '选择测评,查看探索进度与证据。', previous: '上一页', next: '下一页', name: '测评名称', objective: '目标', scope: '允许范围与排除项', criteria: '验收条件', model: '模型渠道', project: '关联项目', role: '角色', default: '系统默认', none: '不关联', tokens: '累计 Token', rounds: '规划轮次', concurrency: '并行步骤', autoResume: '服务重启后自动恢复结果明确的步骤', save: '保存草稿', close: '关闭', start: '开始 / 继续', pause: '暂停', cancel: '停止', delete: '删除', report: '下载报告', overview: '概览', plan: '步骤清单', evidence: '证据回执', activity: '运行记录', quality: '上下文与用量', guidance: '补充线索或调整方向', send: '提交方向', answer: '答复并继续', retry: '恢复此步骤', conversation: '查看执行会话', unknown: '请先核对回执,确认上次操作结果及执行资源状态。', reconcile: '我已核对上次调用结果,允许从原会话继续', confirmStop: '停止后将保留已有结果,结束本次测评。', confirmDelete: '删除本条测评?关联执行会话仍保留。', strategy: '当前路线', summary: '当前结论 / 缺口', question: '待补充信息', dependencies: '前置步骤', segments: '执行分段', evidenceIDs: '证据引用', noSteps: '开始后由规划器逐步生成探索方向。', noRecords: '暂无记录', calls: '工具调用', compactions: '上下文压缩', activeTools: '当前可见工具', session: '会话', tokenNote: '累计用量包含 Pi 压缩,不作为任务自动结束条件。', recoveryNote: '结果不明的调用会暂停等待核对,已完成步骤不会自动重做。', saved: '已保存', updated: '已更新', retryNote: '恢复会保留原 Pi 会话及历史证据。' }; const states = { draft: '草稿', running: '执行中', pending: '待执行', completed: '已完成', blocked: '受阻', failed: '失败', paused: '已暂停', pausing: '暂停中', cancelling: '停止中', cancelled: '已停止', recovering: '待恢复', waiting_retry: '等待模型恢复', waiting_input: '待答复', needs_review: '待核对', uncertain: '结果不明', waiting_progress: '等待新进展', interrupted: '已中断', cleanup_unconfirmed: '待确认资源停止', retired: '已撤下', reconciled: '已核对', yielded: '分段完成' }; const tr = (key, fallback) => { const v = typeof window.t === 'function' ? window.t('deepAssessments.' + key) : ''; return v && v !== 'deepAssessments.' + key ? v : fallback; }; const L = key => tr(key, labels[key] || key); @@ -11,6 +11,7 @@ const $ = id => document.getElementById(id); const active = t => ['running', 'pausing', 'cancelling'].includes(t?.status); const terminal = t => ['completed', 'cancelled'].includes(t?.status); + const canFindings = () => typeof window.hasPermission !== 'function' || window.hasPermission('vulnerability:read'); const can = action => typeof window.hasPermission !== 'function' || window.hasPermission('assessments:' + action); function notice(message, error = false) { ['da-notice', 'da-detail-notice', 'da-form-notice'].forEach(id => { @@ -75,6 +76,34 @@ async function json(path, options) { return (await api(path, options)).json(); } const button = (action, label, extra = '') => ``; const badge = value => `${esc(status(value))}`; + function writeRoute() { + if (!S.id) return; + const params = new URLSearchParams({ assessment_id: S.id, tab: S.tab }); + if (S.focusStepId) params.set('step_id', S.focusStepId); + if (S.originFindingId) params.set('vulnerability_id', S.originFindingId); + history.replaceState(null, '', '#deep-assessments?' + params); + S.routeKey = window.location.hash; + } + function applyRoute() { + const [page, ...query] = window.location.hash.slice(1).split('?'); + if (page !== 'deep-assessments' || !$('page-deep-assessments')?.classList.contains('active') || (typeof window.hasPermission === 'function' && !window.hasPermission('assessments:read'))) return false; + const params = new URLSearchParams(query.join('?')), id = params.get('assessment_id'); + if (!id) return false; + if (S.routeKey === window.location.hash && $('da-inspector').open) return false; + const changed = S.id !== id; + S.id = id; if (changed) { S.task = null; $('da-guidance').value = ''; } + S.focusStepId = params.get('step_id') || ''; S.originFindingId = params.get('vulnerability_id') || ''; + S.focusedStep = null; S.originFinding = null; S.findings = []; S.findingOffset = 0; S.receiptOffset = 0; S.stepOffset = 0; + S.tab = ['overview','graph','plan','evidence','activity','quality','findings'].includes(params.get('tab')) ? params.get('tab') : (S.focusStepId ? 'plan' : 'graph'); + S.graph = null; S.graphScope = ''; S.graphNode = null; S.graphOffset = 0; S.events = []; S.receipts = []; + S.routeKey = window.location.hash; ++S.epoch; + renderTask(); openDrawer('da-inspector'); return true; + } + function sourceBanner(includeEvidence = false) { + if (!S.focusStepId && !S.originFinding) return ''; + const finding = S.originFinding; + return `
${esc(L('sourceStep'))}:${esc(S.focusedStep?.title || finding?.assessment_step_title || S.focusStepId)}${finding ? `

${esc(L('sourceFinding'))}:${esc(finding.title)}

` : ''}${includeEvidence && finding ? `

${esc(L('reproduction'))}

${esc(finding.reproduction_steps)}

${esc(L('findingEvidence'))}

${esc(finding.evidence)}
` : ''}
${button('clear-source', L('allSteps'))}${finding ? button('open-finding', L('openFinding'), `data-vulnerability="${esc(finding.id)}"`) : ''}
`; + } function mount() { const root = $('deep-assessments-root'); if (!root || S.mounted) return; S.mounted = true; @@ -98,7 +127,7 @@ bindDrawer('da-inspector'); bindDrawer('da-form-drawer'); window.addEventListener('hashchange', () => { - if (window.location.hash.slice(1).split('?')[0] !== 'deep-assessments') { closeDrawer('da-form-drawer'); closeDrawer('da-inspector'); } + if (window.location.hash.slice(1).split('?')[0] !== 'deep-assessments') { closeDrawer('da-form-drawer'); closeDrawer('da-inspector'); } else if (applyRoute()) void refresh(); }); root.addEventListener('click', event => { const target = event.target.closest('[data-da-action]'); if (target) void action(target.dataset.daAction, target.dataset); }); root.addEventListener('submit', event => { event.preventDefault(); if (event.target.id === 'da-create-form') void saveCreate(event.target); if (event.target.id === 'da-guidance-form') void guidance(); }); @@ -112,7 +141,7 @@ if (!task) { $('da-title').textContent = L('title'); $('da-controls').innerHTML = ''; $('da-tabs').innerHTML = ''; $('da-body').textContent = L(S.id ? 'loading' : 'select'); $('da-guidance-form').hidden = true; return; } $('da-title').innerHTML = `

${esc(task.name)} ${badge(task.status)}

`; $('da-controls').innerHTML = `${can('write') && !terminal(task) ? (!active(task) ? button('start', L('start'), task.question || task.status === 'needs_review' ? 'disabled' : '') : button('pause', L('pause'), task.status !== 'running' ? 'disabled' : '')) + button('cancel', L('cancel')) : ''}${button('report', L('report'))}${can('delete') && !active(task) ? button('delete', L('delete')) : ''}`; - $('da-tabs').innerHTML = ['overview', 'graph', 'plan', 'evidence', 'activity', 'quality'].map(tab => ``).join(''); + $('da-tabs').innerHTML = ['overview', 'graph', 'plan', ...(canFindings() ? ['findings'] : []), 'evidence', 'activity', 'quality'].map(tab => ``).join(''); const body = $('da-body'), scroller = $('da-inspector').querySelector('.da-detail-scroll'), scroll = scroller.scrollTop; const opened = new Set([...body.querySelectorAll('details[open]')].map(el => el.dataset.step)); if (S.tab !== 'graph') window.DeepAssessmentGraph?.destroy(); @@ -122,10 +151,12 @@ } else if (S.tab === 'graph') { renderGraph(body); } else if (S.tab === 'plan') { - body.innerHTML = (task.steps || []).map(step => `
${badge(step.status)} ${esc(step.title)}${esc(step.id)}
${esc(step.instruction)}

${esc(L('dependencies'))}: ${esc((step.depends_on || []).join(', ') || '—')} · ${esc(L('segments'))}: ${step.attempts || 0}

${esc(step.summary)}

${esc(L('evidenceIDs'))}: ${esc((step.evidence || []).join(', ') || '—')}

${step.conversation_id ? button('conversation', L('conversation'), `data-conversation="${esc(step.conversation_id)}"`) : ''}${!active(task) && can('write') && ['failed', 'blocked', 'interrupted', 'uncertain', 'cleanup_unconfirmed'].includes(step.status) ? button('retry', L('retry'), `data-step="${esc(step.id)}"`) : ''}
`).join('') || `

${esc(L('noSteps'))}

`; - body.innerHTML += `
${S.stepOffset ? button('step-previous', L('previous')) : ''}${(task.steps || []).length} / ${S.stepTotal}${S.stepMore ? button('step-next', L('next')) : ''}
`; + body.innerHTML = sourceBanner() + (S.focusedStep ? [S.focusedStep] : task.steps || []).map(step => `
${badge(step.status)} ${esc(step.title)}${esc(step.id)}
${esc(step.instruction)}

${esc(L('dependencies'))}: ${esc((step.depends_on || []).join(', ') || '—')} · ${esc(L('segments'))}: ${step.attempts || 0}

${esc(step.summary)}

${esc(L('evidenceIDs'))}: ${esc((step.evidence || []).join(', ') || '—')}

${step.conversation_id ? button('conversation', L('conversation'), `data-conversation="${esc(step.conversation_id)}"`) : ''}${!active(task) && can('write') && ['failed', 'blocked', 'interrupted', 'uncertain', 'cleanup_unconfirmed'].includes(step.status) ? button('retry', L('retry'), `data-step="${esc(step.id)}"`) : ''}
`).join('') || `

${esc(L('noSteps'))}

`; + if (!S.focusStepId) body.innerHTML += `
${S.stepOffset ? button('step-previous', L('previous')) : ''}${(task.steps || []).length} / ${S.stepTotal}${S.stepMore ? button('step-next', L('next')) : ''}
`; + } else if (S.tab === 'findings') { + body.innerHTML = `
${button('all-findings', L('allFindings'))}${S.findingTotal}
` + (S.findings.map(v => `

${esc(v.title)}

${esc(v.severity)} · ${esc(v.status)}

${esc(L('sourceStep'))}:${esc(v.assessment_step_title || v.assessment_step_id)}

${button('open-finding', L('openFinding'), `data-vulnerability="${esc(v.id)}"`)}${button('finding-evidence', L('findingEvidence'), `data-vulnerability="${esc(v.id)}" data-step="${esc(v.assessment_step_id)}"`)}
`).join('') || `

${esc(L('noFindings'))}

`) + `
${S.findingOffset ? button('previous-findings', L('previous')) : ''}${S.findingMore ? button('next-findings', L('next')) : ''}
`; } else if (S.tab === 'evidence') { - body.innerHTML = S.receipts.map(row => `
${badge(row.status)} ${esc(row.tool)} · ${esc(row.step_id)}${esc(row.execution_id || row.id)}
${esc(row.arguments)}
${esc(row.result)}
`).join('') || `

${esc(L('noRecords'))}

`; + body.innerHTML = sourceBanner(true) + S.receipts.map(row => `
${badge(row.status)} ${esc(row.tool)} · ${esc(row.step_id)}${esc(row.execution_id || row.id)}
${esc(row.arguments)}
${esc(row.result)}
`).join('') || `

${esc(L('noRecords'))}

`; body.innerHTML += `
${S.receiptOffset > 0 ? button('previous-receipts', L('previous')) : ''}${S.receiptMore ? button('more-receipts', L('next')) : ''}
`; } else if (S.tab === 'activity') { body.innerHTML = S.events.slice().reverse().map(row => `
${esc(new Date(row.created_at).toLocaleString())} · ${esc(row.step_id)} · ${esc(row.kind)}
${esc(row.message)}
`).join('') || `

${esc(L('noRecords'))}

`; @@ -153,9 +184,19 @@ $('deep-assessments-root').querySelector('[data-da-action="next"]').disabled = !S.more; if (detail && (!S.task || detail.task.revision >= S.task.revision)) S.task = detail.task; if (detail) { S.stepTotal = detail.step_total ?? detail.task.steps?.length ?? 0; S.stepMore = !!detail.step_has_more; } + if (id && S.originFindingId && canFindings()) { + const data = await json('/' + encodeURIComponent(id) + '/vulnerabilities/' + encodeURIComponent(S.originFindingId)); if (epoch !== S.epoch) return; + S.originFinding = data.vulnerability; S.focusedStep = data.step; S.focusStepId = data.vulnerability.assessment_step_id; + } else if (id && S.focusStepId) { + const data = await json('/' + encodeURIComponent(id) + '/steps/' + encodeURIComponent(S.focusStepId)); if (epoch !== S.epoch) return; S.focusedStep = data.step; + } + if (id && S.tab === 'findings' && canFindings()) { + const data = await json('/' + encodeURIComponent(id) + '/vulnerabilities?limit=20&offset=' + S.findingOffset); if (epoch !== S.epoch) return; + S.findings = data.vulnerabilities || []; S.findingTotal = data.total; S.findingMore = data.has_more; + } if (id && S.tab === 'graph') { const data = await json('/' + encodeURIComponent(id) + '/graph?' + new URLSearchParams({ scope: S.graphScope, offset: S.graphOffset, limit: 80 })); if (epoch !== S.epoch) return; S.graph = data; } if (id && S.tab === 'activity') { const data = await json('/' + encodeURIComponent(id) + '/events?after=' + (S.events.at(-1)?.id || 0)); if (epoch !== S.epoch) return; S.events.push(...data.events); S.events = S.events.slice(-500); } - if (id && S.tab === 'evidence') { const data = await json('/' + encodeURIComponent(id) + '/receipts?offset=' + S.receiptOffset); if (epoch !== S.epoch) return; S.receipts = data.receipts; S.receiptMore = data.has_more; } + if (id && S.tab === 'evidence') { const data = await json('/' + encodeURIComponent(id) + '/receipts?' + new URLSearchParams({ offset: S.receiptOffset, step_id: S.focusStepId })); if (epoch !== S.epoch) return; S.receipts = data.receipts; S.receiptMore = data.has_more; } renderTask(); } catch (error) { if (epoch === S.epoch) notice(error.message, true); } } @@ -218,7 +259,7 @@ const values = Object.fromEntries(new FormData(form)); values.concurrency = Number(values.concurrency); values.auto_resume = form.elements.auto_resume.checked; S.busy = true; ++S.epoch; form.querySelector('button[type="submit"]').disabled = true; - try { const data = await json('', { method: 'POST', body: JSON.stringify(values) }); S.id = data.task.id; S.task = data.task; S.tab = 'graph'; S.stepOffset = 0; S.stepMore = false; S.stepTotal = 0; S.graph = null; S.graphScope = ''; S.graphOffset = 0; S.graphNode = null; S.events = []; S.receipts = []; S.receiptOffset = 0; closeDrawer('da-form-drawer'); renderTask(); if ($('page-deep-assessments')?.classList.contains('active')) openDrawer('da-inspector'); notice(L('saved')); } + try { const data = await json('', { method: 'POST', body: JSON.stringify(values) }); S.id = data.task.id; S.task = data.task; S.focusStepId = ''; S.focusedStep = null; S.originFindingId = ''; S.originFinding = null; S.findingOffset = 0; S.tab = 'graph'; S.stepOffset = 0; S.stepMore = false; S.stepTotal = 0; S.graph = null; S.graphScope = ''; S.graphOffset = 0; S.graphNode = null; S.events = []; S.receipts = []; S.receiptOffset = 0; closeDrawer('da-form-drawer'); writeRoute(); renderTask(); if ($('page-deep-assessments')?.classList.contains('active')) openDrawer('da-inspector'); notice(L('saved')); } catch (error) { notice(error.message, true); } finally { S.busy = false; form.querySelector('button[type="submit"]').disabled = false; await refresh(); } } @@ -231,8 +272,12 @@ if (name === 'create') return await create(); if (name === 'refresh') return await refresh(); if (name === 'previous' || name === 'next') { S.page += name === 'previous' ? -1 : 1; S.page = Math.max(0, S.page); return await refresh(); } - if (name === 'select') { ++S.drawerEpoch; if (S.id !== data.id) { S.id = data.id; S.task = null; S.tab = 'graph'; S.stepOffset = 0; S.stepMore = false; S.stepTotal = 0; S.graph = null; S.graphScope = ''; S.graphOffset = 0; S.graphNode = null; ++S.nodeRequest; S.events = []; S.receipts = []; S.receiptOffset = 0; $('da-guidance').value = ''; $('da-inspector').querySelector('.da-detail-scroll').scrollTop = 0; } renderTask(); openDrawer('da-inspector'); return await refresh(); } - if (name === 'tab') { S.tab = data.tab; $('da-inspector').querySelector('.da-detail-scroll').scrollTop = 0; return await refresh(); } + if (name === 'select') { ++S.drawerEpoch; S.focusStepId = ''; S.focusedStep = null; S.originFindingId = ''; S.originFinding = null; S.findingOffset = 0; if (S.id !== data.id) { S.id = data.id; S.task = null; S.tab = 'graph'; S.stepOffset = 0; S.stepMore = false; S.stepTotal = 0; S.graph = null; S.graphScope = ''; S.graphOffset = 0; S.graphNode = null; ++S.nodeRequest; S.events = []; S.receipts = []; S.receiptOffset = 0; $('da-guidance').value = ''; $('da-inspector').querySelector('.da-detail-scroll').scrollTop = 0; } writeRoute(); renderTask(); openDrawer('da-inspector'); return await refresh(); } + if (name === 'tab') { S.tab = data.tab; writeRoute(); $('da-inspector').querySelector('.da-detail-scroll').scrollTop = 0; return await refresh(); } + if (name === 'open-finding' || name === 'all-findings') { closeDrawer('da-form-drawer'); closeDrawer('da-inspector'); window.AssessmentFindingLinks?.openFinding(name === 'open-finding' ? data.vulnerability : '', S.id); return; } + if (name === 'finding-evidence') { S.originFindingId = data.vulnerability; S.focusStepId = data.step; S.focusedStep = null; S.originFinding = null; S.tab = 'evidence'; S.receiptOffset = 0; writeRoute(); return await refresh(); } + if (name === 'clear-source') { S.focusStepId = ''; S.focusedStep = null; S.originFindingId = ''; S.originFinding = null; S.receiptOffset = 0; writeRoute(); return await refresh(); } + if (name === 'next-findings' || name === 'previous-findings') { S.findingOffset = Math.max(0, S.findingOffset + (name === 'next-findings' ? 20 : -20)); return await refresh(); } if (name === 'step-next' || name === 'step-previous') { S.stepOffset = Math.max(0, S.stepOffset + (name === 'step-next' ? 50 : -50)); return await refresh(); } if (name === 'graph-fit') return window.DeepAssessmentGraph?.fit(); if (name === 'graph-in') return window.DeepAssessmentGraph?.zoomIn(); @@ -244,11 +289,11 @@ if (name === 'cancel') { if (window.confirm(L('confirmStop'))) return await mutate('cancel'); return; } if (name === 'conversation') { closeDrawer('da-form-drawer'); closeDrawer('da-inspector'); if (typeof window.switchPage === 'function') window.switchPage('chat'); if (typeof window.loadConversation === 'function') await window.loadConversation(data.conversation); return; } - if (name === 'retry') { const step = S.task.steps.find(s => s.id === data.step); const uncertain = ['uncertain', 'cleanup_unconfirmed'].includes(step?.status); if (uncertain && !window.confirm(L('unknown') + '\n\n' + L('reconcile'))) return; return await mutate('retry', { step_id: data.step, reconciled: uncertain, cleanup_confirmed: uncertain }); } + if (name === 'retry') { const step = (S.focusedStep?.id === data.step ? S.focusedStep : S.task.steps.find(s => s.id === data.step)); const uncertain = ['uncertain', 'cleanup_unconfirmed'].includes(step?.status); if (uncertain && !window.confirm(L('unknown') + '\n\n' + L('reconcile'))) return; return await mutate('retry', { step_id: data.step, reconciled: uncertain, cleanup_confirmed: uncertain }); } if (name === 'report') { const response = await api('/' + encodeURIComponent(S.id) + '/report'); const url = URL.createObjectURL(await response.blob()); const a = document.createElement('a'); a.href = url; a.download = 'assessment-' + S.id + '.md'; a.click(); setTimeout(() => URL.revokeObjectURL(url), 1000); return; } if (name === 'delete' && can('delete') && window.confirm(L('confirmDelete'))) { S.busy = true; ++S.epoch; try { await api('/' + encodeURIComponent(S.id), { method: 'DELETE' }); S.id = ''; S.task = null; closeDrawer('da-inspector'); } finally { S.busy = false; } return await refresh(); } if (name === 'more-receipts' || name === 'previous-receipts') { S.receiptOffset = Math.max(0, S.receiptOffset + (name === 'more-receipts' ? 50 : -50)); return await refresh(); } } catch (error) { notice(error.message, true); } } - window.DeepAssessments = { init() { mount(); void refresh(); if (!S.timer) S.timer = setInterval(() => { if ($('page-deep-assessments')?.classList.contains('active') && !document.hidden) void refresh(); }, 4000); }, refresh }; + window.DeepAssessments = { init() { mount(); applyRoute(); void refresh(); if (!S.timer) S.timer = setInterval(() => { if ($('page-deep-assessments')?.classList.contains('active') && !document.hidden) void refresh(); }, 4000); }, fromLocation() { mount(); if (applyRoute()) void refresh(); }, refresh }; })(); diff --git a/web/static/js/router.js b/web/static/js/router.js index 67e8bf7d..0b121dfb 100644 --- a/web/static/js/router.js +++ b/web/static/js/router.js @@ -3,7 +3,7 @@ let currentPage = null; /** 对话、漏洞管理和设置页切换时保留查询串(会话 ID 或设置分区)。 */ function buildHashForPage(pageId) { - if (pageId !== 'chat' && pageId !== 'vulnerabilities' && pageId !== 'settings') { + if (pageId !== 'chat' && pageId !== 'vulnerabilities' && pageId !== 'settings' && pageId !== 'deep-assessments') { return pageId; } const full = window.location.hash.slice(1); @@ -653,7 +653,7 @@ document.addEventListener('DOMContentLoaded', function() { // 与首屏解析同一套别名:#system-update 落到系统设置页的「一键更新」分区。 const settingsSection = pageId === 'system-update' ? 'update' : pageId === 'settings' && new URLSearchParams(hashParts.slice(1).join('?')).get('section') === 'token-usage' ? 'token-usage' : ''; if (settingsSection) pageId = 'settings'; - if (pageId && ['dashboard', 'chat', 'hitl', 'tool-guard', 'asset-overview', 'asset-library', 'info-collect', 'projects', 'tasks', 'workflows', 'vulnerabilities', 'webshell', 'chat-files', 'mcp-monitor', 'mcp-management', 'knowledge-management', 'knowledge-retrieval-logs', 'roles-management', 'platform-rbac', 'skills-monitor', 'skills-management', 'agents-management', 'settings', 'c2-listeners', 'c2-sessions', 'c2-tasks', 'c2-payloads', 'c2-events', 'c2-profiles'].includes(pageId)) { + if (pageId && ['dashboard', 'chat', 'hitl', 'tool-guard', 'asset-overview', 'asset-library', 'info-collect', 'projects', 'tasks', 'deep-assessments', 'workflows', 'vulnerabilities', 'webshell', 'chat-files', 'mcp-monitor', 'mcp-management', 'knowledge-management', 'knowledge-retrieval-logs', 'roles-management', 'platform-rbac', 'skills-monitor', 'skills-management', 'agents-management', 'settings', 'c2-listeners', 'c2-sessions', 'c2-tasks', 'c2-payloads', 'c2-events', 'c2-profiles'].includes(pageId)) { switchPage(pageId); if (settingsSection && typeof switchSettingsSection === 'function') { switchSettingsSection(settingsSection); diff --git a/web/static/js/vulnerability-host-view.test.cjs b/web/static/js/vulnerability-host-view.test.cjs index 62d492cd..a6c08d42 100644 --- a/web/static/js/vulnerability-host-view.test.cjs +++ b/web/static/js/vulnerability-host-view.test.cjs @@ -9,6 +9,7 @@ test('domain export includes exactly the visible records from the loaded page', { id: 'b', target_host: 'www.example.com', target_domain: 'example.com', task_id:'task-b', task_queue_id:'queue' }, { id: 'c', target_host: 'example.net', target_domain: 'example.net' }, { id: 'unknown', target_host: '' }, + { id: 'assessment', assessment_id: 'task-a', assessment_name: 'Assessment', target_host: 'assessment.example.test' }, ]; const downloads = []; const context = vm.createContext({ @@ -25,12 +26,13 @@ test('domain export includes exactly the visible records from the loaded page', ), context); for (const [selection, expected] of [ - ['', ['a', 'b', 'c', 'unknown']], + ['', ['a', 'b', 'c', 'unknown', 'assessment']], ['host:api.example.com', ['a']], ['domain:example.com', ['a', 'b']], ['host:', ['unknown']], ['host:missing.example.com', []], ['task:task-a',['a']], + ['assessment:task-a',['assessment']], ['queue:queue',['a','b']], ]) { context.vulnerabilityBrowserSelection = selection; diff --git a/web/static/js/vulnerability-workspace.js b/web/static/js/vulnerability-workspace.js index a198d4d6..e152e7eb 100644 --- a/web/static/js/vulnerability-workspace.js +++ b/web/static/js/vulnerability-workspace.js @@ -154,6 +154,7 @@ async function openVulnerabilityInspector(id) {
+ ${window.AssessmentFindingLinks ? window.AssessmentFindingLinks.render(v) : ''}
${['overview','evidence','history'].map(tab => ``).join('')}
@@ -216,3 +217,9 @@ function refreshVulnerabilityInspector(id) { else if (!event.shiftKey && document.activeElement === last) { event.preventDefault(); first?.focus(); } }); }); + +// Invalidate an in-flight inspector load when following an assessment source. +window.closeVulnerabilityInspectorForNavigation = function () { + vulnerabilityInspectorRequest++; + closeAppModal('vulnerability-inspector'); +}; diff --git a/web/static/js/vulnerability.js b/web/static/js/vulnerability.js index f971ce22..a27a1c4e 100644 --- a/web/static/js/vulnerability.js +++ b/web/static/js/vulnerability.js @@ -221,6 +221,7 @@ let vulnerabilityFilters = { project_id: '', conversation_id: '', task_id: '', + assessment_id: '', conversation_tag: '', task_tag: '', severity: '', @@ -264,6 +265,7 @@ const VULN_FILTER_CHIP_FIELDS = [ { key: 'project_id', labelKey: null }, { key: 'conversation_id', labelKey: 'vulnerabilityPage.conversationId' }, { key: 'task_id', labelKey: 'vulnerabilityPage.taskOrQueueId' }, + { key: 'assessment_id', labelKey: 'vulnerabilityPage.assessmentTask' }, { key: 'conversation_tag', labelKey: 'vulnerabilityPage.conversationTag' }, { key: 'task_tag', labelKey: 'vulnerabilityPage.taskTag' } ]; @@ -279,13 +281,15 @@ function syncVulnerabilityFiltersFromLocationHash() { const vid = (params.get('id') || '').trim(); const cid = (params.get('conversation_id') || '').trim(); const tid = (params.get('task_id') || '').trim(); + const assessmentID = (params.get('assessment_id') || '').trim(); + if (params.get('view') === 'task') { vulnerabilityView = 'task'; vulnerabilityBrowserSelection = ''; document.querySelectorAll('[data-vuln-view]').forEach(button => button.setAttribute('aria-pressed', String(button.dataset.vulnView === 'task'))); } const sev = (params.get('severity') || '').trim(); const st = (params.get('status') || '').trim(); const convTag = (params.get('conversation_tag') || '').trim(); const taskTag = (params.get('task_tag') || '').trim(); const pid = (params.get('project_id') || '').trim(); const q = (params.get('q') || params.get('search') || '').trim(); - if (!vid && !cid && !tid && !sev && !st && !convTag && !taskTag && !q && !pid) { + if (!vid && !cid && !tid && !sev && !st && !convTag && !taskTag && !q && !pid && !assessmentID) { return; } @@ -294,6 +298,7 @@ function syncVulnerabilityFiltersFromLocationHash() { vulnerabilityFilters.project_id = ''; vulnerabilityFilters.conversation_id = ''; vulnerabilityFilters.task_id = ''; + vulnerabilityFilters.assessment_id = ''; vulnerabilityFilters.conversation_tag = ''; vulnerabilityFilters.task_tag = ''; vulnerabilityFilters.severity = ''; @@ -333,6 +338,7 @@ function syncVulnerabilityFiltersFromLocationHash() { vulnerabilityFilters.conversation_id = cid; if (convEl) convEl.value = cid; } + if (assessmentID) vulnerabilityFilters.assessment_id = assessmentID; if (tid) { vulnerabilityFilters.task_id = tid; if (taskEl) taskEl.value = tid; @@ -456,13 +462,13 @@ function readVulnerabilityFiltersFromForm() { function hasVulnerabilityAdvancedFiltersActive() { const f = vulnerabilityFilters; - return Boolean(f.id || f.conversation_id || f.task_id || f.conversation_tag || f.task_tag); + return Boolean(f.id || f.conversation_id || f.task_id || f.assessment_id || f.conversation_tag || f.task_tag); } function hasAnyVulnerabilityFilterActive() { const f = vulnerabilityFilters; return Boolean( - f.q || f.id || f.project_id || f.conversation_id || f.task_id || f.conversation_tag || f.task_tag || f.severity || f.status + f.q || f.id || f.project_id || f.conversation_id || f.task_id || f.assessment_id || f.conversation_tag || f.task_tag || f.severity || f.status ); } @@ -489,6 +495,7 @@ function updateVulnerabilityLocationHashFromFilters() { ['project_id', f.project_id], ['conversation_id', f.conversation_id], ['task_id', f.task_id], + ['assessment_id', f.assessment_id], ['conversation_tag', f.conversation_tag], ['task_tag', f.task_tag], ['severity', f.severity], @@ -942,6 +949,7 @@ function countVulnerabilityAdvancedFiltersActive() { if (f.id) n++; if (f.conversation_id) n++; if (f.task_id) n++; + if (f.assessment_id) n++; if (f.conversation_tag) n++; if (f.task_tag) n++; return n; @@ -1395,7 +1403,7 @@ function renderVulnerabilities(vulnerabilities, renderOptions) { window.applyTranslations(listContainer); } if (typeof rbacAfterDynamicRender === 'function') rbacAfterDynamicRender(listContainer); - if (exactMatch && typeof openVulnerabilityInspector === 'function') { + if (exactMatch && document.getElementById('page-vulnerabilities')?.classList.contains('active') && typeof openVulnerabilityInspector === 'function') { openVulnerabilityInspector(exactMatch); } updateVulnerabilityListSummary(); @@ -1439,6 +1447,11 @@ function renderVulnerabilityBrowser(vulnerabilities, opts) { rootLabel = vuln.task_queue_title || (vuln.task_queue_id ? vulnT('vulnerabilityPage.taskQueueGroup', {id:vuln.task_queue_id}) : label); flat = !vuln.task_queue_id; + if (!vuln.task_id && vuln.assessment_id) { + rootKey = key = 'assessment:' + vuln.assessment_id; + rootLabel = label = vuln.assessment_name || vuln.assessment_id; + flat = true; + } } if (!groups.has(rootKey)) groups.set(rootKey, {label:rootLabel, children:new Map(), items:[], flat}); const group = groups.get(rootKey); @@ -1525,9 +1538,10 @@ function getVisibleVulnerabilityBrowserItems() { const items = vulnerabilityBrowserRows.filter(vuln => !selection || selection === 'host:' + (vuln.target_host || '') || selection === 'domain:' + (vuln.target_domain || vuln.target_host || '') || + (!vuln.task_id && vuln.assessment_id && selection === 'assessment:' + vuln.assessment_id) || (vuln.task_id && selection === 'task:' + vuln.task_id) || (vuln.task_queue_id && selection === 'queue:' + vuln.task_queue_id) || - (!vuln.task_id && selection === 'tag:' + (vuln.task_tag || '').replace(/^ +| +$/g, ''))); + (!vuln.task_id && !vuln.assessment_id && selection === 'tag:' + (vuln.task_tag || '').replace(/^ +| +$/g, ''))); return Array.from(new Map(items.map(vuln => [vuln.id,vuln])).values()); } @@ -1586,7 +1600,7 @@ function renderVulnerabilityBrowserTable() { initVulnerabilityProjectBindSelects(container); if (typeof rbacAfterDynamicRender === 'function') rbacAfterDynamicRender(container); const exact = items.find(vuln => vulnerabilityFilters.id === vuln.id); - if (exact && typeof openVulnerabilityInspector === 'function') openVulnerabilityInspector(exact.id); + if (exact && document.getElementById('page-vulnerabilities')?.classList.contains('active') && typeof openVulnerabilityInspector === 'function') openVulnerabilityInspector(exact.id); updateVulnerabilityListSummary(); } @@ -1974,6 +1988,7 @@ function clearVulnerabilityFilters() { project_id: '', conversation_id: '', task_id: '', + assessment_id: '', conversation_tag: '', task_tag: '', severity: '', @@ -2295,6 +2310,10 @@ function formatVulnerabilityAsMarkdown(vuln) { markdown += `- **${L('labelTarget')}**: ${vuln.target}\n`; } markdown += `- **${L('labelConversationId')}**: \`${vuln.conversation_id}\`\n`; + if (vuln.assessment_id) { + markdown += `- **${vulnT('vulnerabilityPage.assessmentTask')}**: ${vuln.assessment_name || vuln.assessment_id} (${vuln.assessment_id})\n`; + markdown += `- **${vulnT('vulnerabilityPage.assessmentStep')}**: ${vuln.assessment_step_title || vuln.assessment_step_id} (${vuln.assessment_step_id})\n`; + } if (vuln.task_id) { markdown += `- **${L('labelTaskId')}**: \`${vuln.task_id}\`\n`; } @@ -2350,7 +2369,7 @@ function buildVulnerabilityFilterParams() { if (vulnerabilityFilters.q) { params.append('q', vulnerabilityFilters.q); } - const keys = ['id', 'project_id', 'conversation_id', 'task_id', 'conversation_tag', 'task_tag', 'severity', 'status']; + const keys = ['id', 'project_id', 'conversation_id', 'task_id', 'assessment_id', 'conversation_tag', 'task_tag', 'severity', 'status']; keys.forEach(function (k) { if (vulnerabilityFilters[k]) { params.append(k, vulnerabilityFilters[k]); @@ -2379,7 +2398,7 @@ function triggerTextDownload(fileName, content) { } function hasActiveVulnerabilityFilters() { - const keys = ['q', 'id', 'project_id', 'conversation_id', 'task_id', 'conversation_tag', 'task_tag', 'severity', 'status']; + const keys = ['q', 'id', 'project_id', 'conversation_id', 'task_id', 'assessment_id', 'conversation_tag', 'task_tag', 'severity', 'status']; return keys.some(function (k) { return Boolean(vulnerabilityFilters[k]); }); diff --git a/web/templates/index.html b/web/templates/index.html index a09a4f9f..fcf11df6 100644 --- a/web/templates/index.html +++ b/web/templates/index.html @@ -49,8 +49,8 @@ - - + +