diff --git a/CHANGELOG.md b/CHANGELOG.md index c533c78b..39bed22f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,12 +4,18 @@ ### Added +- 支持通过 `agent.task_timeout_minutes` 配置单代理、多代理、工作流及异步任务执行超时:未配置默认 600 分钟,`0` 表示不限时,负数拒绝加载;续跑保留重新计时行为,单次工具超时仍独立生效。 + +- 漏洞列表的单条下载按钮新增格式选择弹窗,支持 Markdown 与 Word(.docx),Word 下载复用漏洞读取权限并仅包含所选漏洞(#365)。 + - 新增单代理与多代理异步对话 API:接收后返回任务回执,客户端断线不停止执行;支持按用户隔离的幂等提交、持久状态与结果查询、显式取消以及服务重启后的中断状态。同步接口保持兼容。 - 启动时以统一最新 SQLite 定义自动检查全部项目管理表,缺表建表、缺字段补字段,无需维护逐字段迁移列表;保留已有数据和额外表/字段,结构补齐失败回滚并阻止启动。HITL 与通知表纳入统一初始化,历史漏洞外键迁移保留额外列、索引、触发器及依赖记录。 ### Fixed +- 修复 WebShell 批量探活因请求构建异常一直停留在“探活中”的问题;使用连接自身 ID 读取已保存凭据,并在探活失败后恢复按钮、继续处理其他连接。 + - 修复审计 Agent 向不支持 thinking 字段的兼容网关发起请求失败的问题;支持独立兼容 profile,并按模型和地址识别默认行为。 - 修复已知支持 `none` 的官方 OpenAI 模型在关闭推理后仍使用服务端默认推理的问题(#366):按提供商、端点和模型发送并保留显式关闭参数,覆盖 Planner 和强制工具选择;保留 DeepSeek 与第三方兼容网关行为,并明确提示需要 Responses 的工具调用限制。 diff --git a/config.example.yaml b/config.example.yaml index 71ce90bc..3880e5a2 100644 --- a/config.example.yaml +++ b/config.example.yaml @@ -165,6 +165,8 @@ shodan: # Agent 配置 # 达到最大迭代次数时,AI 会自动总结测试结果 agent: + # 修改后重启服务,对新任务生效;例如 1440 = 24 小时,单次工具超时独立生效。 + task_timeout_minutes: 600 # 任务执行超时(分钟);未配置=600,0=不限时,负数无效;续跑重新计时 max_iterations: 12000 # 全局最大迭代次数(单代理 / Deep / Supervisor / Plan-Execute 主执行器 / 子代理均沿用;agents/*.md 中 max_iterations>0 可单独覆盖) tool_timeout_minutes: 60 # 单次工具执行最大时长(分钟),超时自动终止;0 表示不限制(不推荐,易出现长时间挂起) tool_wait_timeout_seconds: 300 # 工具本轮最多等待(秒);到时返回 execution_id,worker 继续后台执行,可用 wait_tool_execution 继续等待;0=等到完成 diff --git a/docs/en-US/word-reports.md b/docs/en-US/word-reports.md new file mode 100644 index 00000000..5271cc0b --- /dev/null +++ b/docs/en-US/word-reports.md @@ -0,0 +1,11 @@ +# Vulnerability report download + +Click the download icon beside a vulnerability. A dialog offers **Markdown (.md)** and **Word (.docx)**. Choosing a format downloads only that finding. Cancel or Escape dismisses the dialog without downloading. A failed download leaves the dialog available for retry. + +Markdown retains the existing content, UI language and filename. Word includes the selected finding's metadata, description, prerequisites, reproduction steps, evidence, impact, remediation and retest records. Original statuses remain intact. Evidence is plain text; embedded HTML, Markdown formatting and screenshots are not rendered. + +The feature creates no automatic tasks, database schema changes or stored report artifacts. No Office, Python or Pandoc installation is required on the server. The Word viewer needs Chinese font support. + +Word uses `GET /api/vulnerabilities/:id/download?format=docx`, authorized with `vulnerability:read` and the finding's resource scope. No file-management permission is needed. The endpoint also accepts `format=md`. Unsupported formats return 400, missing records 404 and unauthorized access 403. Word body input is limited to 8 MiB. + +Existing page-level Markdown batch export is unchanged. diff --git a/docs/zh-CN/word-reports.md b/docs/zh-CN/word-reports.md new file mode 100644 index 00000000..93b6655f --- /dev/null +++ b/docs/zh-CN/word-reports.md @@ -0,0 +1,11 @@ +# 漏洞报告下载 + +在漏洞管理列表中,点击每条漏洞右侧的下载图标,弹窗选择 **Markdown(.md)** 或 **Word(.docx)**。选择后下载该条漏洞,取消或按 Esc 不会下载。下载失败时保留弹窗,可重新选择。 + +Markdown 沿用现有内容、界面语言与文件名。Word 包含所选漏洞的基本信息、描述、前置条件、复现步骤、证据、影响、修复建议和复测记录;保留原始状态,待确认或误报不会改写为已确认漏洞。证据作为纯文本导出,不解析其中的 HTML 或 Markdown,也不自动嵌入截图。 + +此功能不配置自动生成任务,不修改数据库结构,也不保存额外的报告产物。服务器无需安装 Office、Python 或 Pandoc;查看 Word 文件的软件需要中文字体。 + +Word 下载使用 `GET /api/vulnerabilities/:id/download?format=docx`,要求 `vulnerability:read` 及对应漏洞的资源访问范围,无需额外的文件管理权限。接口也支持 `format=md`,格式参数不合法返回 400,不存在的记录返回 404,越权请求返回 403。Word 正文限制为 8 MiB,超出时返回生成失败。 + +原有页面级 Markdown 批量导出保持不变。 diff --git a/internal/app/app.go b/internal/app/app.go index b7b2d8ff..891c22c1 100644 --- a/internal/app/app.go +++ b/internal/app/app.go @@ -1333,6 +1333,7 @@ func setupRoutes( protected.GET("/vulnerability-alerts/subscription", vulnerabilityHandler.GetMyAlertSubscription) protected.PUT("/vulnerability-alerts/subscription", vulnerabilityHandler.UpdateMyAlertSubscription) protected.GET("/vulnerabilities/:id", vulnerabilityHandler.GetVulnerability) + protected.GET("/vulnerabilities/:id/download", vulnerabilityHandler.DownloadVulnerability) protected.POST("/vulnerabilities", vulnerabilityHandler.CreateVulnerability) protected.POST("/vulnerabilities/:id/retest", vulnerabilityHandler.CreateRetest) protected.PUT("/vulnerabilities/:id", vulnerabilityHandler.UpdateVulnerability) diff --git a/internal/config/agent_timeout.go b/internal/config/agent_timeout.go new file mode 100644 index 00000000..5e3efe85 --- /dev/null +++ b/internal/config/agent_timeout.go @@ -0,0 +1,27 @@ +package config + +import ( + "fmt" + "time" +) + +// EffectiveTaskTimeout returns the execution budget for each task segment. +// An omitted value retains the historical ten-hour limit; zero disables it. +func (a AgentConfig) EffectiveTaskTimeout() time.Duration { + if a.TaskTimeoutMinutes == nil { + return 600 * time.Minute + } + return time.Duration(*a.TaskTimeoutMinutes) * time.Minute +} + +func (a AgentConfig) validateTaskTimeout() error { + if a.TaskTimeoutMinutes == nil { + return nil + } + const maxMinutes = int64((1<<63 - 1) / time.Minute) + minutes := int64(*a.TaskTimeoutMinutes) + if minutes < 0 || minutes > maxMinutes { + return fmt.Errorf("agent.task_timeout_minutes must be between 0 and %d minutes", maxMinutes) + } + return nil +} diff --git a/internal/config/agent_timeout_test.go b/internal/config/agent_timeout_test.go new file mode 100644 index 00000000..4a1e7412 --- /dev/null +++ b/internal/config/agent_timeout_test.go @@ -0,0 +1,61 @@ +package config + +import ( + "os" + "path/filepath" + "strings" + "testing" + "time" + + "gopkg.in/yaml.v3" +) + +func TestLoadTaskTimeout(t *testing.T) { + for _, tc := range []struct { + name, yaml string + want time.Duration + invalid bool + }{ + {"absent agent", "{}", 600 * time.Minute, false}, + {"absent field", "agent: {}", 600 * time.Minute, false}, + {"custom", "agent:\n task_timeout_minutes: 1440", 24 * time.Hour, false}, + {"unlimited", "agent:\n task_timeout_minutes: 0", 0, false}, + {"negative", "agent:\n task_timeout_minutes: -1", 0, true}, + {"overflow", "agent:\n task_timeout_minutes: 153722868", 0, true}, + } { + t.Run(tc.name, func(t *testing.T) { + path := filepath.Join(t.TempDir(), "config.yaml") + if err := os.WriteFile(path, []byte(tc.yaml), 0600); err != nil { + t.Fatal(err) + } + cfg, err := Load(path) + if tc.invalid { + if err == nil || !strings.Contains(err.Error(), "agent.task_timeout_minutes") { + t.Fatalf("expected field validation error, got %v", err) + } + return + } + if err != nil { + t.Fatal(err) + } + if got := cfg.Agent.EffectiveTaskTimeout(); got != tc.want { + t.Fatalf("timeout = %v, want %v", got, tc.want) + } + // YAML saves must preserve explicit zero as distinct from omission. + data, err := yaml.Marshal(cfg) + if err != nil { + t.Fatal(err) + } + if err := os.WriteFile(path, data, 0600); err != nil { + t.Fatal(err) + } + again, err := Load(path) + if err != nil { + t.Fatal(err) + } + if again.Agent.EffectiveTaskTimeout() != tc.want { + t.Fatal("timeout changed after save/load") + } + }) + } +} diff --git a/internal/config/config.go b/internal/config/config.go index f29d41d2..700306bd 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -1118,13 +1118,14 @@ type DatabaseConfig struct { } type AgentConfig struct { - MaxIterations int `yaml:"max_iterations" json:"max_iterations"` - ToolTimeoutMinutes int `yaml:"tool_timeout_minutes" json:"tool_timeout_minutes"` // 单次工具执行最大时长(分钟),超时自动终止,防止长时间挂起;0 表示不限制(不推荐) - ToolWaitTimeoutSeconds int `yaml:"tool_wait_timeout_seconds" json:"tool_wait_timeout_seconds"` // 工具本轮等待秒数;到时返回 execution_id,worker 继续后台执行;0 表示等到完成 - ExternalMCPMaxConcurrentPerServer int `yaml:"external_mcp_max_concurrent_per_server" json:"external_mcp_max_concurrent_per_server"` // 单个外部 MCP server 同时运行的工具数;0 表示默认 2 - ExternalMCPMaxConcurrentTotal int `yaml:"external_mcp_max_concurrent_total" json:"external_mcp_max_concurrent_total"` // 所有外部 MCP 工具全局并发;0 表示默认 16 - ExternalMCPCircuitFailureThreshold int `yaml:"external_mcp_circuit_failure_threshold" json:"external_mcp_circuit_failure_threshold"` // 单个 MCP server 连续失败多少次后打开熔断;0 表示默认 3;负数关闭 - ExternalMCPCircuitCooldownSeconds int `yaml:"external_mcp_circuit_cooldown_seconds" json:"external_mcp_circuit_cooldown_seconds"` // 熔断后冷却秒数;0 表示默认 60 + TaskTimeoutMinutes *int `yaml:"task_timeout_minutes,omitempty" json:"task_timeout_minutes,omitempty"` // nil=600 minutes; 0=unlimited + MaxIterations int `yaml:"max_iterations" json:"max_iterations"` + ToolTimeoutMinutes int `yaml:"tool_timeout_minutes" json:"tool_timeout_minutes"` // 单次工具执行最大时长(分钟),超时自动终止,防止长时间挂起;0 表示不限制(不推荐) + ToolWaitTimeoutSeconds int `yaml:"tool_wait_timeout_seconds" json:"tool_wait_timeout_seconds"` // 工具本轮等待秒数;到时返回 execution_id,worker 继续后台执行;0 表示等到完成 + ExternalMCPMaxConcurrentPerServer int `yaml:"external_mcp_max_concurrent_per_server" json:"external_mcp_max_concurrent_per_server"` // 单个外部 MCP server 同时运行的工具数;0 表示默认 2 + ExternalMCPMaxConcurrentTotal int `yaml:"external_mcp_max_concurrent_total" json:"external_mcp_max_concurrent_total"` // 所有外部 MCP 工具全局并发;0 表示默认 16 + ExternalMCPCircuitFailureThreshold int `yaml:"external_mcp_circuit_failure_threshold" json:"external_mcp_circuit_failure_threshold"` // 单个 MCP server 连续失败多少次后打开熔断;0 表示默认 3;负数关闭 + ExternalMCPCircuitCooldownSeconds int `yaml:"external_mcp_circuit_cooldown_seconds" json:"external_mcp_circuit_cooldown_seconds"` // 熔断后冷却秒数;0 表示默认 60 // ShellNoOutputTimeoutSeconds execute/exec 无任何 stdout/stderr 时的空闲终止秒数(通用防挂死,不维护命令黑名单);0=默认 300(5 分钟);-1=关闭。 ShellNoOutputTimeoutSeconds int `yaml:"shell_no_output_timeout_seconds" json:"shell_no_output_timeout_seconds"` // WorkspaceRootDir 会话工作目录根路径(curl/wget 下载、read_file/glob/grep 本地分析);空=tmp/workspace,其下按 projects/{id} 或 conversations/{id} 隔离。 @@ -1658,6 +1659,9 @@ func Load(path string) (*Config, error) { if err := yaml.Unmarshal(data, &cfg); err != nil { return nil, fmt.Errorf("解析配置文件失败: %w", err) } + if err := cfg.Agent.validateTaskTimeout(); err != nil { + return nil, err + } if cfg.ToolGuard != nil { if err := validateToolGuardYAML(data); err != nil { return nil, fmt.Errorf("调用拦截配置无效: %w", err) diff --git a/internal/handler/async_agent_runs.go b/internal/handler/async_agent_runs.go index e2a12ec2..ce25df11 100644 --- a/internal/handler/async_agent_runs.go +++ b/internal/handler/async_agent_runs.go @@ -10,7 +10,6 @@ import ( "net/http" "strings" "sync" - "time" "cyberstrike-ai/internal/database" "cyberstrike-ai/internal/mcp" @@ -98,7 +97,7 @@ func (h *AgentHandler) submitAgentRunWithExecutor(c *gin.Context, multi bool, ex return } base, cancel := context.WithCancelCause(detachedAgentContext(c.Request.Context())) - ctx, timeoutCancel := context.WithTimeout(base, 600*time.Minute) + ctx, timeoutCancel := h.newTaskContext(base) task, err := h.tasks.StartTask(prep.ConversationID, req.Message, cancel) if err != nil { timeoutCancel() diff --git a/internal/handler/eino_empty_response_continue.go b/internal/handler/eino_empty_response_continue.go index 2c57df86..a946feaa 100644 --- a/internal/handler/eino_empty_response_continue.go +++ b/internal/handler/eino_empty_response_continue.go @@ -19,7 +19,7 @@ func (h *AgentHandler) rebindEinoRunningTask(parent context.Context, conversatio } baseCtx, cancelWithCause := context.WithCancelCause(detachedAgentContext(parent)) h.tasks.BindTaskCancel(conversationID, cancelWithCause) - taskCtx, newTimeoutCancel := context.WithTimeout(baseCtx, 600*time.Minute) + taskCtx, newTimeoutCancel := h.newTaskContext(baseCtx) h.tasks.UpdateTaskStatus(conversationID, "running") return baseCtx, cancelWithCause, taskCtx, newTimeoutCancel } diff --git a/internal/handler/eino_single_agent.go b/internal/handler/eino_single_agent.go index b3ed6207..3701190b 100644 --- a/internal/handler/eino_single_agent.go +++ b/internal/handler/eino_single_agent.go @@ -166,7 +166,7 @@ func (h *AgentHandler) EinoSingleAgentLoopStream(c *gin.Context) { var runErr error baseCtx, cancelWithCause = context.WithCancelCause(detachedAgentContext(c.Request.Context())) - taskCtx, timeoutCancel := context.WithTimeout(baseCtx, 600*time.Minute) + taskCtx, timeoutCancel := h.newTaskContext(baseCtx) if startedTask, err := h.tasks.StartTask(conversationID, req.Message, cancelWithCause); err != nil { var errorMsg string @@ -327,7 +327,7 @@ func (h *AgentHandler) EinoSingleAgentLoopStream(c *gin.Context) { timeoutCancel() baseCtx, cancelWithCause = context.WithCancelCause(detachedAgentContext(baseCtx)) h.tasks.BindTaskCancel(conversationID, cancelWithCause) - taskCtx, timeoutCancel = context.WithTimeout(baseCtx, 600*time.Minute) + taskCtx, timeoutCancel = h.newTaskContext(baseCtx) h.tasks.UpdateTaskStatus(conversationID, "running") continue } @@ -458,7 +458,7 @@ func (h *AgentHandler) EinoSingleAgentLoop(c *gin.Context) { baseCtx, cancelWithCause := context.WithCancelCause(c.Request.Context()) defer cancelWithCause(nil) - taskCtx, timeoutCancel := context.WithTimeout(baseCtx, 600*time.Minute) + taskCtx, timeoutCancel := h.newTaskContext(baseCtx) defer timeoutCancel() jsonTask, startErr := h.tasks.StartTask(prep.ConversationID, req.Message, cancelWithCause) if startErr != nil { diff --git a/internal/handler/multi_agent.go b/internal/handler/multi_agent.go index 6e9ecfa3..912de564 100644 --- a/internal/handler/multi_agent.go +++ b/internal/handler/multi_agent.go @@ -173,7 +173,7 @@ func (h *AgentHandler) MultiAgentLoopStream(c *gin.Context) { var runErr error baseCtx, cancelWithCause = context.WithCancelCause(detachedAgentContext(c.Request.Context())) - taskCtx, timeoutCancel := context.WithTimeout(baseCtx, 600*time.Minute) + taskCtx, timeoutCancel := h.newTaskContext(baseCtx) if startedTask, err := h.tasks.StartTask(conversationID, req.Message, cancelWithCause); err != nil { var errorMsg string @@ -341,7 +341,7 @@ func (h *AgentHandler) MultiAgentLoopStream(c *gin.Context) { timeoutCancel() baseCtx, cancelWithCause = context.WithCancelCause(detachedAgentContext(baseCtx)) h.tasks.BindTaskCancel(conversationID, cancelWithCause) - taskCtx, timeoutCancel = context.WithTimeout(baseCtx, 600*time.Minute) + taskCtx, timeoutCancel = h.newTaskContext(baseCtx) h.tasks.UpdateTaskStatus(conversationID, "running") continue } @@ -477,7 +477,7 @@ func (h *AgentHandler) MultiAgentLoop(c *gin.Context) { baseCtx, cancelWithCause := context.WithCancelCause(c.Request.Context()) defer cancelWithCause(nil) - taskCtx, timeoutCancel := context.WithTimeout(baseCtx, 600*time.Minute) + taskCtx, timeoutCancel := h.newTaskContext(baseCtx) defer timeoutCancel() jsonTask, startErr := h.tasks.StartTask(prep.ConversationID, req.Message, cancelWithCause) if startErr != nil { diff --git a/internal/handler/task_deadline.go b/internal/handler/task_deadline.go index 37d7c8be..0448b261 100644 --- a/internal/handler/task_deadline.go +++ b/internal/handler/task_deadline.go @@ -3,6 +3,8 @@ package handler import ( "context" "errors" + + "cyberstrike-ai/internal/config" ) // taskDeadlineExceeded distinguishes the task's deadline from a child operation's @@ -11,3 +13,17 @@ import ( func taskDeadlineExceeded(taskCtx context.Context) bool { return taskCtx != nil && errors.Is(taskCtx.Err(), context.DeadlineExceeded) } + +// newTaskContext starts a fresh execution budget. Unlimited tasks remain cancellable. +// A parent's cancellation or earlier deadline is always respected. +func (h *AgentHandler) newTaskContext(parent context.Context) (context.Context, context.CancelFunc) { + var cfg config.AgentConfig + if h.config != nil { + cfg = h.config.Agent + } + timeout := cfg.EffectiveTaskTimeout() + if timeout == 0 { + return context.WithCancel(parent) + } + return context.WithTimeout(parent, timeout) +} diff --git a/internal/handler/task_timeout_test.go b/internal/handler/task_timeout_test.go new file mode 100644 index 00000000..3288500d --- /dev/null +++ b/internal/handler/task_timeout_test.go @@ -0,0 +1,122 @@ +package handler + +import ( + "context" + "errors" + "gopkg.in/yaml.v3" + "strconv" + "testing" + "time" + + "cyberstrike-ai/internal/config" +) + +func TestConfiguredTaskContext(t *testing.T) { + for _, minutes := range []int{-1, 0, 1440} { + t.Run(taskTimeoutCaseName(minutes), func(t *testing.T) { + h := &AgentHandler{} + want := 600 * time.Minute + if minutes >= 0 { + h.config = &config.Config{Agent: config.AgentConfig{TaskTimeoutMinutes: &minutes}} + want = time.Duration(minutes) * time.Minute + } + parent, cancelParent := context.WithCancelCause(context.Background()) + defer cancelParent(nil) + before := time.Now() + ctx, cancel := h.newTaskContext(parent) + defer cancel() + deadline, ok := ctx.Deadline() + if want == 0 { + if ok { + t.Fatal("unlimited task has a deadline") + } + } else if !ok || deadline.Before(before.Add(want)) || deadline.After(time.Now().Add(want)) { + t.Fatalf("unexpected deadline %v", deadline) + } + cancelParent(ErrTaskCancelled) + if !errors.Is(context.Cause(ctx), ErrTaskCancelled) { + t.Fatal("parent cancellation lost") + } + + ctx, cancel = h.newTaskContext(context.Background()) + cancel() + if !errors.Is(ctx.Err(), context.Canceled) { + t.Fatal("explicit cancellation lost") + } + + early := time.Now().Add(time.Minute) + parentDeadline, stop := context.WithDeadline(context.Background(), early) + defer stop() + ctx, cancel = h.newTaskContext(parentDeadline) + defer cancel() + if got, ok := ctx.Deadline(); !ok || !got.Equal(early) { + t.Fatal("earlier parent deadline lost") + } + }) + } +} + +func taskTimeoutCaseName(minutes int) string { + if minutes < 0 { + return "default" + } + if minutes == 0 { + return "unlimited" + } + return "custom" +} + +func TestRebindTaskRestartsConfiguredBudget(t *testing.T) { + for _, minutes := range []int{0, 1440} { + t.Run(taskTimeoutCaseName(minutes), func(t *testing.T) { + h := &AgentHandler{config: &config.Config{Agent: config.AgentConfig{TaskTimeoutMinutes: &minutes}}, tasks: NewAgentTaskManager()} + base, stop := context.WithCancelCause(context.Background()) + defer stop(nil) + if _, err := h.tasks.StartTask("resume", "test", stop); err != nil { + t.Fatal(err) + } + expired, cancelExpired := context.WithDeadline(base, time.Now().Add(-time.Second)) + before := time.Now() + _, stopNew, resumed, cancelNew := h.rebindEinoRunningTask(expired, "resume", cancelExpired) + defer stopNew(nil) + defer cancelNew() + if resumed.Err() != nil { + t.Fatalf("resumed task inherited expired context: %v", resumed.Err()) + } + deadline, ok := resumed.Deadline() + if minutes == 0 { + if ok { + t.Fatal("unlimited resume has deadline") + } + } else if !ok || deadline.Before(before.Add(24*time.Hour)) || deadline.After(time.Now().Add(24*time.Hour)) { + t.Fatalf("resume budget was not reset: %v", deadline) + } + stopNew(ErrTaskCancelled) + if !errors.Is(context.Cause(resumed), ErrTaskCancelled) { + t.Fatal("resumed task cannot be cancelled") + } + }) + } +} + +// Saving unrelated settings must not erase a manually configured task budget. +func TestSettingsSavePreservesTaskTimeout(t *testing.T) { + for _, value := range []string{"0", "1440"} { + var doc yaml.Node + if err := yaml.Unmarshal([]byte("agent:\n task_timeout_minutes: "+value+"\n"), &doc); err != nil { + t.Fatal(err) + } + updateAgentConfig(&doc, config.AgentConfig{MaxIterations: 100}) + data, err := yaml.Marshal(&doc) + if err != nil { + t.Fatal(err) + } + var cfg config.Config + if err := yaml.Unmarshal(data, &cfg); err != nil { + t.Fatal(err) + } + if cfg.Agent.TaskTimeoutMinutes == nil || strconv.Itoa(*cfg.Agent.TaskTimeoutMinutes) != value { + t.Fatalf("settings save changed timeout: %s", data) + } + } +} diff --git a/internal/handler/vulnerability_download.go b/internal/handler/vulnerability_download.go new file mode 100644 index 00000000..e1ddb685 --- /dev/null +++ b/internal/handler/vulnerability_download.go @@ -0,0 +1,83 @@ +package handler + +import ( + "mime" + "net/http" + "strconv" + "strings" + "time" + + "cyberstrike-ai/internal/database" + "cyberstrike-ai/internal/report" + "cyberstrike-ai/internal/security" + "github.com/gin-gonic/gin" + "go.uber.org/zap" +) + +// DownloadVulnerability exports exactly one record under the same RBAC boundary +// as its detail view. It does not create artifacts or require files permissions. +func (h *VulnerabilityHandler) DownloadVulnerability(c *gin.Context) { + format := c.DefaultQuery("format", "docx") + if format != "docx" && format != "md" { + c.JSON(400, gin.H{"error": "format must be md or docx"}) + return + } + session, ok := security.CurrentSession(c) + if !ok || session.UserID == "" { + c.JSON(401, gin.H{"error": "unauthorized"}) + return + } + if !security.SessionHasPermission(c, "vulnerability:read") || !h.db.UserCanAccessResource(session.UserID, session.ScopeFor("vulnerability:read"), "vulnerability", c.Param("id")) { + c.JSON(403, gin.H{"error": "无权访问该漏洞"}) + return + } + var exists bool + if err := h.db.QueryRow("SELECT EXISTS(SELECT 1 FROM vulnerabilities WHERE id=?)", c.Param("id")).Scan(&exists); err != nil { + c.JSON(500, gin.H{"error": "读取漏洞失败"}) + return + } + if !exists { + c.JSON(404, gin.H{"error": "漏洞不存在"}) + return + } + v, err := h.db.GetVulnerability(c.Param("id")) + if err != nil { + h.logger.Warn("读取漏洞下载记录失败", zap.Error(err)) + c.JSON(500, gin.H{"error": "读取漏洞失败"}) + return + } + var data []byte + contentType := "text/markdown; charset=utf-8" + if format == "md" { + var b strings.Builder + appendVulnerabilityMarkdown(&b, v, "#") + data = []byte(b.String()) + } else { + template := report.DefaultTemplate() + // A long vulnerability title remains intact in the detail; the cover is bounded. + title := []rune(v.Title) + if len(title) > 180 { + title = title[:180] + } + template.Title = string(title) + " 漏洞报告" + template.Scope = v.Target + template.Introduction = "本报告记录该漏洞的描述、证据与修复建议。" + template.IncludeSummary = false + data, err = report.Render(template, report.Snapshot{ConversationID: v.ConversationID, ConversationTitle: v.ConversationTag, GeneratedAt: time.Now(), Findings: []*database.Vulnerability{v}}) + if err != nil { + h.logger.Warn("生成漏洞 Word 报告失败", zap.Error(err)) + c.JSON(500, gin.H{"error": "生成 Word 报告失败"}) + return + } + contentType = report.MIME + } + title := []rune(sanitizeExportName(v.Title)) + if len(title) > 50 { + title = title[:50] + } + filename := string(title) + "_" + v.ID + "." + format + c.Header("Content-Disposition", mime.FormatMediaType("attachment", map[string]string{"filename": filename})) + c.Header("Content-Length", strconv.Itoa(len(data))) + c.Header("Cache-Control", "no-store") + c.Data(http.StatusOK, contentType, data) +} diff --git a/internal/handler/vulnerability_download_test.go b/internal/handler/vulnerability_download_test.go new file mode 100644 index 00000000..328b83c8 --- /dev/null +++ b/internal/handler/vulnerability_download_test.go @@ -0,0 +1,108 @@ +package handler + +import ( + "archive/zip" + "bytes" + "io" + "mime" + "net/http/httptest" + "path/filepath" + "strings" + "testing" + + "cyberstrike-ai/internal/database" + "cyberstrike-ai/internal/report" + "cyberstrike-ai/internal/security" + "github.com/gin-gonic/gin" + "go.uber.org/zap" +) + +func TestSingleVulnerabilityDownloadFormatsAndIsolation(t *testing.T) { + gin.SetMode(gin.TestMode) + db, err := database.NewDB(filepath.Join(t.TempDir(), "download.db"), zap.NewNop()) + if err != nil { + t.Fatal(err) + } + defer db.Close() + user, err := db.CreateRBACUser("report-reader", "Reader", "hash", true, nil) + if err != nil { + t.Fatal(err) + } + selected, err := db.CreateVulnerability(&database.Vulnerability{Title: "中文漏洞 <测试>", Severity: "high", Status: "open", Evidence: "sample & value", Recommendation: "修复权限验证"}) + if err != nil { + t.Fatal(err) + } + other, err := db.CreateVulnerability(&database.Vulnerability{Title: "other-secret-finding", Severity: "low", Status: "confirmed"}) + if err != nil { + t.Fatal(err) + } + if err = db.SetResourceOwner("vulnerability", selected.ID, user.ID); err != nil { + t.Fatal(err) + } + h := NewVulnerabilityHandler(db, zap.NewNop()) + session := security.Session{UserID: user.ID, Scope: database.RBACScopeAll, Permissions: map[string]bool{"vulnerability:read": true}, PermissionScopes: map[string]string{"vulnerability:read": database.RBACScopeOwn}} + request := func(id, format string, s security.Session) *httptest.ResponseRecorder { + r := gin.New() + r.Use(func(c *gin.Context) { c.Set(security.ContextSessionKey, s) }, security.RBACMiddleware(db)) + r.GET("/api/vulnerabilities/:id/download", h.DownloadVulnerability) + w := httptest.NewRecorder() + r.ServeHTTP(w, httptest.NewRequest("GET", "/api/vulnerabilities/"+id+"/download?format="+format, nil)) + return w + } + for _, format := range []string{"md", "docx"} { + w := request(selected.ID, format, session) + if w.Code != 200 { + t.Fatalf("%s: %d %s", format, w.Code, w.Body) + } + _, params, err := mime.ParseMediaType(w.Header().Get("Content-Disposition")) + if err != nil || !strings.Contains(params["filename"], "中文漏洞") || !strings.HasSuffix(params["filename"], "."+format) { + t.Fatalf("filename %v %v", params, err) + } + content := w.Body.String() + if format == "docx" { + if w.Header().Get("Content-Type") != report.MIME { + t.Fatal("incorrect DOCX MIME") + } + z, err := zip.NewReader(bytes.NewReader(w.Body.Bytes()), int64(w.Body.Len())) + if err != nil { + t.Fatal(err) + } + for _, f := range z.File { + if f.Name == "word/document.xml" { + r, err := f.Open() + if err != nil { + t.Fatal(err) + } + b, err := io.ReadAll(r) + r.Close() + if err != nil { + t.Fatal(err) + } + content = string(b) + } + } + if !strings.Contains(content, "<evidence> & value") { + t.Fatal("evidence not escaped") + } + } + if !strings.Contains(content, selected.ID) || !strings.Contains(content, "修复权限验证") || strings.Contains(content, "other-secret-finding") { + t.Fatal("wrong finding exported") + } + } + if w := request(other.ID, "docx", session); w.Code != 403 { + t.Fatalf("unrelated global scope widened download: %d", w.Code) + } + denied := session + denied.Permissions = map[string]bool{} + if w := request(selected.ID, "docx", denied); w.Code != 403 { + t.Fatalf("missing permission: %d", w.Code) + } + if w := request(selected.ID, "pdf", session); w.Code != 400 { + t.Fatalf("invalid format: %d", w.Code) + } + all := session + all.PermissionScopes = nil + if w := request("missing", "docx", all); w.Code != 404 { + t.Fatalf("missing record: %d", w.Code) + } +} diff --git a/internal/handler/workflow_integration.go b/internal/handler/workflow_integration.go index 3c40ea8c..042a3e8b 100644 --- a/internal/handler/workflow_integration.go +++ b/internal/handler/workflow_integration.go @@ -88,7 +88,7 @@ func (h *AgentHandler) runRoleWorkflowStreamIfBound( } baseCtx, cancelWithCause := context.WithCancelCause(detachedAgentContext(c.Request.Context())) defer cancelWithCause(nil) - taskCtx, timeoutCancel := context.WithTimeout(baseCtx, 600*time.Minute) + taskCtx, timeoutCancel := h.newTaskContext(baseCtx) defer timeoutCancel() if startedTask, err := h.tasks.StartTask(conversationID, userMessage, cancelWithCause); err != nil { @@ -231,7 +231,7 @@ func (h *AgentHandler) runRoleWorkflowJSONIfBound(c *gin.Context, req *ChatReque baseCtx, cancelWithCause := context.WithCancelCause(c.Request.Context()) defer cancelWithCause(nil) - taskCtx, timeoutCancel := context.WithTimeout(baseCtx, 600*time.Minute) + taskCtx, timeoutCancel := h.newTaskContext(baseCtx) defer timeoutCancel() if startedTask, err := h.tasks.StartTask(conversationID, userMessage, cancelWithCause); err != nil { diff --git a/internal/report/docx.go b/internal/report/docx.go new file mode 100644 index 00000000..19ef34c3 --- /dev/null +++ b/internal/report/docx.go @@ -0,0 +1,181 @@ +// Package report renders evidence already collected by a conversation into Word. +// It never runs tools, calls an LLM, or interprets template content as code. +package report + +import ( + "archive/zip" + "bytes" + "encoding/xml" + "fmt" + "strings" + "time" + "unicode/utf8" + + "cyberstrike-ai/internal/database" +) + +const MIME = "application/vnd.openxmlformats-officedocument.wordprocessingml.document" + +// Template is intentionally structured: text is literal, not executable markup. +type Template struct { + Title string `json:"title"` + Organization string `json:"organization"` + Scope string `json:"scope"` + Introduction string `json:"introduction"` + IncludeSummary bool `json:"include_summary"` + IncludeEvidence bool `json:"include_evidence"` + IncludeRemediation bool `json:"include_remediation"` +} + +func DefaultTemplate() Template { + return Template{Title: "安全检查报告", Introduction: "本报告汇总当前会话已记录的检查结果,供人工复核与修复跟踪。", IncludeSummary: true, IncludeEvidence: true, IncludeRemediation: true} +} +func (t Template) Validate() error { + if strings.TrimSpace(t.Title) == "" { + return fmt.Errorf("报告标题不能为空") + } + for _, f := range []struct { + name, value string + limit int + }{{"标题", t.Title, 200}, {"单位", t.Organization, 500}, {"检查范围", t.Scope, 10000}, {"章节说明", t.Introduction, 10000}} { + if !utf8.ValidString(f.value) || utf8.RuneCountInString(f.value) > f.limit { + return fmt.Errorf("%s超出长度限制(%d 字)", f.name, f.limit) + } + } + return nil +} + +type Snapshot struct { + ConversationID, ConversationTitle, RunID, Summary string + GeneratedAt time.Time + Findings []*database.Vulnerability +} + +func escaped(s string) string { + // XML 1.0 excludes control characters sometimes found in tool output. + s = strings.Map(func(r rune) rune { + if r == 9 || r == 10 || r == 13 || r >= 0x20 && r <= 0xD7FF || r >= 0xE000 && r <= 0xFFFD || r >= 0x10000 && r <= 0x10FFFF { + return r + } + return -1 + }, s) + var b bytes.Buffer + _ = xml.EscapeText(&b, []byte(s)) + return b.String() +} + +// Render creates a standalone OOXML document with A4 pages and Chinese fonts. +func Render(t Template, s Snapshot) ([]byte, error) { + if err := t.Validate(); err != nil { + return nil, err + } + if len(s.Findings) > 2000 { + return nil, fmt.Errorf("报告超过 2000 条发现限制") + } + size := len(s.Summary) + for _, v := range s.Findings { + if v == nil { + return nil, fmt.Errorf("发现记录不能为空") + } + for _, text := range []string{v.ID, v.Title, v.Description, v.Severity, v.Status, v.Type, v.Target, v.Preconditions, v.ReproSteps, v.Evidence, v.Impact, v.Recommendation, v.RetestNotes, v.RetestLog} { + size += len(text) + } + } + if size > 8*1024*1024 { + return nil, fmt.Errorf("报告正文超过 8 MiB 限制,请缩小范围") + } + var body strings.Builder + p := func(style, text string) { + for _, line := range strings.Split(strings.ReplaceAll(text, "\r\n", "\n"), "\n") { + body.WriteString(`` + escaped(line) + ``) + } + } + field := func(label, value string) { + if strings.TrimSpace(value) == "" { + value = "未记录" + } + p("Normal", label+":"+value) + } + p("Title", t.Title) + if t.Organization != "" { + field("单位", t.Organization) + } + field("生成时间", s.GeneratedAt.Format("2006-01-02 15:04:05 -07:00")) + if s.ConversationID != "" { + field("会话", s.ConversationTitle+"("+s.ConversationID+")") + } + if s.RunID != "" { + field("运行 ID", s.RunID) + } + p("Heading1", "检查范围与说明") + field("检查范围", t.Scope) + p("Normal", t.Introduction) + if len(s.Findings) != 1 { + p("Normal", "本报告保留生成时的记录状态。未记录漏洞不代表目标安全,记录状态、证据充分性及覆盖范围需人工复核。") + p("Heading1", "风险统计") + counts := map[string]int{} + for _, v := range s.Findings { + counts[v.Severity]++ + } + field("发现总数", fmt.Sprint(len(s.Findings))) + for _, severity := range []string{"critical", "high", "medium", "low", "info"} { + field(severity, fmt.Sprint(counts[severity])) + } + p("Normal", "统计包含当前筛选范围内的全部记录;误报、已忽略与待确认记录请结合各项状态判断,不应全部视为已验证漏洞。") + } + if t.IncludeSummary { + p("Heading1", "最终回复(原文,待人工复核)") + field("会话最终回复", s.Summary) + } + if len(s.Findings) == 1 { + p("Heading1", "漏洞详情") + } else { + p("Heading1", "发现详情") + } + if len(s.Findings) == 0 { + p("Normal", "当前范围内没有已记录的漏洞;这不构成安全保证。") + } + for i, v := range s.Findings { + if len(s.Findings) != 1 { + p("Heading2", fmt.Sprintf("%d. %s", i+1, v.Title)) + } else { + p("Heading2", v.Title) + } + for _, f := range [][2]string{{"记录 ID", v.ID}, {"严重程度", v.Severity}, {"记录状态", v.Status}, {"类型", v.Type}, {"目标", v.Target}, {"描述", v.Description}, {"前置条件", v.Preconditions}, {"影响", v.Impact}} { + field(f[0], f[1]) + } + if t.IncludeEvidence { + field("复现步骤", v.ReproSteps) + field("证据 / POC", v.Evidence) + } + if t.IncludeRemediation { + field("修复建议", v.Recommendation) + field("复测方式", v.RetestNotes) + field("复测记录", v.RetestLog) + } + } + body.WriteString(``) + doc := `` + body.String() + `` + files := []struct{ name, content string }{ + {"[Content_Types].xml", ``}, + {"_rels/.rels", ``}, + {"word/_rels/document.xml.rels", ``}, + {"word/document.xml", doc}, + {"word/styles.xml", ``}, + } + var out bytes.Buffer + z := zip.NewWriter(&out) + for _, f := range files { + w, err := z.Create(f.name) + if err != nil { + return nil, err + } + if _, err = w.Write([]byte(f.content)); err != nil { + return nil, err + } + } + if err := z.Close(); err != nil { + return nil, err + } + return out.Bytes(), nil +} diff --git a/internal/report/docx_test.go b/internal/report/docx_test.go new file mode 100644 index 00000000..659bb628 --- /dev/null +++ b/internal/report/docx_test.go @@ -0,0 +1,91 @@ +package report + +import ( + "archive/zip" + "bytes" + "encoding/xml" + "io" + "strings" + "testing" + "time" + + "cyberstrike-ai/internal/database" +) + +func TestWordReportEscapesEvidenceAndHonorsSections(t *testing.T) { + template := DefaultTemplate() + template.Title = "中文报告 & <客户>" + template.IncludeRemediation = false + v := &database.Vulnerability{Title: "待确认发现", Severity: "high", Status: "false_positive", Evidence: " + @@ -137,6 +138,7 @@
中文
English
Русский
+
العربية
@@ -7031,6 +7033,19 @@ + +
+

下载漏洞报告

+

请选择下载格式

+
+ + +
+

+ +
+
+ @@ -7056,7 +7071,8 @@ - + +