From ef89d9e464053f6e38174e2a03a96e33d9174f17 Mon Sep 17 00:00:00 2001
From: Sycun <165354365+Sycun@users.noreply.github.com>
Date: Mon, 2 Nov 2026 22:32:11 +0800
Subject: [PATCH] fix(assessment): bind approvals and enforce scoped execution
boundaries
---
docs/DEEP_ASSESSMENTS.md | 8 +-
docs/DEEP_ASSESSMENT_SECURITY_REVIEW.md | 35 ++++
internal/app/app.go | 4 +-
internal/app/assessment_security_test.go | 88 ++++++++++
internal/app/asset_tools.go | 18 +-
internal/app/asset_tools_test.go | 2 +-
internal/app/mcp_authorization.go | 23 +++
internal/assessment/approval.go | 118 +++++++++++++
internal/assessment/engine.go | 46 +++--
internal/assessment/engine_test.go | 8 +-
internal/assessment/memory.go | 1 +
internal/assessment/runtime.go | 61 +++++--
internal/assessment/security_test.go | 190 +++++++++++++++++++++
internal/assessment/store.go | 15 +-
internal/assessment/types.go | 36 ++--
internal/assessment/worker.go | 40 +++--
internal/database/asset.go | 23 ++-
internal/database/asset_test.go | 46 +++++
internal/handler/assessment.go | 119 ++++++++++---
internal/handler/assessment_config.go | 33 ++++
internal/handler/assessment_config_test.go | 43 +++++
internal/handler/assessment_openapi.go | 6 +-
internal/handler/assessment_test.go | 93 +++++++++-
scripts/assessment-browser-smoke.mjs | 12 +-
web/static/js/assessments.js | 12 +-
25 files changed, 974 insertions(+), 106 deletions(-)
create mode 100644 docs/DEEP_ASSESSMENT_SECURITY_REVIEW.md
create mode 100644 internal/app/assessment_security_test.go
create mode 100644 internal/assessment/approval.go
create mode 100644 internal/assessment/security_test.go
create mode 100644 internal/handler/assessment_config.go
create mode 100644 internal/handler/assessment_config_test.go
diff --git a/docs/DEEP_ASSESSMENTS.md b/docs/DEEP_ASSESSMENTS.md
index 3d50b3ce..cbefa8c5 100644
--- a/docs/DEEP_ASSESSMENTS.md
+++ b/docs/DEEP_ASSESSMENTS.md
@@ -49,10 +49,10 @@
| GET / POST | `/api/assessments` | 分页列表(limit/offset)/ 创建草稿 |
| GET / DELETE | `/api/assessments/:id` | 查询 / 删除非活跃任务 |
| POST | `/api/assessments/:id/control/:action` | `start`、`resume`、`pause`、`stop`、`steer` |
-| POST | `/api/assessments/:id/steps/:stepId/decision` | `{ "approved": true/false }`,仅批准该次调用 |
+| POST | `/api/assessments/:id/steps/:stepId/decision` | `{ "approved": true/false, "approval_id": "当前步骤返回的编号" }`,仅批准该次调用 |
| POST | `/api/assessments/:id/steps/:stepId/retry` | 明确重试受阻步骤,不自动重复外部操作 |
-| GET | `/api/assessments/:id/events?after=0` | 按 ID 增量读取,单页最多 200 条 |
-| POST | `/api/assessments/:id/publish` | `{ "step_id": "…", "index": 0, "kind": "fact|asset|vulnerability" }` |
+| GET | `/api/assessments/:id/events?after=0` | 按 ID 增量读取,单页最多 200 条且约 1 MiB |
+| POST | `/api/assessments/:id/publish` | `{ "step_id": "…", "index": 0, "kind": "fact|asset|vulnerability", "revision": "展示证据的版本" }` |
| GET | `/api/assessments/:id/report` | 下载包含部分结果的 Markdown 报告 |
创建示例(工具名应从 options 中选择):
@@ -87,3 +87,5 @@
### 长程回归场景
`internal/assessment/longrun_test.go` 覆盖慢 Worker、慢规划器、替代路线与退休分支、多轮依赖链、历史长输出尾部检索、跨 Worker 证据、检查点恢复、格式修复和预算边界。均为确定性本地夹具,用于验证机制和避免回归;这些测试不等同于真实模型的漏洞发现率、成本或长时稳定性对标。
+
+安全边界、已修复问题和回归场景见 [深度测评安全复查](DEEP_ASSESSMENT_SECURITY_REVIEW.md)。审批编号和证据版本为必填字段,旧客户端应刷新页面后提交;过期请求返回 409。
diff --git a/docs/DEEP_ASSESSMENT_SECURITY_REVIEW.md b/docs/DEEP_ASSESSMENT_SECURITY_REVIEW.md
new file mode 100644
index 00000000..31ff6a75
--- /dev/null
+++ b/docs/DEEP_ASSESSMENT_SECURITY_REVIEW.md
@@ -0,0 +1,35 @@
+# 深度测评安全复查
+
+范围:独立测评的 HTTP/API → 调度 → 模型输出 → MCP 执行,以及审批、证据发布、项目隔离和前端异步交互。采用源码数据流审查与本地回归夹具,未执行真实目标攻击。
+
+## 已修复的边界问题
+
+| 问题 | 触发条件及影响 | 修复与回归 |
+|---|---|---|
+| 审批请求未绑定具体调用 | 旧页面/重放请求只携带步骤 ID,同一步骤已产生下一次待审批调用时,可能批准非用户所见的调用 | 服务器生成 approval_id,绑定调用参数摘要、执行者;旧编号返回 409。恢复时重新生成待审编号;执行前重新检查审批人有效性与权限;请求、决定和执行日志保留审批编号/摘要/操作者关联 |
+| HITL 权限范围未独立验证 | 同时拥有全局 assessment:write 和仅自身范围的 hitl:write,可能审批其他人的任务 | 两个权限分别检查各自资源范围;审批权限/授权被撤销后,旧批准不能继续使用 |
+| 自动放行记录未跟随策略变化 | 暂停后全局策略改为需要人工审批,旧自动放行状态可能继续有效 | policy/manual 授权分别处理,执行前检查当前策略;切换执行者或恢复运行使旧授权失效 |
+| 运行中证据更新与人工发布竞态 | 人工看到的证据与提交时同一数组位置的内容已不同 | 每份展示证据附带 revision;发布必须携带匹配版本,内容变化返回 409 |
+| 无 owner 的资产被低权限去重回写 | 非全局写用户提交已有无 owner 资产的去重键,原逻辑可能更新该记录 | 非全局导入必须匹配所有者;显式全局操作仍可更新。共享导入入口一并修复 |
+| 项目边界与去重不一致 | 绑定项目的工具修改其他项目资产,或全局角色通过去重把另一项目记录重新绑定 | MCP 资源与目标项目约束统一检查;项目内去重在同一 SQLite 事务核对已有记录归属 |
+| 暂停与后台工具提交竞态 | 工具服务会解耦请求上下文,暂停时若仅取消等待而尚未关闭任务执行入口,可能继续接收新的后台动作 | 暂停/停止返回前同步关闭本地进程入口和 MCP worker 租约;截止时间也关闭入口;取消上下文不得再提交工具 |
+| 前端切换任务的异步窗口 | 切换后新任务 ID 已生效,旧任务按钮仍显示,可能对错误任务发送控制动作 | 切换即清空详情;控制请求仅绑定当前已加载任务 |
+
+## 资源与一致性加固
+
+- 所有测评 JSON 写入口在解析前限制为 128 KiB;超限返回 413。Cookie 形式的浏览器写操作校验来源;显式 Bearer 集成沿用认证/CORS 策略。
+- 模型每轮最多 8 个工具调用,参数最多 64 KiB;调用 ID 要求唯一,压缩过的历史调用 ID 仍被记住。
+- 列表查询在数据库侧剔除步骤轨迹与材料,避免每次列表轮询把全部私有模型轨迹加载并复制到 Go 内存。事件分页同时限制条数和约 1 MiB 总量,游标可继续读取。
+- 模型渠道和 HITL 策略使用与配置写入相同锁下生成的深拷贝快照,避免热更新读取混用不同版本的配置字段。
+- 测评将已授权的项目上下文传递给 MCP,项目资产查询可以使用现有工具,同时保持其他项目隔离;错误结果保留诊断信息,便于规划器解释受阻原因。
+
+## 验证入口
+
+- `internal/assessment/security_test.go`:审批重放、参数与执行者绑定、审批人撤权、策略变化、重复/超量调用、列表及事件分页。
+- `internal/handler/assessment_test.go`:权限范围组合、证据版本竞态、超大请求、写操作来源检查。
+- `internal/handler/assessment_config_test.go`:并发热更新下配置快照一致且不共享可变映射。
+- `internal/app/assessment_security_test.go`:无隐藏会话的真实 MCP/资产工具链、跨项目操作拒绝。
+- `internal/database/asset_test.go`:无 owner 资产写保护、项目内去重的原子归属检查。
+- 浏览器冒烟脚本:精确审批编号、证据版本提交、切换任务时清除旧控制界面。
+
+这不是全项目不存在漏洞的证明。通用 Shell 和外部 MCP 仍继承其宿主权限;自由文本 scope 不构成网络或文件系统沙箱。任务输出可能包含敏感证据,访问和备份应按运行数据管理。真实模型的提示注入抗性和实际长时效果仍需在授权隔离环境中评估。
diff --git a/internal/app/app.go b/internal/app/app.go
index 30ce478c..9a5319d5 100644
--- a/internal/app/app.go
+++ b/internal/app/app.go
@@ -626,7 +626,7 @@ func New(cfg *config.Config, log *logger.Logger, configPath string) (*App, error
if err := assessmentStore.Recover(); err != nil {
return nil, fmt.Errorf("recover assessments: %w", err)
}
- app.assessmentEngine = assessment.NewEngine(assessmentStore, &assessment.CSAIRuntime{DB: db, Agent: agent, Config: cfg, Logger: log.Logger}, log.Logger)
+ app.assessmentEngine = assessment.NewEngine(assessmentStore, &assessment.CSAIRuntime{DB: db, Agent: agent, ConfigSnapshot: configHandler.AssessmentConfigSnapshot, Logger: log.Logger}, log.Logger)
// 设置路由(使用 App 实例以便动态获取 handler)
setupRoutes(
@@ -1011,7 +1011,7 @@ func setupRoutes(
}
}))
{
- assessmentHandler := &handler.AssessmentHandler{Engine: app.assessmentEngine, DB: app.db, Config: app.config, Audit: auditSvc}
+ assessmentHandler := &handler.AssessmentHandler{Engine: app.assessmentEngine, DB: app.db, ConfigSnapshot: configHandler.AssessmentConfigSnapshot, Audit: auditSvc}
protected.GET("/assessments/options", assessmentHandler.Options)
protected.GET("/assessments", assessmentHandler.List)
protected.POST("/assessments", assessmentHandler.Create)
diff --git a/internal/app/assessment_security_test.go b/internal/app/assessment_security_test.go
new file mode 100644
index 00000000..786f9828
--- /dev/null
+++ b/internal/app/assessment_security_test.go
@@ -0,0 +1,88 @@
+package app
+
+import (
+ "context"
+ "path/filepath"
+ "testing"
+
+ "cyberstrike-ai/internal/agent"
+ "cyberstrike-ai/internal/assessment"
+ "cyberstrike-ai/internal/authctx"
+ "cyberstrike-ai/internal/config"
+ "cyberstrike-ai/internal/database"
+ "cyberstrike-ai/internal/mcp"
+ "cyberstrike-ai/internal/mcp/builtin"
+ "cyberstrike-ai/internal/security"
+ "go.uber.org/zap"
+)
+
+func TestAssessmentMCPUsesProjectWithoutConversation(t *testing.T) {
+ db, err := database.NewDB(filepath.Join(t.TempDir(), "assessment.db"), zap.NewNop())
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer db.Close()
+ if err = db.BootstrapRBAC("fixture", security.PermissionCatalog); err != nil {
+ t.Fatal(err)
+ }
+ user, err := db.GetRBACUserByUsername("admin")
+ if err != nil {
+ t.Fatal(err)
+ }
+ a, _ := db.CreateProject(&database.Project{Name: "bound"})
+ b, _ := db.CreateProject(&database.Project{Name: "other"})
+ own := &database.Asset{Host: "https://bound.example.test", ProjectID: a.ID}
+ other := &database.Asset{Host: "https://other.example.test", ProjectID: b.ID}
+ if _, err = db.UpsertAssets([]*database.Asset{own, other}, user.ID, true); err != nil {
+ t.Fatal(err)
+ }
+ task := &assessment.Task{ID: "assessment-fixture", ExecutorID: user.ID, OwnerID: user.ID, ProjectID: a.ID, Tools: []string{builtin.ToolGetAsset}}
+ server := mcp.NewServer(zap.NewNop())
+ server.SetToolAuthorizer(mcpToolAuthorizer(db))
+ registerAssetTools(server, db, zap.NewNop())
+ cfg := &config.Config{}
+ ag := agent.NewAgent(&cfg.OpenAI, &cfg.Agent, server, nil, zap.NewNop(), 5)
+ rt := &assessment.CSAIRuntime{DB: db, Agent: ag, Config: cfg}
+ for _, test := range []struct {
+ id string
+ allowed bool
+ }{{own.ID, true}, {other.ID, false}} {
+ result, err := rt.Execute(context.Background(), task, "worker", agent.ToolCall{ID: "call", Function: agent.FunctionCall{Name: builtin.ToolGetAsset, Arguments: map[string]interface{}{"id": test.id}}})
+ if err != nil || result == nil {
+ t.Fatal(err)
+ }
+ if test.allowed == result.IsError {
+ t.Fatalf("project boundary: id=%s error=%t result=%s", test.id, result.IsError, result.Result)
+ }
+ }
+ var count int
+ db.QueryRow(`SELECT count(*) FROM conversations`).Scan(&count)
+ if count != 0 {
+ t.Fatal("hidden conversation created")
+ }
+}
+
+func TestBoundAssetMutationCannotChangeAnotherProject(t *testing.T) {
+ db, err := database.NewDB(filepath.Join(t.TempDir(), "bound-mutation.db"), zap.NewNop())
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer db.Close()
+ a, _ := db.CreateProject(&database.Project{Name: "a"})
+ b, _ := db.CreateProject(&database.Project{Name: "b"})
+ asset := &database.Asset{Host: "https://other.example.test", ProjectID: b.ID}
+ if _, err = db.UpsertAssets([]*database.Asset{asset}, "admin", true); err != nil {
+ t.Fatal(err)
+ }
+ ctx := authctx.WithPrincipal(context.Background(), authctx.NewPrincipal("admin", "admin", database.RBACScopeAll, map[string]bool{"asset:read": true, "asset:write": true, "asset:delete": true}))
+ ctx = mcp.WithMCPProjectID(ctx, a.ID)
+ authorize := mcpToolAuthorizer(db)
+ for _, name := range []string{builtin.ToolGetAsset, builtin.ToolUpdateAsset, builtin.ToolDeleteAsset} {
+ if err = authorize(ctx, name, map[string]interface{}{"id": asset.ID}); err == nil {
+ t.Fatal("foreign asset authorized", name)
+ }
+ }
+ if err = authorize(ctx, builtin.ToolCreateAsset, map[string]interface{}{"host": "https://fixture.test", "project_id": b.ID}); err == nil {
+ t.Fatal("foreign destination accepted")
+ }
+}
diff --git a/internal/app/asset_tools.go b/internal/app/asset_tools.go
index 611976d7..6c066f1f 100644
--- a/internal/app/asset_tools.go
+++ b/internal/app/asset_tools.go
@@ -36,7 +36,20 @@ func registerAssetTools(server *mcp.Server, db *database.DB, logger *zap.Logger)
return textResult("错误: "+err.Error(), true), nil
}
access, owner, global := assetAccessFromToolContext(ctx, "asset:write")
- result, err := db.UpsertAssets([]*database.Asset{asset}, owner, global)
+ projectID, scoped, err := agentAssetProjectScope(db, ctx)
+ if err != nil {
+ return textResult("错误: "+err.Error(), true), nil
+ }
+ var result database.AssetImportResult
+ if scoped {
+ if asset.ProjectID != "" && asset.ProjectID != projectID {
+ return textResult("错误: 资产不属于当前项目", true), nil
+ }
+ asset.ProjectID = projectID
+ result, err = db.UpsertAssetsInProject([]*database.Asset{asset}, owner, global, projectID)
+ } else {
+ result, err = db.UpsertAssets([]*database.Asset{asset}, owner, global)
+ }
if err != nil {
logger.Error("Agent 保存资产失败", zap.Error(err))
return textResult("错误: "+err.Error(), true), nil
@@ -436,6 +449,9 @@ func assetAccessFromToolContext(ctx context.Context, permission string) (databas
// conversation) keeps the existing all-accessible-assets behavior. A bound
// conversation can only read assets assigned to that exact project.
func agentAssetProjectScope(db *database.DB, ctx context.Context) (projectID string, scoped bool, err error) {
+ if projectID = strings.TrimSpace(mcp.MCPProjectIDFromContext(ctx)); projectID != "" {
+ return projectID, true, nil
+ }
conversationID := conversationIDFromToolCtx(ctx)
if conversationID == "" {
return "", false, nil
diff --git a/internal/app/asset_tools_test.go b/internal/app/asset_tools_test.go
index 9cb491b7..4433ee90 100644
--- a/internal/app/asset_tools_test.go
+++ b/internal/app/asset_tools_test.go
@@ -188,7 +188,7 @@ func TestAssetReadToolsRespectConversationProjectScope(t *testing.T) {
}
result, _, err = server.CallTool(boundCtx, builtin.ToolGetAsset, map[string]interface{}{"id": assets[1].ID})
- if err != nil || result == nil || !result.IsError {
+ if err == nil || !strings.Contains(err.Error(), "tool authorization denied") {
t.Fatalf("bound get read a foreign-project asset: result=%#v err=%v", result, err)
}
diff --git a/internal/app/mcp_authorization.go b/internal/app/mcp_authorization.go
index 7862b655..f2fb5bb6 100644
--- a/internal/app/mcp_authorization.go
+++ b/internal/app/mcp_authorization.go
@@ -124,6 +124,11 @@ func mcpToolAuthorizer(db *database.DB) func(context.Context, string, map[string
if err := require("asset:write"); err != nil {
return err
}
+ if projectID := mcpAuthorizationString(args, "project_id"); projectID != "" {
+ if bound := mcpEffectiveProjectFilter(ctx, db); bound != "" && bound != projectID {
+ return fmt.Errorf("asset destination is outside the current project")
+ }
+ }
if projectID := mcpAuthorizationString(args, "project_id"); projectID != "" && (db == nil || !db.UserCanAccessResource(principal.UserID, principal.ScopeFor("asset:write"), "project", projectID)) {
return fmt.Errorf("no access to project %s", projectID)
}
@@ -139,6 +144,11 @@ func mcpToolAuthorizer(db *database.DB) func(context.Context, string, map[string
}
return nil
}
+ if projectID := mcpAuthorizationString(args, "project_id"); projectID != "" {
+ if bound := mcpEffectiveProjectFilter(ctx, db); bound != "" && bound != projectID {
+ return fmt.Errorf("asset destination is outside the current project")
+ }
+ }
if projectID := mcpAuthorizationString(args, "project_id"); projectID != "" && (db == nil || !db.UserCanAccessResource(principal.UserID, principal.ScopeFor("asset:write"), "project", projectID)) {
return fmt.Errorf("no access to project %s", projectID)
}
@@ -316,6 +326,11 @@ func authorizeMCPProjectResourceBoundary(ctx context.Context, db *database.DB, r
return nil
}
if filter == database.ProjectFilterUnbound {
+ // Asset/vulnerability managers historically allow an unbound session to
+ // operate across its RBAC-visible records; bound sessions remain constrained.
+ if resourceType == "asset" || resourceType == "vulnerability" {
+ return nil
+ }
if projectID != "" {
return fmt.Errorf("resource %s %s belongs to project %s, current conversation is unbound", resourceType, resourceID, projectID)
}
@@ -332,6 +347,14 @@ func authorizeMCPProjectResourceBoundary(ctx context.Context, db *database.DB, r
func mcpResourceProjectID(db *database.DB, resourceType, resourceID string) (string, bool, error) {
switch resourceType {
+ case "asset", "vulnerability":
+ table := "assets"
+ if resourceType == "vulnerability" {
+ table = "vulnerabilities"
+ }
+ var projectID string
+ err := db.QueryRow(`SELECT COALESCE(project_id,'') FROM `+table+` WHERE id=?`, resourceID).Scan(&projectID)
+ return projectID, true, err
case "webshell":
conn, err := db.GetWebshellConnection(resourceID)
if err != nil {
diff --git a/internal/assessment/approval.go b/internal/assessment/approval.go
new file mode 100644
index 00000000..d0a82f86
--- /dev/null
+++ b/internal/assessment/approval.go
@@ -0,0 +1,118 @@
+package assessment
+
+import (
+ "context"
+ "crypto/sha256"
+ "encoding/hex"
+ "encoding/json"
+ "fmt"
+
+ "cyberstrike-ai/internal/agent"
+ "github.com/google/uuid"
+)
+
+// Approval binds a host-generated request to exact arguments and the run actor.
+// Model call IDs alone are neither unique nor a trustworthy authorization token.
+func callDigest(call agent.ToolCall) string {
+ b, err := json.Marshal(call)
+ if err != nil {
+ return ""
+ }
+ sum := sha256.Sum256(b)
+ return hex.EncodeToString(sum[:])
+}
+func clearApproval(s *Step) {
+ s.Approved = false
+ s.ApprovalID = ""
+ s.ApprovalDigest = ""
+ s.ApprovalKind = ""
+ s.ApprovedBy = ""
+ s.ApprovedExecutorID = ""
+}
+func requestApproval(t *Task, s *Step, call *agent.ToolCall) {
+ clearApproval(s)
+ s.ApprovalID = uuid.NewString()
+ s.ApprovalDigest = callDigest(*call)
+ s.ApprovedExecutorID = t.ExecutorID
+ s.Pending = call
+ s.Status = "awaiting_approval"
+}
+func (e *Engine) approvedCall(ctx context.Context, t *Task, s *Step, call agent.ToolCall) (bool, error) {
+ if !s.Approved || s.Pending == nil || s.ApprovalDigest == "" || s.ApprovalDigest != callDigest(call) || s.ApprovedExecutorID != t.ExecutorID {
+ return false, nil
+ }
+ manual := true
+ if p, ok := e.Runtime.(interface{ RequiresApproval(*Task, string) bool }); ok {
+ manual = p.RequiresApproval(t, call.Function.Name)
+ }
+ if s.ApprovalKind == "policy" {
+ return !manual, nil
+ }
+ if s.ApprovalKind != "manual" || s.ApprovedBy == "" {
+ return false, nil
+ }
+ if verifier, ok := e.Runtime.(interface {
+ VerifyApproval(context.Context, *Task, *Step) (bool, error)
+ }); ok {
+ return verifier.VerifyApproval(ctx, t, s)
+ }
+ return true, nil
+}
+func (r *CSAIRuntime) VerifyApproval(ctx context.Context, t *Task, s *Step) (bool, error) {
+ if err := ctx.Err(); err != nil {
+ return false, err
+ }
+ a, err := r.DB.ResolveRBACAccess(s.ApprovedBy)
+ if err != nil {
+ return false, err
+ }
+ if a == nil || !a.User.Enabled {
+ return false, nil
+ }
+ for _, permission := range []string{"assessment:write", "hitl:write"} {
+ scope := a.PermissionScopes[permission]
+ if scope == "" {
+ scope = a.Scope
+ }
+ if !a.Permissions[permission] || !r.DB.UserCanAccessResource(a.User.ID, scope, "assessment", t.ID) {
+ return false, nil
+ }
+ }
+ return true, nil
+}
+func validateToolCalls(messages []agent.ChatMessage, calls []agent.ToolCall, used []string) error {
+ if len(calls) > 8 {
+ return fmt.Errorf("at most 8 tool calls are permitted per model turn")
+ }
+ seen := map[string]bool{}
+ for _, id := range used {
+ seen[id] = true
+ }
+ for _, m := range messages {
+ for _, c := range m.ToolCalls {
+ seen[c.ID] = true
+ }
+ }
+ for _, c := range calls {
+ if c.ID == "" || len(c.ID) > 200 || seen[c.ID] {
+ return fmt.Errorf("tool call IDs must be present, bounded and unique")
+ }
+ seen[c.ID] = true
+ if len(c.Function.Name) > 200 || c.Function.Name == "" {
+ return fmt.Errorf("invalid tool name")
+ }
+ b, err := json.Marshal(c.Function.Arguments)
+ if err != nil || len(b) > 64<<10 {
+ return fmt.Errorf("tool arguments exceed 64 KiB")
+ }
+ }
+ return nil
+}
+
+// EvidenceRevision identifies the exact observation shown to a reviewer.
+func EvidenceRevision(v Evidence) string {
+ v.Revision = ""
+ b, _ := json.Marshal(v)
+ sum := sha256.Sum256(b)
+ return hex.EncodeToString(sum[:])
+}
diff --git a/internal/assessment/engine.go b/internal/assessment/engine.go
index 3b935731..bde68497 100644
--- a/internal/assessment/engine.go
+++ b/internal/assessment/engine.go
@@ -82,6 +82,14 @@ func (e *Engine) StartAs(id, actorID string) error {
return ErrBudget
}
t.Status = "running"
+ for _, s := range t.Steps {
+ if s.Status == "awaiting_approval" && s.Pending != nil {
+ t.ExecutorID = actorID
+ requestApproval(t, s, s.Pending)
+ } else if s.Status == "pending" {
+ clearApproval(s)
+ }
+ }
t.ExecutorID = actorID
t.Reason = ""
t.Deadline = time.Now().Unix() + t.RemainingSeconds
@@ -90,15 +98,23 @@ func (e *Engine) StartAs(id, actorID string) error {
return err
}
ctx, cancel := context.WithDeadline(ctx, time.Unix(time.Now().Unix()+t.RemainingSeconds, 0))
- run := &activeRun{cancel: cancel, done: make(chan struct{})}
+ scope := security.NewProcessScope()
+ workers := runlease.New()
+ ctx = runlease.WithScope(security.WithProcessScope(ctx, scope), workers)
+ closeAdmission := func() { scope.Seal(); workers.Cancel(); cancel() }
+ stopDeadlineWatch := context.AfterFunc(ctx, func() { scope.Seal(); workers.Cancel() })
+ run := &activeRun{cancel: closeAdmission, done: make(chan struct{})}
e.active[id] = run
go func() {
- defer func() { cancel(); e.mu.Lock(); delete(e.active, id); close(run.done); e.mu.Unlock() }()
+ defer func() {
+ stopDeadlineWatch()
+ closeAdmission()
+ e.mu.Lock()
+ delete(e.active, id)
+ close(run.done)
+ e.mu.Unlock()
+ }()
// Isolate and reap local subprocesses even if an MCP tool detaches cancellation.
- scope := security.NewProcessScope()
- ctx = security.WithProcessScope(ctx, scope)
- workers := runlease.New()
- ctx = runlease.WithScope(ctx, workers)
err := func() (err error) {
defer func() {
if p := recover(); p != nil {
@@ -204,26 +220,31 @@ func (e *Engine) Close() {
<-r.done
}
}
-func (e *Engine) Decide(id, step string, approved bool) error {
+func (e *Engine) Decide(id, step, approvalID, reviewerID string, approved bool) error {
+ event := map[string]any{"approval_id": approvalID, "reviewer_id": reviewerID, "approved": approved}
return e.Store.Change(id, step, "approval", fmt.Sprintf("approved=%t", approved), func(t *Task) error {
s := t.Step(step)
- if s == nil || s.Status != "awaiting_approval" || s.Pending == nil {
+ if s == nil || s.Status != "awaiting_approval" || s.Pending == nil || approvalID == "" || approvalID != s.ApprovalID || reviewerID == "" || s.ApprovalDigest != callDigest(*s.Pending) {
return ErrConflict
}
if t.Terminal() || t.Status == "pausing" || t.Status == "stopping" {
return ErrConflict
}
+ event["call_digest"] = s.ApprovalDigest
+ event["executor_id"] = s.ApprovedExecutorID
if approved {
s.Approved = true
+ s.ApprovalKind = "manual"
+ s.ApprovedBy = reviewerID
s.Status = "pending"
} else {
s.Status = "blocked"
s.Result = "Tool execution denied by reviewer"
s.Pending = nil
- s.Approved = false
+ clearApproval(s)
}
return nil
- })
+ }, event)
}
func (e *Engine) Retry(id, step string) error {
return e.Store.Change(id, step, "retry", "Explicit retry requested; prior evidence retained in events", func(t *Task) error {
@@ -238,7 +259,7 @@ func (e *Engine) Retry(id, step string) error {
s.Trace = nil
s.Turns = 0
s.Pending = nil
- s.Approved = false
+ clearApproval(s)
s.Result = ""
return nil
})
@@ -503,6 +524,9 @@ func (e *Engine) plan(ctx context.Context, id string) error {
if reads >= 3 {
return fmt.Errorf("planner memory-read budget exhausted")
}
+ if err = validateToolCalls(msgs, r.Message.ToolCalls, nil); err != nil {
+ return err
+ }
msgs = append(msgs, r.Message)
for _, call := range r.Message.ToolCalls {
content := "Only assessment_memory is available to the planner"
diff --git a/internal/assessment/engine_test.go b/internal/assessment/engine_test.go
index 79003fb0..33a5b4a0 100644
--- a/internal/assessment/engine_test.go
+++ b/internal/assessment/engine_test.go
@@ -114,10 +114,10 @@ func TestAssessmentApprovalCompletionAndChatIndependence(t *testing.T) {
if waiting.Public().Steps[0].Trace != nil {
t.Fatal("private transcript exposed")
}
- if err := e.Decide(task.ID, st.ID, true); err != nil {
+ if err := e.Decide(task.ID, st.ID, st.ApprovalID, "reviewer", true); err != nil {
t.Fatal(err)
}
- if err := e.Decide(task.ID, st.ID, true); !errors.Is(err, ErrConflict) {
+ if err := e.Decide(task.ID, st.ID, st.ApprovalID, "reviewer", true); !errors.Is(err, ErrConflict) {
t.Fatal("duplicate decision accepted")
}
completed := waitTask(t, store, task.ID, func(t *Task) bool { return t.Status == "completed" && t.Deadline == 0 })
@@ -196,7 +196,7 @@ func TestPauseCancelsInFlightWorkAndRequiresExplicitRetry(t *testing.T) {
t.Fatal(err)
}
got := waitTask(t, store, task.ID, func(t *Task) bool { return len(t.Steps) > 0 && t.Steps[0].Status == "awaiting_approval" })
- if err := e.Decide(task.ID, got.Steps[0].ID, true); err != nil {
+ if err := e.Decide(task.ID, got.Steps[0].ID, got.Steps[0].ApprovalID, "reviewer", true); err != nil {
t.Fatal(err)
}
select {
@@ -292,7 +292,7 @@ func TestWorkerRejectsFabricatedEvidence(t *testing.T) {
t.Fatal(err)
}
got := waitTask(t, store, task.ID, func(t *Task) bool { return len(t.Steps) > 0 && t.Steps[0].Status == "awaiting_approval" })
- if err := e.Decide(task.ID, got.Steps[0].ID, true); err != nil {
+ if err := e.Decide(task.ID, got.Steps[0].ID, got.Steps[0].ApprovalID, "reviewer", true); err != nil {
t.Fatal(err)
}
got = waitTask(t, store, task.ID, func(t *Task) bool { return t.Status == "blocked" && t.Deadline == 0 })
diff --git a/internal/assessment/memory.go b/internal/assessment/memory.go
index ceb01090..0b1e6741 100644
--- a/internal/assessment/memory.go
+++ b/internal/assessment/memory.go
@@ -207,6 +207,7 @@ func validateEvidence(t *Task, s *Step, rows []Evidence) error {
}
for i := range rows {
v := &rows[i]
+ v.Revision = ""
if v.Kind != "fact" && v.Kind != "finding" && v.Kind != "asset" && v.Kind != "gap" {
return fmt.Errorf("invalid evidence kind")
}
diff --git a/internal/assessment/runtime.go b/internal/assessment/runtime.go
index 9d819f73..f1461b02 100644
--- a/internal/assessment/runtime.go
+++ b/internal/assessment/runtime.go
@@ -18,13 +18,17 @@ import (
// CSAIRuntime reuses the existing model transport and Agent->MCP execution path.
// The execution namespace is an assessment/step ID, never a chat database row.
type CSAIRuntime struct {
- DB *database.DB
- Agent *agent.Agent
- Config *config.Config
- Logger *zap.Logger
+ ConfigSnapshot func() (*config.Config, error)
+ DB *database.DB
+ Agent *agent.Agent
+ Config *config.Config
+ Logger *zap.Logger
}
func (r *CSAIRuntime) Context(ctx context.Context, t *Task) (context.Context, error) {
+ if err := ctx.Err(); err != nil {
+ return nil, err
+ }
actorID := t.ExecutorID
if actorID == "" {
actorID = t.OwnerID
@@ -43,7 +47,7 @@ func (r *CSAIRuntime) Context(ctx context.Context, t *Task) (context.Context, er
if t.ProjectID != "" && (!principal.HasPermission("project:read") || !r.DB.UserCanAccessResource(principal.UserID, principal.ScopeFor("project:read"), "project", t.ProjectID)) {
return nil, fmt.Errorf("operator no longer has access to the linked project")
}
- return authctx.WithPrincipal(ctx, principal), nil
+ return mcp.WithMCPProjectID(authctx.WithPrincipal(ctx, principal), t.ProjectID), nil
}
func (r *CSAIRuntime) Tools(t *Task) ([]agent.Tool, error) {
if r.Agent == nil {
@@ -88,12 +92,16 @@ func (r *CSAIRuntime) Complete(ctx context.Context, t *Task, msgs []agent.ChatMe
if err != nil {
return nil, err
}
+ snapshot, err := r.configuration()
+ if err != nil {
+ return nil, err
+ }
if t.Model != "" {
- if _, _, ok := r.Config.AI.ResolveChannel(t.Model); !ok {
+ if _, _, ok := snapshot.AI.ResolveChannel(t.Model); !ok {
return nil, fmt.Errorf("model channel no longer exists")
}
}
- cfg, _, ok := r.Config.ResolveAIChannel(t.Model)
+ cfg, _, ok := snapshot.ResolveAIChannel(t.Model)
if !ok {
return nil, fmt.Errorf("unknown model channel %q", t.Model)
}
@@ -108,6 +116,23 @@ func (r *CSAIRuntime) Execute(ctx context.Context, t *Task, sid string, call age
if err != nil {
return nil, err
}
+ allowed := false
+ defs, err := r.Tools(t)
+ if err != nil {
+ return nil, err
+ }
+ for _, def := range defs {
+ if def.Function.Name == call.Function.Name {
+ allowed = true
+ break
+ }
+ }
+ if !allowed {
+ return nil, fmt.Errorf("tool is outside the assessment allowlist")
+ }
+ if err = ctx.Err(); err != nil {
+ return nil, err
+ }
// Reserved execution ID only supplies MCP trace attribution; no chat is created.
result, err := r.Agent.ExecuteMCPToolForConversation(ctx, "assessment-"+t.ID+"-"+sid, call.Function.Name, call.Function.Arguments)
if err != nil || result == nil {
@@ -130,7 +155,9 @@ func (r *CSAIRuntime) Execute(ctx context.Context, t *Task, sid string, call age
}
continue
}
- result.Result = r.Agent.MCPExecutionResultText(result.ExecutionID)
+ if stored := r.Agent.MCPExecutionResultText(result.ExecutionID); stored != "" {
+ result.Result = stored
+ }
result.IsError = status != mcp.ToolExecutionStatusCompleted
result.Blocked = status == mcp.ToolExecutionStatusBlocked
if status == "" {
@@ -147,13 +174,27 @@ func (r *CSAIRuntime) RequiresApproval(t *Task, name string) bool {
if t.ApprovalMode == "manual" {
return true
}
- if r.Config.Hitl.EffectiveDefaultMode() == "off" {
+ snapshot, err := r.configuration()
+ if err != nil {
+ return true
+ }
+ if snapshot.Hitl.EffectiveDefaultMode() == "off" {
return false
}
- for _, allowed := range r.Config.Hitl.ToolWhitelist {
+ for _, allowed := range snapshot.Hitl.ToolWhitelist {
if strings.EqualFold(strings.TrimSpace(allowed), name) {
return false
}
}
return true
}
+
+func (r *CSAIRuntime) configuration() (*config.Config, error) {
+ if r.ConfigSnapshot != nil {
+ return r.ConfigSnapshot()
+ }
+ if r.Config == nil {
+ return nil, fmt.Errorf("configuration unavailable")
+ }
+ return r.Config, nil
+}
diff --git a/internal/assessment/security_test.go b/internal/assessment/security_test.go
new file mode 100644
index 00000000..6d0b8560
--- /dev/null
+++ b/internal/assessment/security_test.go
@@ -0,0 +1,190 @@
+package assessment
+
+import (
+ "context"
+ "cyberstrike-ai/internal/runlease"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "strings"
+ "testing"
+ "time"
+
+ "cyberstrike-ai/internal/agent"
+ "cyberstrike-ai/internal/config"
+ "cyberstrike-ai/internal/database"
+ "cyberstrike-ai/internal/security"
+)
+
+func TestApprovalReplayAndArgumentBinding(t *testing.T) {
+ store, task := fixture(t)
+ e := NewEngine(store, normalRuntime(), nil)
+ call := &agent.ToolCall{ID: "reused-model-id", Function: agent.FunctionCall{Name: "inspect", Arguments: map[string]interface{}{"target": "first"}}}
+ create := func() string {
+ if err := store.Change(task.ID, "", "", "", func(t *Task) error {
+ t.ExecutorID = "operator"
+ t.Steps = []*Step{{ID: "step"}}
+ requestApproval(t, t.Steps[0], call)
+ return nil
+ }); err != nil {
+ t.Fatal(err)
+ }
+ current, _ := store.Get(task.ID)
+ return current.Steps[0].ApprovalID
+ }
+ first := create()
+ if err := e.Decide(task.ID, "step", first, "reviewer", true); err != nil {
+ t.Fatal(err)
+ }
+ current, _ := store.Get(task.ID)
+ ok, err := e.approvedCall(context.Background(), current, current.Steps[0], *call)
+ if err != nil || !ok {
+ t.Fatal("valid grant rejected", err)
+ }
+ call.Function.Arguments["target"] = "second"
+ ok, err = e.approvedCall(context.Background(), current, current.Steps[0], *call)
+ if err != nil || ok {
+ t.Fatal("argument change inherited approval")
+ }
+ second := create()
+ if first == second {
+ t.Fatal("host request IDs reused")
+ }
+ if err = e.Decide(task.ID, "step", first, "reviewer", true); !errors.Is(err, ErrConflict) {
+ t.Fatal("old approval approved a different command", err)
+ }
+ if err = e.Decide(task.ID, "step", second, "reviewer", true); err != nil {
+ t.Fatal(err)
+ }
+ current, _ = store.Get(task.ID)
+ current.ExecutorID = "different-operator"
+ ok, err = e.approvedCall(context.Background(), current, current.Steps[0], *call)
+ if err != nil || ok {
+ t.Fatal("grant crossed executor identity")
+ }
+}
+func TestApprovalReviewerRevocationAndScope(t *testing.T) {
+ store, task := fixture(t)
+ if err := store.DB.BootstrapRBAC("fixture", security.PermissionCatalog); err != nil {
+ t.Fatal(err)
+ }
+ admin, err := store.DB.GetRBACUserByUsername("admin")
+ if err != nil {
+ t.Fatal(err)
+ }
+ role, err := store.DB.UpsertRBACRole("review", "review", "", database.RBACScopeOwn, []string{"hitl:write", "assessment:write"})
+ if err != nil {
+ t.Fatal(err)
+ }
+ user, err := store.DB.CreateRBACUser("reviewer", "Reviewer", "fixture", true, []string{role.ID})
+ if err != nil {
+ t.Fatal(err)
+ }
+ rt := &CSAIRuntime{DB: store.DB, Config: &config.Config{}}
+ st := &Step{ApprovedBy: user.ID}
+ task.OwnerID = admin.ID
+ if ok, err := rt.VerifyApproval(context.Background(), task, st); err != nil || ok {
+ t.Fatal("own scope approved somebody else's task", err)
+ }
+ if err = store.DB.AssignResourceToUser(user.ID, "assessment", task.ID); err != nil {
+ t.Fatal(err)
+ }
+ if ok, err := rt.VerifyApproval(context.Background(), task, st); err != nil || !ok {
+ t.Fatal("assigned reviewer rejected", err)
+ }
+ if _, err = store.DB.Exec(`DELETE FROM rbac_resource_assignments WHERE user_id=?`, user.ID); err != nil {
+ t.Fatal(err)
+ }
+ if ok, err := rt.VerifyApproval(context.Background(), task, st); err != nil || ok {
+ t.Fatal("revoked review assignment stayed valid", err)
+ }
+}
+func TestPolicyGrantDoesNotBypassNewManualPolicy(t *testing.T) {
+ store, task := fixture(t)
+ rt := &CSAIRuntime{Config: &config.Config{}}
+ e := NewEngine(store, rt, nil)
+ task.ApprovalMode = "policy"
+ task.ExecutorID = "operator"
+ call := agent.ToolCall{ID: "call", Function: agent.FunctionCall{Name: "inspect", Arguments: map[string]interface{}{}}}
+ s := &Step{Approved: true, Pending: &call, ApprovalKind: "policy", ApprovalDigest: callDigest(call), ApprovedExecutorID: "operator"}
+ if ok, err := e.approvedCall(context.Background(), task, s, call); err != nil || !ok {
+ t.Fatal("valid policy denied", err)
+ }
+ rt.Config.Hitl.DefaultMode = "approval"
+ if ok, err := e.approvedCall(context.Background(), task, s, call); err != nil || ok {
+ t.Fatal("old policy grant bypassed newly required approval", err)
+ }
+}
+func TestToolCallBatchCannotReuseIDsAfterCompaction(t *testing.T) {
+ c := agent.ToolCall{ID: "old", Function: agent.FunctionCall{Name: "inspect", Arguments: map[string]interface{}{}}}
+ if err := validateToolCalls(nil, []agent.ToolCall{c}, []string{"old"}); err == nil {
+ t.Fatal("reused archived tool ID accepted")
+ }
+ calls := []agent.ToolCall{}
+ for i := 0; i < 9; i++ {
+ v := c
+ v.ID = fmt.Sprint(i)
+ calls = append(calls, v)
+ }
+ if err := validateToolCalls(nil, calls, nil); err == nil {
+ t.Fatal("unbounded tool fan-out accepted")
+ }
+}
+func TestLargeTraceListAndEventPagingRemainBounded(t *testing.T) {
+ store, task := fixture(t)
+ trace, _ := json.Marshal([]agent.ChatMessage{{Role: "assistant", Content: strings.Repeat("x", 2<<20)}})
+ store.Change(task.ID, "", "", "", func(t *Task) error { t.Steps = []*Step{{ID: "large", Trace: trace}}; return nil })
+ rows, err := store.List("owner", database.RBACScopeOwn, 50, 0)
+ if err != nil || len(rows) != 1 || len(rows[0].Steps) != 0 {
+ t.Fatal("list exposed trace", err)
+ }
+ for i := 0; i < 12; i++ {
+ if err = store.Event(task.ID, "large", "tool_result", "body", map[string]string{"output": strings.Repeat("x", 200000)}); err != nil {
+ t.Fatal(err)
+ }
+ }
+ first, err := store.Events(task.ID, 0)
+ if err != nil || len(first) == 0 || len(first) >= 12 {
+ t.Fatal("event page is unbounded", len(first), err)
+ }
+ next, err := store.Events(task.ID, first[len(first)-1].ID)
+ if err != nil || len(next) == 0 || next[0].ID <= first[len(first)-1].ID {
+ t.Fatal("bounded paging lost events", err)
+ }
+}
+
+func TestPauseClosesDetachedToolAdmissionBeforeAcknowledgement(t *testing.T) {
+ store, task := fixture(t)
+ entered := make(chan struct{})
+ release := make(chan struct{})
+ late := make(chan error, 1)
+ r := normalRuntime()
+ r.execute = func(ctx context.Context, _ *Task, _ string, _ agent.ToolCall) (*agent.ToolExecutionResult, error) {
+ close(entered)
+ <-release
+ unregister, err := runlease.FromContext(ctx).Register("late-tool", func() {})
+ if err == nil {
+ unregister()
+ }
+ late <- err
+ return nil, ctx.Err()
+ }
+ e := NewEngine(store, autonomousFixture{r}, nil)
+ defer e.Close()
+ if err := e.Start(task.ID); err != nil {
+ t.Fatal(err)
+ }
+ select {
+ case <-entered:
+ case <-time.After(5 * time.Second):
+ t.Fatal("tool dispatch not reached")
+ }
+ if err := e.Control(task.ID, "pause"); err != nil {
+ t.Fatal(err)
+ }
+ close(release)
+ if err := <-late; !errors.Is(err, runlease.ErrClosed) {
+ t.Fatal("tool submitted after pause acknowledgement", err)
+ }
+ waitTask(t, store, task.ID, func(t *Task) bool { return t.Status == "paused" })
+}
diff --git a/internal/assessment/store.go b/internal/assessment/store.go
index 6d842ddb..90833ed8 100644
--- a/internal/assessment/store.go
+++ b/internal/assessment/store.go
@@ -87,19 +87,25 @@ func (s *Store) Events(id string, after int64) ([]Event, error) {
}
defer rows.Close()
out := []Event{}
+ bytes := 0
for rows.Next() {
var e Event
var b string
if err = rows.Scan(&e.ID, &e.StepID, &e.Kind, &e.Message, &b, &e.CreatedAt); err != nil {
return nil, err
}
+ size := len(b) + len(e.Message) + len(e.StepID) + len(e.Kind) + 128
+ if bytes+size > 1<<20 && len(out) > 0 {
+ break
+ }
+ bytes += size
e.Data = json.RawMessage(b)
out = append(out, e)
}
return out, rows.Err()
}
func (s *Store) List(user, scope string, limit, offset int) ([]*Task, error) {
- q := `SELECT payload FROM assessments a WHERE 1=1`
+ q := `SELECT json_remove(payload, '$.steps', '$.material') FROM assessments a WHERE 1=1`
args := []any{}
if scope != database.RBACScopeAll {
if scope == database.RBACScopeOwn {
@@ -127,10 +133,7 @@ func (s *Store) List(user, scope string, limit, offset int) ([]*Task, error) {
if err = json.Unmarshal([]byte(b), &t); err != nil {
return nil, err
}
- p := t.Public()
- p.Steps = nil
- p.Material = ""
- out = append(out, p)
+ out = append(out, &t)
}
return out, rows.Err()
}
@@ -222,7 +225,7 @@ func settleTime(t *Task) {
func interrupt(s *Step, reason string) {
s.Status = "blocked"
s.Result = reason
- s.Approved = false
+ clearApproval(s)
s.Pending = nil
// Trace is retained as evidence; retry starts a fresh bounded session.
}
diff --git a/internal/assessment/types.go b/internal/assessment/types.go
index fe0a892a..04cd636e 100644
--- a/internal/assessment/types.go
+++ b/internal/assessment/types.go
@@ -45,19 +45,25 @@ type Task struct {
}
type Step struct {
- Checkpoint string `json:"checkpoint,omitempty"`
- RetrievedIDs []string `json:"retrieved_execution_ids,omitempty"`
- RetiredReason string `json:"retired_reason,omitempty"`
- ID string `json:"id"`
- Key string `json:"key"`
- Title string `json:"title"`
- Instruction string `json:"instruction"`
- DependsOn []string `json:"depends_on"`
- Status string `json:"status"`
- Turns int `json:"turns"`
- Result string `json:"result"`
- Evidence []Evidence `json:"evidence"`
- Messages []agent.ChatMessage `json:"-"`
+ ApprovalID string `json:"approval_id,omitempty"`
+ ApprovalDigest string `json:"approval_digest,omitempty"`
+ ApprovalKind string `json:"approval_kind,omitempty"`
+ ApprovedBy string `json:"approved_by,omitempty"`
+ ApprovedExecutorID string `json:"approved_executor_id,omitempty"`
+ SeenCallIDs []string `json:"seen_call_ids,omitempty"`
+ Checkpoint string `json:"checkpoint,omitempty"`
+ RetrievedIDs []string `json:"retrieved_execution_ids,omitempty"`
+ RetiredReason string `json:"retired_reason,omitempty"`
+ ID string `json:"id"`
+ Key string `json:"key"`
+ Title string `json:"title"`
+ Instruction string `json:"instruction"`
+ DependsOn []string `json:"depends_on"`
+ Status string `json:"status"`
+ Turns int `json:"turns"`
+ Result string `json:"result"`
+ Evidence []Evidence `json:"evidence"`
+ Messages []agent.ChatMessage `json:"-"`
// Trace is private model state stored in the payload, excluded by Public().
Trace json.RawMessage `json:"trace,omitempty"`
Pending *agent.ToolCall `json:"pending,omitempty"`
@@ -77,6 +83,7 @@ type ObservedAsset struct {
}
type Evidence struct {
+ Revision string `json:"revision,omitempty"`
Asset *ObservedAsset `json:"asset,omitempty"`
Kind string `json:"kind"` // fact | finding | asset | gap
Title string `json:"title"`
@@ -156,6 +163,9 @@ func (t *Task) Public() *Task {
_ = json.Unmarshal(b, &out)
for _, s := range out.Steps {
s.Trace = nil
+ for i := range s.Evidence {
+ s.Evidence[i].Revision = EvidenceRevision(s.Evidence[i])
+ }
}
return &out
}
diff --git a/internal/assessment/worker.go b/internal/assessment/worker.go
index 4fead4e0..d6527df2 100644
--- a/internal/assessment/worker.go
+++ b/internal/assessment/worker.go
@@ -119,7 +119,11 @@ func (e *Engine) work(ctx context.Context, id, sid string) (runErr error) {
if !allowed {
return fmt.Errorf("tool %q is outside the selected allowlist", tc.Function.Name)
}
- if !s.Approved || s.Pending == nil || s.Pending.ID != tc.ID {
+ approved, approvalErr := e.approvedCall(ctx, t, s, *tc)
+ if approvalErr != nil {
+ return approvalErr
+ }
+ if !approved {
manual := true
if policy, ok := e.Runtime.(interface{ RequiresApproval(*Task, string) bool }); ok {
manual = policy.RequiresApproval(t, tc.Function.Name)
@@ -130,8 +134,12 @@ func (e *Engine) work(ctx context.Context, id, sid string) (runErr error) {
if st == nil || st.Status != "running" {
return ErrConflict
}
+ clearApproval(st)
st.Pending = tc
st.Approved = true
+ st.ApprovalKind = "policy"
+ st.ApprovalDigest = callDigest(*tc)
+ st.ApprovedExecutorID = t.ExecutorID
saveTrace(st, msgs)
return nil
}); err != nil {
@@ -139,19 +147,21 @@ func (e *Engine) work(ctx context.Context, id, sid string) (runErr error) {
}
continue
}
+ auditRequest := map[string]any{"call": tc}
return e.Store.Change(id, sid, "approval_requested", tc.Function.Name, func(t *Task) error {
s := t.Step(sid)
if s == nil || s.Status != "running" {
return ErrConflict
}
- s.Status = "awaiting_approval"
- s.Pending = tc
- s.Approved = false
+ requestApproval(t, s, tc)
+ auditRequest["approval_id"] = s.ApprovalID
+ auditRequest["call_digest"] = s.ApprovalDigest
+ auditRequest["executor_id"] = s.ApprovedExecutorID
saveTrace(s, msgs)
return nil
- })
+ }, auditRequest)
}
- if err = e.Store.Event(id, sid, "tool_start", tc.Function.Name, tc); err != nil {
+ if err = e.Store.Event(id, sid, "tool_start", tc.Function.Name, map[string]any{"call": tc, "approval_id": s.ApprovalID, "approval_kind": s.ApprovalKind, "call_digest": s.ApprovalDigest, "executor_id": t.ExecutorID}); err != nil {
return err
}
result, execErr := e.Runtime.Execute(ctx, t, sid, *tc)
@@ -173,7 +183,7 @@ func (e *Engine) work(ctx context.Context, id, sid string) (runErr error) {
}
saveTrace(st, msgs)
st.Pending = nil
- st.Approved = false
+ clearApproval(st)
st.ExecutionID = result.ExecutionID
if result.ExecutionID != "" {
st.ExecutionIDs = append(st.ExecutionIDs, result.ExecutionID)
@@ -207,12 +217,18 @@ func (e *Engine) work(ctx context.Context, id, sid string) (runErr error) {
}
if len(reply.Message.ToolCalls) > 0 && !settling {
msgs = append(msgs, reply.Message)
- for _, tc := range reply.Message.ToolCalls {
- if tc.ID == "" {
- return fmt.Errorf("tool call has no id")
- }
+ if err = validateToolCalls(msgs[:len(msgs)-1], reply.Message.ToolCalls, s.SeenCallIDs); err != nil {
+ return err
}
- if err = e.Store.Change(id, sid, "model", "Worker requested tools", func(t *Task) error { st := t.Step(sid); st.Turns++; saveTrace(st, msgs); return nil }); err != nil {
+ if err = e.Store.Change(id, sid, "model", "Worker requested tools", func(t *Task) error {
+ st := t.Step(sid)
+ st.Turns++
+ for _, c := range reply.Message.ToolCalls {
+ st.SeenCallIDs = append(st.SeenCallIDs, c.ID)
+ }
+ saveTrace(st, msgs)
+ return nil
+ }); err != nil {
return err
}
continue
diff --git a/internal/database/asset.go b/internal/database/asset.go
index 183bdd9f..e224dcd4 100644
--- a/internal/database/asset.go
+++ b/internal/database/asset.go
@@ -304,6 +304,15 @@ func appendAssetAccess(query string, args []interface{}, access RBACListAccess,
}
func (db *DB) UpsertAssets(assets []*Asset, ownerUserID string, allowGlobal ...bool) (AssetImportResult, error) {
+ return db.upsertAssets(assets, ownerUserID, len(allowGlobal) > 0 && allowGlobal[0], nil)
+}
+
+// UpsertAssetsInProject enforces the caller's project boundary inside the same
+// transaction that resolves deduplication, including for globally scoped users.
+func (db *DB) UpsertAssetsInProject(assets []*Asset, ownerUserID string, global bool, projectID string) (AssetImportResult, error) {
+ return db.upsertAssets(assets, ownerUserID, global, &projectID)
+}
+func (db *DB) upsertAssets(assets []*Asset, ownerUserID string, global bool, projectBoundary *string) (AssetImportResult, error) {
result := AssetImportResult{}
tx, err := db.Begin()
if err != nil {
@@ -317,6 +326,9 @@ func (db *DB) UpsertAssets(assets []*Asset, ownerUserID string, allowGlobal ...b
continue
}
normalizeAsset(asset)
+ if projectBoundary != nil && asset.ProjectID != *projectBoundary {
+ return result, fmt.Errorf("asset is outside the current project")
+ }
if err := validateAsset(asset); err != nil {
return result, fmt.Errorf("第 %d 个资产无效: %w", result.Created+result.Updated+result.Skipped+1, err)
}
@@ -326,8 +338,8 @@ func (db *DB) UpsertAssets(assets []*Asset, ownerUserID string, allowGlobal ...b
continue
}
var existingID string
- var existingOwner sql.NullString
- err := tx.QueryRow(`SELECT id,owner_user_id FROM assets WHERE dedup_key = ?`, key).Scan(&existingID, &existingOwner)
+ var existingOwner, existingProject sql.NullString
+ err := tx.QueryRow(`SELECT id,owner_user_id,project_id FROM assets WHERE dedup_key = ?`, key).Scan(&existingID, &existingOwner, &existingProject)
tagsJSON, _ := json.Marshal(asset.Tags)
if err == sql.ErrNoRows {
asset.ID = uuid.NewString()
@@ -356,8 +368,11 @@ func (db *DB) UpsertAssets(assets []*Asset, ownerUserID string, allowGlobal ...b
return result, fmt.Errorf("检查资产去重键失败: %w", err)
}
asset.ID = existingID
- global := len(allowGlobal) > 0 && allowGlobal[0]
- if !global && existingOwner.Valid && strings.TrimSpace(existingOwner.String) != "" && strings.TrimSpace(existingOwner.String) != strings.TrimSpace(ownerUserID) {
+ if projectBoundary != nil && existingProject.String != *projectBoundary {
+ result.Skipped++
+ continue
+ }
+ if !global && strings.TrimSpace(existingOwner.String) != strings.TrimSpace(ownerUserID) {
result.Skipped++
continue
}
diff --git a/internal/database/asset_test.go b/internal/database/asset_test.go
index 9039483c..52e6dc25 100644
--- a/internal/database/asset_test.go
+++ b/internal/database/asset_test.go
@@ -580,3 +580,49 @@ func TestAssetIPURLWithPrefilledIPDoesNotBecomeDomain(t *testing.T) {
}
}
}
+
+func TestScopedAssetImportCannotOverwriteOwnerlessRecord(t *testing.T) {
+ db, err := NewDB(filepath.Join(t.TempDir(), "ownerless.db"), zap.NewNop())
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer db.Close()
+ original := &Asset{Host: "https://fixture.example.test", Title: "Protected ownerless asset"}
+ if _, err = db.UpsertAssets([]*Asset{original}, "", true); err != nil {
+ t.Fatal(err)
+ }
+ result, err := db.UpsertAssets([]*Asset{{Host: original.Host, Title: "Unauthorized replacement", ProjectID: "attacker-project"}}, "scoped-user", false)
+ if err != nil || result.Skipped != 1 || result.Updated != 0 {
+ t.Fatal("ownerless row writable by scoped import", result, err)
+ }
+ saved, err := db.GetAsset(original.ID, RBACListAccess{Scope: RBACScopeAll})
+ if err != nil || saved.Title != original.Title || saved.ProjectID != "" {
+ t.Fatal("asset changed", saved, err)
+ }
+ result, err = db.UpsertAssets([]*Asset{{Host: original.Host, Title: "Admin update"}}, "admin", true)
+ if err != nil || result.Updated != 1 {
+ t.Fatal("explicit global import broken", result, err)
+ }
+}
+
+func TestProjectBoundImportCannotReassignDeduplicatedAsset(t *testing.T) {
+ db, err := NewDB(filepath.Join(t.TempDir(), "bound-import.db"), zap.NewNop())
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer db.Close()
+ currentProject, _ := db.CreateProject(&Project{Name: "current"})
+ otherProject, _ := db.CreateProject(&Project{Name: "other"})
+ original := &Asset{Host: "https://shared.example.test", ProjectID: otherProject.ID, Title: "Original"}
+ if _, err = db.UpsertAssets([]*Asset{original}, "admin", true); err != nil {
+ t.Fatal(err)
+ }
+ result, err := db.UpsertAssetsInProject([]*Asset{{Host: original.Host, ProjectID: currentProject.ID, Title: "Reassigned"}}, "admin", true, currentProject.ID)
+ if err != nil || result.Skipped != 1 {
+ t.Fatal("project boundary bypass via dedup", result, err)
+ }
+ saved, err := db.GetAsset(original.ID, RBACListAccess{Scope: RBACScopeAll})
+ if err != nil || saved.ProjectID != otherProject.ID || saved.Title != "Original" {
+ t.Fatal("foreign project record changed", err)
+ }
+}
diff --git a/internal/handler/assessment.go b/internal/handler/assessment.go
index baed96f1..7d9be4c6 100644
--- a/internal/handler/assessment.go
+++ b/internal/handler/assessment.go
@@ -5,6 +5,7 @@ import (
"errors"
"fmt"
"net/http"
+ "net/url"
"sort"
"strconv"
"strings"
@@ -19,14 +20,23 @@ import (
)
type AssessmentHandler struct {
- Engine *assessment.Engine
- DB *database.DB
- Config *config.Config
- Audit *audit.Service
+ ConfigSnapshot func() (*config.Config, error)
+ Engine *assessment.Engine
+ DB *database.DB
+ Config *config.Config
+ Audit *audit.Service
}
+func (h *AssessmentHandler) bind(c *gin.Context, v any) error {
+ c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, 128<<10)
+ return c.ShouldBindJSON(v)
+}
func (h *AssessmentHandler) fail(c *gin.Context, err error) {
code := http.StatusBadRequest
+ var tooLarge *http.MaxBytesError
+ if errors.As(err, &tooLarge) {
+ code = http.StatusRequestEntityTooLarge
+ }
if errors.Is(err, sql.ErrNoRows) {
code = 404
}
@@ -36,6 +46,9 @@ func (h *AssessmentHandler) fail(c *gin.Context, err error) {
c.JSON(code, gin.H{"error": err.Error()})
}
func (h *AssessmentHandler) task(c *gin.Context) (*assessment.Task, bool) {
+ if !assessmentMutationOriginAllowed(c) {
+ return nil, false
+ }
session, ok := security.CurrentSession(c)
if !ok {
c.AbortWithStatus(401)
@@ -53,12 +66,17 @@ func (h *AssessmentHandler) task(c *gin.Context) (*assessment.Task, bool) {
return t, true
}
func (h *AssessmentHandler) Options(c *gin.Context) {
+ cfg, err := h.configuration()
+ if err != nil {
+ h.fail(c, err)
+ return
+ }
options := []gin.H{}
- for id, ch := range h.Config.AI.Channels {
- options = append(options, gin.H{"id": id, "name": ch.Name, "model": ch.Model, "default": id == h.Config.AI.DefaultChannel})
+ for id, ch := range cfg.AI.Channels {
+ options = append(options, gin.H{"id": id, "name": ch.Name, "model": ch.Model, "default": id == cfg.AI.DefaultChannel})
}
if len(options) == 0 {
- options = append(options, gin.H{"id": "", "name": "Default", "model": h.Config.OpenAI.Model, "default": true})
+ options = append(options, gin.H{"id": "", "name": "Default", "model": cfg.OpenAI.Model, "default": true})
}
sort.Slice(options, func(i, j int) bool { return options[i]["id"].(string) < options[j]["id"].(string) })
tools, _ := h.Engine.Runtime.Tools(&assessment.Task{Tools: allAssessmentToolNames(h)})
@@ -113,6 +131,14 @@ func (h *AssessmentHandler) Get(c *gin.Context) {
}
}
func (h *AssessmentHandler) Create(c *gin.Context) {
+ if !assessmentMutationOriginAllowed(c) {
+ return
+ }
+ cfg, err := h.configuration()
+ if err != nil {
+ h.fail(c, err)
+ return
+ }
// Only creation fields are accepted. Runtime state/owner cannot be supplied.
var req struct {
ApprovalMode string `json:"approval_mode"`
@@ -129,7 +155,7 @@ func (h *AssessmentHandler) Create(c *gin.Context) {
Rounds int `json:"max_rounds"`
}
c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, 128<<10)
- if err := c.ShouldBindJSON(&req); err != nil {
+ if err := h.bind(c, &req); err != nil {
h.fail(c, err)
return
}
@@ -146,12 +172,12 @@ func (h *AssessmentHandler) Create(c *gin.Context) {
}
}
if req.Model != "" {
- if _, _, ok := h.Config.AI.ResolveChannel(req.Model); !ok {
+ if _, _, ok := cfg.AI.ResolveChannel(req.Model); !ok {
h.fail(c, fmt.Errorf("unknown model channel"))
return
}
}
- if _, _, ok := h.Config.ResolveAIChannel(req.Model); !ok {
+ if _, _, ok := cfg.ResolveAIChannel(req.Model); !ok {
h.fail(c, fmt.Errorf("unknown model channel"))
return
}
@@ -209,7 +235,7 @@ func (h *AssessmentHandler) Control(c *gin.Context) {
var req struct {
Message string `json:"message"`
}
- if err = c.ShouldBindJSON(&req); err == nil {
+ if err = h.bind(c, &req); err == nil {
text := strings.TrimSpace(req.Message)
if len(text) == 0 || len(text) > 8000 {
err = fmt.Errorf("message must contain 1..8000 bytes")
@@ -245,22 +271,28 @@ func (h *AssessmentHandler) Decision(c *gin.Context) {
c.JSON(403, gin.H{"error": "hitl:write is required"})
return
}
+ session, _ := security.CurrentSession(c)
+ if !h.DB.UserCanAccessResource(session.UserID, session.ScopeFor("hitl:write"), "assessment", t.ID) {
+ c.JSON(403, gin.H{"error": "approval scope does not include this assessment"})
+ return
+ }
var req struct {
- Approved *bool `json:"approved"`
+ ApprovalID string `json:"approval_id"`
+ Approved *bool `json:"approved"`
}
- if err := c.ShouldBindJSON(&req); err != nil {
+ if err := h.bind(c, &req); err != nil {
h.fail(c, err)
return
}
- if req.Approved == nil {
- h.fail(c, fmt.Errorf("approved is required"))
+ if req.Approved == nil || strings.TrimSpace(req.ApprovalID) == "" {
+ h.fail(c, fmt.Errorf("approved and approval_id are required"))
return
}
- if err := h.Engine.Decide(t.ID, c.Param("stepId"), *req.Approved); err != nil {
+ if err := h.Engine.Decide(t.ID, c.Param("stepId"), req.ApprovalID, session.UserID, *req.Approved); err != nil {
h.fail(c, err)
return
}
- h.Audit.RecordOK(c, "assessment", "approval", "Assessment tool decision", "assessment", t.ID, map[string]interface{}{"step_id": c.Param("stepId"), "approved": *req.Approved})
+ h.Audit.RecordOK(c, "assessment", "approval", "Assessment tool decision", "assessment", t.ID, map[string]interface{}{"step_id": c.Param("stepId"), "approved": *req.Approved, "approval_id": req.ApprovalID})
c.JSON(200, gin.H{"ok": true})
}
func (h *AssessmentHandler) Retry(c *gin.Context) {
@@ -316,11 +348,12 @@ func (h *AssessmentHandler) Publish(c *gin.Context) {
return
}
var req struct {
- StepID string `json:"step_id"`
- Index int `json:"index"`
- Kind string `json:"kind"`
+ StepID string `json:"step_id"`
+ Revision string `json:"revision"`
+ Index int `json:"index"`
+ Kind string `json:"kind"`
}
- if err := c.ShouldBindJSON(&req); err != nil {
+ if err := h.bind(c, &req); err != nil {
h.fail(c, err)
return
}
@@ -330,6 +363,10 @@ func (h *AssessmentHandler) Publish(c *gin.Context) {
return
}
v := st.Evidence[req.Index]
+ if req.Revision == "" || req.Revision != assessment.EvidenceRevision(v) {
+ h.fail(c, assessment.ErrConflict)
+ return
+ }
if len(v.ExecutionIDs) == 0 || v.Kind == "gap" {
h.fail(c, fmt.Errorf("execution-backed observation required"))
return
@@ -380,7 +417,14 @@ func (h *AssessmentHandler) Publish(c *gin.Context) {
return
}
a := v.Asset
- imported, err := h.DB.UpsertAssets([]*database.Asset{{ProjectID: t.ProjectID, Host: a.Host, IP: a.IP, Domain: a.Domain, Port: a.Port, Protocol: a.Protocol, Server: a.Server, Title: v.Title, Source: "assessment", SourceQuery: body, Tags: []string{"assessment:" + t.ID}}}, session.UserID, session.ScopeFor("asset:write") == database.RBACScopeAll)
+ assets := []*database.Asset{{ProjectID: t.ProjectID, Host: a.Host, IP: a.IP, Domain: a.Domain, Port: a.Port, Protocol: a.Protocol, Server: a.Server, Title: v.Title, Source: "assessment", SourceQuery: body, Tags: []string{"assessment:" + t.ID}}}
+ var imported database.AssetImportResult
+ var err error
+ if t.ProjectID != "" {
+ imported, err = h.DB.UpsertAssetsInProject(assets, session.UserID, session.ScopeFor("asset:write") == database.RBACScopeAll, t.ProjectID)
+ } else {
+ imported, err = h.DB.UpsertAssets(assets, session.UserID, session.ScopeFor("asset:write") == database.RBACScopeAll)
+ }
if err != nil {
h.fail(c, err)
return
@@ -397,3 +441,34 @@ func (h *AssessmentHandler) Publish(c *gin.Context) {
h.Audit.RecordOK(c, "assessment", "publish", "Published reviewed observation", "assessment", t.ID, map[string]interface{}{"step_id": st.ID, "kind": req.Kind})
c.JSON(200, gin.H{"result": result})
}
+
+// Bearer-authenticated integrations do not rely on ambient browser cookies.
+// Cookie mutations must originate from this host, including non-JSON controls.
+func assessmentMutationOriginAllowed(c *gin.Context) bool {
+ if c.Request.Method == http.MethodGet || c.Request.Method == http.MethodHead || c.GetHeader("Authorization") != "" {
+ return true
+ }
+ origin := c.GetHeader("Origin")
+ if origin != "" {
+ u, err := url.Parse(origin)
+ if err != nil || u.Host != c.Request.Host || (u.Scheme != "http" && u.Scheme != "https") {
+ c.AbortWithStatusJSON(403, gin.H{"error": "cross-origin assessment mutation denied"})
+ return false
+ }
+ }
+ if origin == "" && c.GetHeader("Sec-Fetch-Site") == "cross-site" {
+ c.AbortWithStatusJSON(403, gin.H{"error": "cross-site assessment mutation denied"})
+ return false
+ }
+ return true
+}
+
+func (h *AssessmentHandler) configuration() (*config.Config, error) {
+ if h.ConfigSnapshot != nil {
+ return h.ConfigSnapshot()
+ }
+ if h.Config == nil {
+ return nil, fmt.Errorf("configuration unavailable")
+ }
+ return h.Config, nil
+}
diff --git a/internal/handler/assessment_config.go b/internal/handler/assessment_config.go
new file mode 100644
index 00000000..4b812649
--- /dev/null
+++ b/internal/handler/assessment_config.go
@@ -0,0 +1,33 @@
+package handler
+
+import (
+ "encoding/json"
+ "fmt"
+
+ "cyberstrike-ai/internal/config"
+)
+
+// AssessmentConfigSnapshot shares the same lock as configuration writes. Deep
+// copying prevents a model request from combining a key, endpoint or approval
+// whitelist from different configuration revisions during hot reload.
+func (h *ConfigHandler) AssessmentConfigSnapshot() (*config.Config, error) {
+ h.mu.RLock()
+ if h.config == nil {
+ h.mu.RUnlock()
+ return nil, fmt.Errorf("configuration unavailable")
+ }
+ data, err := json.Marshal(struct {
+ OpenAI config.OpenAIConfig `json:"openai"`
+ AI config.AIConfig `json:"ai"`
+ Hitl config.HitlConfig `json:"hitl"`
+ }{h.config.OpenAI, h.config.AI, h.config.Hitl})
+ h.mu.RUnlock()
+ if err != nil {
+ return nil, err
+ }
+ var snapshot config.Config
+ if err = json.Unmarshal(data, &snapshot); err != nil {
+ return nil, err
+ }
+ return &snapshot, nil
+}
diff --git a/internal/handler/assessment_config_test.go b/internal/handler/assessment_config_test.go
new file mode 100644
index 00000000..d7ca4829
--- /dev/null
+++ b/internal/handler/assessment_config_test.go
@@ -0,0 +1,43 @@
+package handler
+
+import (
+ "fmt"
+ "sync"
+ "testing"
+
+ "cyberstrike-ai/internal/config"
+)
+
+func TestAssessmentConfigSnapshotIsConsistentAndDetached(t *testing.T) {
+ h := &ConfigHandler{config: &config.Config{}}
+ var wg sync.WaitGroup
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ for i := 0; i < 500; i++ {
+ h.mu.Lock()
+ tag := fmt.Sprint(i)
+ h.config.OpenAI = config.OpenAIConfig{Model: tag, APIKey: "fixture-" + tag, Headers: map[string]string{"revision": tag}}
+ h.config.Hitl.ToolWhitelist = []string{tag}
+ h.mu.Unlock()
+ }
+ }()
+ for i := 0; i < 500; i++ {
+ s, err := h.AssessmentConfigSnapshot()
+ if err != nil {
+ t.Fatal(err)
+ }
+ if s.OpenAI.Model != "" && (s.OpenAI.APIKey != "fixture-"+s.OpenAI.Model || s.Hitl.ToolWhitelist[0] != s.OpenAI.Model) {
+ t.Fatal("mixed configuration revisions")
+ }
+ if s.OpenAI.Headers != nil {
+ s.OpenAI.Headers["revision"] = "modified snapshot"
+ }
+ }
+ wg.Wait()
+ h.mu.RLock()
+ defer h.mu.RUnlock()
+ if h.config.OpenAI.Headers["revision"] == "modified snapshot" {
+ t.Fatal("snapshot shares mutable headers")
+ }
+}
diff --git a/internal/handler/assessment_openapi.go b/internal/handler/assessment_openapi.go
index d0f3f67f..d74fba52 100644
--- a/internal/handler/assessment_openapi.go
+++ b/internal/handler/assessment_openapi.go
@@ -36,14 +36,14 @@ func addAssessmentSpec(spec map[string]interface{}) {
body(control, map[string]interface{}{"type": "object", "properties": map[string]interface{}{"message": str()}})
paths["/api/assessments/{id}/control/{action}"] = map[string]interface{}{"post": control}
decision := op("Decide one exact tool call (also requires hitl:write)", "assessment:write", "id", "stepId")
- body(decision, map[string]interface{}{"type": "object", "required": []string{"approved"}, "properties": map[string]interface{}{"approved": map[string]interface{}{"type": "boolean"}}})
+ body(decision, map[string]interface{}{"type": "object", "required": []string{"approved", "approval_id"}, "properties": map[string]interface{}{"approval_id": str(), "approved": map[string]interface{}{"type": "boolean"}}})
paths["/api/assessments/{id}/steps/{stepId}/decision"] = map[string]interface{}{"post": decision}
paths["/api/assessments/{id}/steps/{stepId}/retry"] = map[string]interface{}{"post": op("Explicitly retry blocked work after reviewing partial effects", "assessment:write", "id", "stepId")}
- events := op("Read up to 200 durable events after a cursor", "assessment:read", "id")
+ events := op("Read up to 200 durable events after a cursor (approximately 1 MiB per page)", "assessment:read", "id")
events["parameters"] = append(events["parameters"].([]map[string]interface{}), map[string]interface{}{"in": "query", "name": "after", "schema": map[string]interface{}{"type": "integer", "format": "int64", "default": 0}})
paths["/api/assessments/{id}/events"] = map[string]interface{}{"get": events}
publish := op("Publish reviewed evidence (also requires destination write permissions)", "assessment:write", "id")
- body(publish, map[string]interface{}{"type": "object", "required": []string{"step_id", "index", "kind"}, "properties": map[string]interface{}{"step_id": str(), "index": map[string]interface{}{"type": "integer", "minimum": 0}, "kind": map[string]interface{}{"type": "string", "enum": []string{"fact", "asset", "vulnerability"}}}})
+ body(publish, map[string]interface{}{"type": "object", "required": []string{"step_id", "index", "kind", "revision"}, "properties": map[string]interface{}{"step_id": str(), "revision": str(), "index": map[string]interface{}{"type": "integer", "minimum": 0}, "kind": map[string]interface{}{"type": "string", "enum": []string{"fact", "asset", "vulnerability"}}}})
paths["/api/assessments/{id}/publish"] = map[string]interface{}{"post": publish}
report := op("Download an evidence-based Markdown report, including partial results", "assessment:read", "id")
report["responses"].(map[string]interface{})["200"] = map[string]interface{}{"description": "Markdown report", "content": map[string]interface{}{"text/markdown": map[string]interface{}{"schema": str()}}}
diff --git a/internal/handler/assessment_test.go b/internal/handler/assessment_test.go
index a9d3b368..f21f54df 100644
--- a/internal/handler/assessment_test.go
+++ b/internal/handler/assessment_test.go
@@ -158,7 +158,7 @@ func TestAssessmentAPIPublishEvidenceWithNoConversationAndStableIdentity(t *test
}
for i := 0; i < 2; i++ {
for _, kind := range []string{"fact", "vulnerability"} {
- w := request("POST", "/api/assessments/"+task.ID+"/publish", `{"step_id":"step","index":0,"kind":"`+kind+`"}`)
+ w := publishFixture(t, h, request, task.ID, `{"step_id":"step","index":0,"kind":"`+kind+`"}`)
if w.Code != 200 {
t.Fatalf("publish %s: %d %s", kind, w.Code, w.Body.String())
}
@@ -174,7 +174,7 @@ func TestAssessmentAPIPublishEvidenceWithNoConversationAndStableIdentity(t *test
}
// A global project read role must not widen a restricted project write role.
session.PermissionScopes = map[string]string{"assessment:write": database.RBACScopeAll, "project:read": database.RBACScopeAll, "project:write": database.RBACScopeOwn}
- w := request("POST", "/api/assessments/"+task.ID+"/publish", `{"step_id":"step","index":0,"kind":"fact"}`)
+ w := publishFixture(t, h, request, task.ID, `{"step_id":"step","index":0,"kind":"fact"}`)
if w.Code != 403 {
t.Fatalf("project scope widening: %d", w.Code)
}
@@ -200,7 +200,7 @@ func TestAssessmentAPIPublishesObservedAsset(t *testing.T) {
t.Fatal(err)
}
for i := 0; i < 2; i++ {
- w := request("POST", "/api/assessments/"+task.ID+"/publish", `{"step_id":"step","index":0,"kind":"asset"}`)
+ w := publishFixture(t, h, request, task.ID, `{"step_id":"step","index":0,"kind":"asset"}`)
if w.Code != 200 {
t.Fatal(w.Code, w.Body.String())
}
@@ -210,7 +210,7 @@ func TestAssessmentAPIPublishesObservedAsset(t *testing.T) {
t.Fatalf("asset duplicate/missing: %d %v", count, err)
}
delete(session.Permissions, "asset:write")
- w := request("POST", "/api/assessments/"+task.ID+"/publish", `{"step_id":"step","index":0,"kind":"asset"}`)
+ w := publishFixture(t, h, request, task.ID, `{"step_id":"step","index":0,"kind":"asset"}`)
if w.Code != 403 {
t.Fatal("asset permission bypass", w.Code)
}
@@ -232,3 +232,88 @@ func TestAssessmentAPIBindsRunToCurrentOperator(t *testing.T) {
t.Fatalf("wrong run identity: %+v", current)
}
}
+
+func publishFixture(t *testing.T, h *AssessmentHandler, request func(string, string, string) *httptest.ResponseRecorder, id, body string) *httptest.ResponseRecorder {
+ t.Helper()
+ var input map[string]any
+ if err := json.Unmarshal([]byte(body), &input); err != nil {
+ t.Fatal(err)
+ }
+ task, err := h.Engine.Store.Get(id)
+ if err != nil {
+ t.Fatal(err)
+ }
+ st := task.Step(input["step_id"].(string))
+ input["revision"] = assessment.EvidenceRevision(st.Evidence[int(input["index"].(float64))])
+ b, _ := json.Marshal(input)
+ return request("POST", "/api/assessments/"+id+"/publish", string(b))
+}
+
+func TestAssessmentApprovalScopesAndStaleRequest(t *testing.T) {
+ h, session, request := assessmentAPI(t)
+ task := createAPIAssessment(t, request)
+ call := &agent.ToolCall{ID: "call", Function: agent.FunctionCall{Name: "inspect", Arguments: map[string]interface{}{}}}
+ h.Engine.Store.Change(task.ID, "", "", "", func(t *assessment.Task) error {
+ t.Steps = []*assessment.Step{{ID: "step", Status: "awaiting_approval", Pending: call, ApprovalID: "new-request"}}
+ return nil
+ })
+ // A broad assessment role cannot widen the separate own-scoped HITL role.
+ session.UserID = "other-reviewer"
+ session.PermissionScopes = map[string]string{"assessment:write": database.RBACScopeAll, "hitl:write": database.RBACScopeOwn}
+ w := request("POST", "/api/assessments/"+task.ID+"/steps/step/decision", `{"approved":true,"approval_id":"new-request"}`)
+ if w.Code != 403 {
+ t.Fatal("HITL scope was widened", w.Code, w.Body.String())
+ }
+ session.UserID = task.OwnerID
+ session.PermissionScopes = nil
+ w = request("POST", "/api/assessments/"+task.ID+"/steps/step/decision", `{"approved":true,"approval_id":"old-request"}`)
+ if w.Code != 409 {
+ t.Fatal("stale approval accepted", w.Code, w.Body.String())
+ }
+}
+func TestAssessmentPublishRejectsChangedEvidence(t *testing.T) {
+ h, _, request := assessmentAPI(t)
+ task := createAPIAssessment(t, request)
+ old := assessment.Evidence{Kind: "finding", Title: "Reviewed candidate", Detail: "old observation", ExecutionIDs: []string{"exec"}}
+ revision := assessment.EvidenceRevision(old)
+ changed := old
+ changed.Detail = "Changed after review"
+ h.Engine.Store.Change(task.ID, "", "", "", func(t *assessment.Task) error {
+ t.Steps = []*assessment.Step{{ID: "step", Evidence: []assessment.Evidence{changed}}}
+ return nil
+ })
+ body := `{"step_id":"step","index":0,"kind":"vulnerability","revision":"` + revision + `"}`
+ w := request("POST", "/api/assessments/"+task.ID+"/publish", body)
+ if w.Code != 409 {
+ t.Fatal("unreviewed replacement published", w.Code)
+ }
+ var count int
+ h.DB.QueryRow(`SELECT count(*) FROM vulnerabilities`).Scan(&count)
+ if count != 0 {
+ t.Fatal("stale request wrote candidate")
+ }
+}
+func TestAssessmentJSONBodiesAreBounded(t *testing.T) {
+ _, _, request := assessmentAPI(t)
+ task := createAPIAssessment(t, request)
+ w := request("POST", "/api/assessments/"+task.ID+"/control/steer", `{"message":"`+strings.Repeat("x", 256<<10)+`"}`)
+ if w.Code != 413 {
+ t.Fatal("large body was parsed without bound", w.Code)
+ }
+}
+func TestAssessmentMutationOriginGuard(t *testing.T) {
+ for _, tc := range []struct {
+ origin, site, auth string
+ want bool
+ }{{"https://evil.test", "cross-site", "", false}, {"null", "", "", false}, {"", "cross-site", "", false}, {"https://csai.test", "same-origin", "", true}, {"https://integration.test", "cross-site", "Bearer fixture", true}} {
+ w := httptest.NewRecorder()
+ c, _ := gin.CreateTestContext(w)
+ c.Request = httptest.NewRequest("POST", "https://csai.test/api/assessments/x/control/start", nil)
+ c.Request.Header.Set("Origin", tc.origin)
+ c.Request.Header.Set("Sec-Fetch-Site", tc.site)
+ c.Request.Header.Set("Authorization", tc.auth)
+ if got := assessmentMutationOriginAllowed(c); got != tc.want {
+ t.Fatalf("origin %q: got %v", tc.origin, got)
+ }
+ }
+}
diff --git a/scripts/assessment-browser-smoke.mjs b/scripts/assessment-browser-smoke.mjs
index fee94951..0c2402d9 100644
--- a/scripts/assessment-browser-smoke.mjs
+++ b/scripts/assessment-browser-smoke.mjs
@@ -16,7 +16,9 @@ const task = { id: 'fixture-assessment', name: '本地测评 · 浏览器验证'
{ id: 's1', key: 'inspect', title: '检查响应和服务信息', instruction: '读取测试夹具并记录响应。', depends_on: [], status: 'completed', result: '响应证据已记录。', checkpoint: '服务响应已保存,后续可复用。', evidence: [{ kind: 'fact', title: '已记录测试响应', detail: '本地测试数据返回固定响应。', execution_ids: ['fixture-execution-1'] }] },
{ id: 's2', key: 'access', title: '核验访问控制边界', instruction: '对照测试夹具中的两个角色。', depends_on: ['inspect'], status: 'blocked', result: '等待补充测试角色。', evidence: [{ kind: 'finding', title: '待复核访问控制线索', detail: '仅为合成数据,需在授权环境中复核。', execution_ids: ['fixture-execution-2'] }] }
] };
+for (const step of task.steps) for (const evidence of step.evidence) evidence.revision="fixture-version";
const tasks = [task];
+let holdDetail=false;const detailWaiters=[];
const server = http.createServer(async (req, res) => {
const url = new URL(req.url, 'http://localhost');
const send = data => { res.setHeader('Content-Type', 'application/json'); res.end(JSON.stringify(data)); };
@@ -42,12 +44,13 @@ const server = http.createServer(async (req, res) => {
if (url.pathname.includes('/control/')) {
const action = url.pathname.split('/').at(-1);
if (action === 'steer') current.material += '\n' + input.message;
- else if (action === 'start') { current.status = 'awaiting_approval'; current.steps = [{ ...task.steps[0], id: 'review-step', status: 'awaiting_approval', pending: { id: 'call1', function: { name: 'inspect', arguments: { target: 'local-fixture' } } } }]; }
+ else if (action === 'start') { current.status = 'awaiting_approval'; current.steps = [{ ...task.steps[0], id: 'review-step', status: 'awaiting_approval', approval_id: 'fixture-request', pending: { id: 'call1', function: { name: 'inspect', arguments: { target: 'local-fixture' } } } }]; }
else current.status = action === 'pause' ? 'paused' : 'stopped';
current.updated_at = now(); send({ ok: true }); return;
}
- if (url.pathname.endsWith('/decision')) { current.status = input.approved ? 'completed' : 'blocked'; current.steps[0].status = current.status; current.steps[0].pending = null; current.updated_at = now(); send({ ok: true }); return; }
- if (url.pathname.endsWith('/publish')) { send({ result: { id: 'published' } }); return; }
+ if (url.pathname.endsWith('/decision')) { if(input.approval_id !== current.steps[0].approval_id) {res.statusCode=409;send({error:'stale approval'});return;} current.status = input.approved ? 'completed' : 'blocked'; current.steps[0].status = current.status; current.steps[0].pending = null; current.updated_at = now(); send({ ok: true }); return; }
+ if (url.pathname.endsWith('/publish')) { if(input.revision !== 'fixture-version'){res.statusCode=409;send({error:'stale evidence'});return;} send({ result: { id: 'published' } }); return; }
+ if(holdDetail && req.method === "GET") await new Promise(resolve => detailWaiters.push(resolve));
send({ assessment: current });
} catch (error) { res.statusCode = 500; send({ error: error.message }); }
});
@@ -78,6 +81,7 @@ try {
await click('[data-tab=chain]'); await waitFor("!!document.querySelector('#assessment-graph canvas')"); await screenshot('desktop-chain');
await evaluate("document.documentElement.dataset.theme='dark'"); await click('[data-tab=chain]'); await screenshot('desktop-dark-chain'); await evaluate("document.documentElement.dataset.theme='light'");
await click('[data-tab=evidence]'); assert.equal(await evaluate("document.querySelectorAll('[data-assessment-action=vulnerability]').length"), 1);
+ await click('[data-assessment-action=fact]'); await waitFor("document.getElementById('assessment-message').textContent.includes('已保存')");
await click('[data-tab=logs]'); assert.equal(await evaluate('window.XSS || 0'), 0, 'untrusted log rendered as HTML');
await click('[data-assessment-action=new]'); await waitFor("document.getElementById('assessment-create')?.open"); assert.equal(await evaluate("document.querySelector('[name=project_id] option:last-child').textContent"), '本地测试项目');
await evaluate(`document.querySelector('[name=name]').value='Created in browser';document.querySelector('[name=goal]').value='Inspect fixture';document.querySelector('[name=scope]').value='Local fixture';document.querySelector('[name=tools]').checked=true;document.getElementById('assessment-create-form').requestSubmit()`);
@@ -85,7 +89,7 @@ try {
assert.ok((await evaluate('location.hash')).startsWith('#assessments?task=created-'), 'created task deep link missing');
await click('[data-assessment-action=start]'); await waitFor("document.querySelector('#assessment-detail .assessment-status')?.dataset.status==='awaiting_approval'");
await click('[data-tab=plan]'); await waitFor("!!document.querySelector('[data-assessment-action=approve]')"); await click('[data-assessment-action=approve]'); await waitFor("document.querySelector('#assessment-detail .assessment-status')?.dataset.status==='completed'");
- await click('[data-id=fixture-assessment]'); await waitFor("document.querySelector('#assessment-detail h2')?.textContent==='本地测评 · 浏览器验证'");
+ holdDetail=true; await click('[data-id=fixture-assessment]'); assert.equal(await evaluate("document.querySelector('#assessment-detail [data-assessment-action=start]') === null"), true, 'stale task controls remained during switch'); holdDetail=false; detailWaiters.splice(0).forEach(resolve=>resolve()); await waitFor("document.querySelector('#assessment-detail h2')?.textContent==='本地测评 · 浏览器验证'");
await cdp('Emulation.setDeviceMetricsOverride', { width: 390, height: 844, deviceScaleFactor: 1, mobile: true });
await click('[data-tab=plan]'); await evaluate("document.getElementById('assessment-tab').scrollIntoView()"); await screenshot('mobile-plan');
assert.ok(await evaluate('document.documentElement.scrollWidth <= window.innerWidth + 1'), 'mobile horizontal overflow');
diff --git a/web/static/js/assessments.js b/web/static/js/assessments.js
index b1ba8b6e..12053d80 100644
--- a/web/static/js/assessments.js
+++ b/web/static/js/assessments.js
@@ -53,11 +53,11 @@
} else if (tab === 'plan') {
body.innerHTML = task.steps.map(s => '' + esc(s.title) + '
' + badge(s.status) + '
' + esc(s.key) + (s.depends_on && s.depends_on.length ? ' ← ' + esc(s.depends_on.join(', ')) : '') + '' + esc(s.instruction) + '
' + esc(s.result) + '
' + (s.checkpoint ? '' + esc(tr('checkpoint')) + ': ' + esc(s.checkpoint) + '
' : '') + (s.retired_reason ? '' + esc(tr('retiredReason')) + ': ' + esc(s.retired_reason) + '
' : '') +
(s.pending ? '' + esc(tr('approval')) + '
' + esc(tr('approvalHint')) + '
' + esc(s.pending.function.name) + '' + esc(JSON.stringify(s.pending.function.arguments, null, 2)) + '
' +
- (s.status === 'awaiting_approval' && !['completed', 'stopped', 'exhausted', 'failed'].includes(task.status) ? button('approve', tr('approve'), 'hitl:write', 'data-step="' + esc(s.id) + '"' + (!can('assessment:write') ? ' disabled' : '')) + button('deny', tr('deny'), 'hitl:write', 'data-step="' + esc(s.id) + '"' + (!can('assessment:write') ? ' disabled' : '')) : '
' + esc(tr('approved')) + '
') + '
' : '') +
+ (s.status === 'awaiting_approval' && !['completed', 'stopped', 'exhausted', 'failed'].includes(task.status) ? button('approve', tr('approve'), 'hitl:write', 'data-step="' + esc(s.id) + '" data-approval="' + esc(s.approval_id) + '"' + (!can('assessment:write') ? ' disabled' : '')) + button('deny', tr('deny'), 'hitl:write', 'data-step="' + esc(s.id) + '" data-approval="' + esc(s.approval_id) + '"' + (!can('assessment:write') ? ' disabled' : '')) : '' + esc(tr('approved')) + '
') + '' : '') +
(s.status === 'blocked' && resumable ? button('retry', tr('retry'), 'assessment:write', 'data-step="' + esc(s.id) + '"') : '') + '').join('') || '' + esc(tr('noSteps')) + '
';
} else if (tab === 'evidence') {
body.innerHTML = '' + esc(tr('candidateHint')) + '
' + task.steps.map(s => (s.evidence || []).map((v, i) => '' + esc(s.title) + ' · ' + esc(v.kind) + '' + esc(v.title) + '
' + esc(v.detail) + '
' + esc((v.execution_ids || []).join('\n')) + '
' +
- (v.kind !== 'gap' && v.execution_ids.length ? (task.project_id ? button('fact', tr('publishFact'), 'project:write', 'data-step="' + esc(s.id) + '" data-index="' + i + '"') : '') + (v.kind === 'asset' && v.asset ? button('asset', tr('publishAsset'), 'asset:write', 'data-step="' + esc(s.id) + '" data-index="' + i + '"') : '') + (v.kind === 'finding' ? button('vulnerability', tr('publishFinding'), 'vulnerability:write', 'data-step="' + esc(s.id) + '" data-index="' + i + '"') : '') : '') + '').join('')).join('');
+ (v.kind !== 'gap' && v.execution_ids.length ? (task.project_id ? button('fact', tr('publishFact'), 'project:write', 'data-step="' + esc(s.id) + '" data-index="' + i + '" data-revision="' + esc(v.revision) + '"') : '') + (v.kind === 'asset' && v.asset ? button('asset', tr('publishAsset'), 'asset:write', 'data-step="' + esc(s.id) + '" data-index="' + i + '" data-revision="' + esc(v.revision) + '"') : '') + (v.kind === 'finding' ? button('vulnerability', tr('publishFinding'), 'vulnerability:write', 'data-step="' + esc(s.id) + '" data-index="' + i + '" data-revision="' + esc(v.revision) + '"') : '') : '') + '').join('')).join('');
} else if (tab === 'logs') {
body.innerHTML = '' + events.map(ev => '
· ' + esc(ev.kind) + ' · ' + esc(ev.message.slice(0, 100)) + '
' + esc(ev.message) + '\n' + esc(ev.data ? JSON.stringify(ev.data, null, 2) : '') + '
').join('') + '
';
} else if (tab === 'chain') {
@@ -131,9 +131,9 @@
}
async function onClick(ev) {
const target = ev.target.closest('[data-assessment-action]'); if (!target || target.disabled) return;
- const action = target.dataset.assessmentAction; const id = selected;
+ const action = target.dataset.assessmentAction; const id = task && task.id === selected ? task.id : null;
try {
- if (action === 'select') { epoch++; selected = target.dataset.id; history.replaceState(null, '', '#assessments?task=' + encodeURIComponent(selected)); task = null; events = []; after = 0; delete root().dataset.updated; await refresh(true); return; }
+ if (action === 'select') { epoch++; selected = target.dataset.id; history.replaceState(null, '', '#assessments?task=' + encodeURIComponent(selected)); task = null; events = []; after = 0; delete root().dataset.updated; detail(); await refresh(true); return; }
if (action === 'tab') { tab = target.dataset.tab; detail(); return; }
if (action === 'refresh') { await refresh(true); return; }
if (action === 'new') { await createDialog(); return; }
@@ -143,10 +143,10 @@
target.disabled = true;
if (['start', 'pause', 'stop'].includes(action)) await api('/' + id + '/control/' + action, 'POST', {});
else if (action === 'steer') await api('/' + id + '/control/steer', 'POST', { message: document.getElementById('assessment-guidance').value });
- else if (action === 'approve' || action === 'deny') await api('/' + id + '/steps/' + target.dataset.step + '/decision', 'POST', { approved: action === 'approve' });
+ else if (action === 'approve' || action === 'deny') await api('/' + id + '/steps/' + target.dataset.step + '/decision', 'POST', { approved: action === 'approve', approval_id: target.dataset.approval });
else if (action === 'retry') { if (!window.confirm(tr('retryConfirm'))) return; await api('/' + id + '/steps/' + target.dataset.step + '/retry', 'POST', {}); }
else if (action === 'delete') { if (!window.confirm(tr('deleteConfirm'))) return; await api('/' + id, 'DELETE'); selected = ''; history.replaceState(null, '', '#assessments'); task = null; events = []; after = 0; }
- else if (action === 'fact' || action === 'vulnerability' || action === 'asset') { await api('/' + id + '/publish', 'POST', { step_id: target.dataset.step, index: Number(target.dataset.index), kind: action }); message(tr('published')); }
+ else if (action === 'fact' || action === 'vulnerability' || action === 'asset') { await api('/' + id + '/publish', 'POST', { step_id: target.dataset.step, index: Number(target.dataset.index), kind: action, revision: target.dataset.revision }); message(tr('published')); }
else if (action === 'report') {
const response = await fetch('/api/assessments/' + id + '/report', { credentials: 'same-origin' }); if (!response.ok) throw new Error(response.statusText);
const url = URL.createObjectURL(await response.blob()); const link = document.createElement('a'); link.href = url; link.download = 'assessment-' + id + '.md'; link.click(); setTimeout(() => URL.revokeObjectURL(url), 1000);