mirror of
https://github.com/RuoJi6/ARTEX.git
synced 2026-11-18 15:33:49 +08:00
fix(findings): protect historical reports and verify consolidation results
This commit is contained in:
1 parent
71ec0f0efd
commit
7db7b71cdb
15 files changed
+906
-74
No files matched your search
@@ -505,6 +505,15 @@ func (s *Server) runConversationTurn(ctx context.Context, cancel context.CancelC
|
||||
// turns may explain the sealed result; the result tool refuses to overwrite it.
|
||||
finishStatus, finishReason := "failed", "Agent 未能启动"
|
||||
if c.AgentKey == "reporter" {
|
||||
manualReview, err := s.isHistoricalFindingReview(c.ID)
|
||||
if err != nil {
|
||||
finishReason = err.Error()
|
||||
_, _ = s.m.pg.Exec(`UPDATE finding_case_review_runs SET state='failed',error=$2 WHERE conversation_id=$1`, c.ID, finishReason)
|
||||
return
|
||||
}
|
||||
if manualReview {
|
||||
ctx = agent.WithFindingCaseReview(ctx)
|
||||
}
|
||||
defer func() {
|
||||
state := "done"
|
||||
reason := ""
|
||||
@@ -515,6 +524,11 @@ func (s *Server) runConversationTurn(ctx context.Context, cancel context.CancelC
|
||||
reason = "整理已停止或服务关闭"
|
||||
}
|
||||
}
|
||||
if state == "done" && manualReview {
|
||||
if err := s.validateFindingReviewCompletion(c.ID); err != nil {
|
||||
state, reason = "failed", err.Error()
|
||||
}
|
||||
}
|
||||
_, _ = s.m.pg.Exec(`UPDATE finding_case_review_runs SET state=$2,error=$3 WHERE conversation_id=$1 AND state='running'`, c.ID, state, reason)
|
||||
}()
|
||||
}
|
||||
|
||||
@@ -0,0 +1,250 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/Autumn-27/artex/intercept"
|
||||
actool "github.com/Autumn-27/norma/tool"
|
||||
)
|
||||
|
||||
type findingReviewDecision struct {
|
||||
FindingID int64 `json:"finding_id"`
|
||||
Verdict string `json:"verdict"`
|
||||
Reason string `json:"reason"`
|
||||
RootCauseEvidence string `json:"root_cause_evidence"`
|
||||
}
|
||||
type findingReviewConclusion struct {
|
||||
Summary string `json:"summary"`
|
||||
Decisions []findingReviewDecision `json:"decisions"`
|
||||
}
|
||||
|
||||
func (s *Server) isHistoricalFindingReview(conv int64) (bool, error) {
|
||||
var exists bool
|
||||
err := s.m.pg.QueryRow(`SELECT EXISTS(SELECT 1 FROM finding_case_review_runs WHERE conversation_id=$1)`, conv).Scan(&exists)
|
||||
return exists, err
|
||||
}
|
||||
|
||||
func (s *Server) toolCompleteFindingCaseReview() actool.CoreTool {
|
||||
decision := objSchema(map[string]any{
|
||||
"finding_id": idParam("所选独立漏洞记录 ID"),
|
||||
"verdict": map[string]any{"type": "string", "enum": []string{"independent", "merged", "suggested"}},
|
||||
"reason": strParam("判断理由,接口或读写影响不同不能单独证明不同根因"),
|
||||
"root_cause_evidence": strParam("原始报告/证据中支持实际共同或不同根因的具体材料;不确定则说明缺失证据及已保存建议")}, "finding_id", "verdict", "reason", "root_cause_evidence")
|
||||
return wrTool("complete_finding_case_review", "历史整理结束前提交每条所选记录的根因判断并验收:必须已读取全部记录,疑似必须已有建议,归并必须已有完整最新统一报告。验收失败不能宣布完成。", objSchema(map[string]any{"summary": strParam("整理结果总结"), "decisions": map[string]any{"type": "array", "items": decision}}, "summary", "decisions"), func(ctx context.Context, raw json.RawMessage) (actool.Result, error) {
|
||||
var a findingReviewConclusion
|
||||
if err := json.Unmarshal(raw, &a); err != nil {
|
||||
return actool.Errorf(err.Error()), nil
|
||||
}
|
||||
conv := intercept.ConvIDFromContext(ctx)
|
||||
if err := s.saveFindingReviewConclusion(ctx, conv, a); err != nil {
|
||||
return actool.Errorf(err.Error()), nil
|
||||
}
|
||||
return actool.Text("历史整理验收通过;原始记录和报告保留,逐条根因判断已保存。"), nil
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) saveFindingReviewConclusion(ctx context.Context, conv int64, a findingReviewConclusion) error {
|
||||
if conv <= 0 {
|
||||
return errors.New("仅用于有上下文的历史整理会话")
|
||||
}
|
||||
return s.m.pg.WithEvidenceTx(ctx, func(tx *sql.Tx) error {
|
||||
var idsRaw, readsRaw json.RawMessage
|
||||
var state string
|
||||
if err := tx.QueryRow(`SELECT finding_ids,reviewed_ids,state FROM finding_case_review_runs WHERE conversation_id=$1 FOR UPDATE`, conv).Scan(&idsRaw, &readsRaw, &state); err != nil {
|
||||
return err
|
||||
}
|
||||
if state != "running" {
|
||||
return errors.New("整理会话未运行,不能提交验收")
|
||||
}
|
||||
var ids, reads []int64
|
||||
if err := json.Unmarshal(idsRaw, &ids); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := json.Unmarshal(readsRaw, &reads); err != nil {
|
||||
return err
|
||||
}
|
||||
read := map[int64]bool{}
|
||||
for _, id := range reads {
|
||||
read[id] = true
|
||||
}
|
||||
decisions := map[int64]findingReviewDecision{}
|
||||
for _, d := range a.Decisions {
|
||||
if _, ok := decisions[d.FindingID]; ok {
|
||||
return errors.New("重复的判断编号")
|
||||
}
|
||||
decisions[d.FindingID] = d
|
||||
}
|
||||
if strings.TrimSpace(a.Summary) == "" || len(ids) != len(decisions) {
|
||||
return errors.New("须提供总结和覆盖全部所选记录的逐条判断")
|
||||
}
|
||||
for _, id := range ids {
|
||||
d, ok := decisions[id]
|
||||
if !ok || !read[id] {
|
||||
return fmt.Errorf("请先 get_finding_record 读取并判断所选记录 #%d", id)
|
||||
}
|
||||
if strings.TrimSpace(d.Reason) == "" || strings.TrimSpace(d.RootCauseEvidence) == "" {
|
||||
return fmt.Errorf("记录 #%d 缺少判断理由或根因证据", id)
|
||||
}
|
||||
var cid sql.NullInt64
|
||||
if err := tx.QueryRow(`SELECT m.case_id FROM findings f LEFT JOIN finding_case_members m ON m.finding_id=f.id WHERE f.id=$1`, id).Scan(&cid); err != nil {
|
||||
return err
|
||||
}
|
||||
switch d.Verdict {
|
||||
case "merged":
|
||||
if !cid.Valid {
|
||||
return fmt.Errorf("记录 #%d 尚未归并", id)
|
||||
}
|
||||
case "suggested":
|
||||
var pending bool
|
||||
if err := tx.QueryRow(`SELECT EXISTS(SELECT 1 FROM finding_case_suggestions WHERE state='pending' AND (left_id=$1 OR right_id=$1))`, id).Scan(&pending); err != nil {
|
||||
return err
|
||||
}
|
||||
if !pending {
|
||||
return fmt.Errorf("记录 #%d 须先保存待确认建议", id)
|
||||
}
|
||||
case "independent":
|
||||
if cid.Valid {
|
||||
return fmt.Errorf("记录 #%d 已在文件夹中,不能声明为独立", id)
|
||||
}
|
||||
default:
|
||||
return errors.New("无效判断类型")
|
||||
}
|
||||
if cid.Valid {
|
||||
var report string
|
||||
var version, rv int64
|
||||
var active bool
|
||||
if err := tx.QueryRow(`SELECT report,version,report_version,active FROM finding_cases WHERE id=$1 FOR SHARE`, cid.Int64).Scan(&report, &version, &rv, &active); err != nil {
|
||||
return err
|
||||
}
|
||||
if !active || rv != version {
|
||||
return fmt.Errorf("文件夹 #%d 的统一报告待更新,请重新读取后更新", cid.Int64)
|
||||
}
|
||||
if err := validateUnifiedFindingReport(report); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
raw, err := json.Marshal(a)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = tx.Exec(`UPDATE finding_case_review_runs SET conclusion=$2 WHERE conversation_id=$1`, conv, string(raw))
|
||||
return err
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) validateFindingReviewCompletion(conv int64) error {
|
||||
var raw json.RawMessage
|
||||
if err := s.m.pg.QueryRow(`SELECT conclusion FROM finding_case_review_runs WHERE conversation_id=$1`, conv).Scan(&raw); err != nil {
|
||||
return err
|
||||
}
|
||||
var a findingReviewConclusion
|
||||
if err := json.Unmarshal(raw, &a); err != nil {
|
||||
return err
|
||||
}
|
||||
if len(a.Decisions) == 0 {
|
||||
return errors.New("整理未通过验收:未提交 complete_finding_case_review 逐条根因判断;请查看执行记录")
|
||||
}
|
||||
// Recheck after the last model turn; concurrent evidence changes invalidate completion.
|
||||
return s.saveFindingReviewConclusion(context.Background(), conv, a)
|
||||
}
|
||||
|
||||
// Require substantive sections and balanced fenced blocks. This validates report
|
||||
// completeness, not the truth of a model's root-cause claim or a live exploit.
|
||||
func validateUnifiedFindingReport(report string) error {
|
||||
aliases := [][]string{{"概述", "overview", "summary"}, {"影响", "impact"}, {"前置", "prerequisite", "precondition"}, {"复现", "reproduction", "reproduce"}, {"证据", "evidence"}, {"poc", "完整脚本", "验证脚本", "proof of concept"}, {"根因", "root cause"}, {"修复", "remediation", "recommendation", "fix"}}
|
||||
names := []string{"概述", "影响", "前置条件", "复现步骤", "证据", "PoC", "根因分析", "修复建议"}
|
||||
found := make([]bool, len(aliases))
|
||||
current := -1
|
||||
hasContent := false
|
||||
fence := ""
|
||||
finish := func() {
|
||||
if current >= 0 && hasContent {
|
||||
found[current] = true
|
||||
}
|
||||
}
|
||||
for _, line := range strings.Split(report, "\n") {
|
||||
t := strings.TrimSpace(line)
|
||||
if strings.HasPrefix(t, "```") || strings.HasPrefix(t, "~~~") {
|
||||
marker := t[:3]
|
||||
if fence == "" {
|
||||
fence = marker
|
||||
} else if fence == marker {
|
||||
fence = ""
|
||||
}
|
||||
continue
|
||||
}
|
||||
if fence != "" {
|
||||
if t != "" {
|
||||
hasContent = true
|
||||
}
|
||||
continue
|
||||
}
|
||||
if strings.HasPrefix(t, "#") {
|
||||
heading := strings.TrimLeft(t, "#")
|
||||
if len(heading) == len(t) || !strings.HasPrefix(heading, " ") {
|
||||
continue
|
||||
}
|
||||
// Subheadings belong to the current section unless they start another required section.
|
||||
next := -1
|
||||
lower := strings.ToLower(heading)
|
||||
for i, words := range aliases {
|
||||
for _, word := range words {
|
||||
if strings.Contains(lower, word) {
|
||||
next = i
|
||||
break
|
||||
}
|
||||
}
|
||||
if next >= 0 {
|
||||
break
|
||||
}
|
||||
}
|
||||
if next >= 0 {
|
||||
finish()
|
||||
current = next
|
||||
hasContent = false
|
||||
}
|
||||
continue
|
||||
}
|
||||
if t != "" && t != "---" && t != "***" && t != ">" {
|
||||
hasContent = true
|
||||
}
|
||||
}
|
||||
finish()
|
||||
if fence != "" {
|
||||
return errors.New("统一报告代码块未闭合,可能截断;请补全后再保存")
|
||||
}
|
||||
missing := []string{}
|
||||
for i, ok := range found {
|
||||
if !ok {
|
||||
missing = append(missing, names[i])
|
||||
}
|
||||
}
|
||||
if len(missing) > 0 {
|
||||
return fmt.Errorf("统一报告缺少有内容的章节:%s;请补全后保存", strings.Join(missing, "、"))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Server) historicalFindingReviewSelection(ctx context.Context) ([]int64, error) {
|
||||
conv := intercept.ConvIDFromContext(ctx)
|
||||
if conv == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
var raw json.RawMessage
|
||||
err := s.m.pg.QueryRow(`SELECT finding_ids FROM finding_case_review_runs WHERE conversation_id=$1`, conv).Scan(&raw)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return nil, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ids := []int64{}
|
||||
err = json.Unmarshal(raw, &ids)
|
||||
return ids, err
|
||||
}
|
||||
@@ -0,0 +1,170 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"github.com/Autumn-27/artex/intercept"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
const completeFindingReviewReport = `# 同一权限缺陷
|
||||
## 概述
|
||||
同一对象权限检查缺失。
|
||||
## 影响
|
||||
已验证读取其他账号的订单。
|
||||
## 前置条件
|
||||
已存在的低权会话和订单编号。
|
||||
## 复现步骤
|
||||
对照自己的订单,再查看其他账号订单,响应证明同一检查缺失。
|
||||
## 证据
|
||||
原报告的保存响应及命令输出,未重新探测。
|
||||
## PoC
|
||||
完整命令在原始证据中,此测试使用隔离材料。
|
||||
## 根因分析
|
||||
同一订单 handler 未验证订单所有者。
|
||||
## 修复建议
|
||||
统一验证请求者与订单所有者,并回归对象权限检查。
|
||||
`
|
||||
|
||||
func TestUnifiedFindingReportRejectsIncompleteAndTruncated(t *testing.T) {
|
||||
if err := validateUnifiedFindingReport(completeFindingReviewReport); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, s := range []string{strings.Split(completeFindingReviewReport, "## 根因分析")[0], completeFindingReviewReport + "\n```bash\nunclosed", strings.Replace(completeFindingReviewReport, "统一验证请求者与订单所有者,并回归对象权限检查。", "", 1)} {
|
||||
if err := validateUnifiedFindingReport(s); err == nil {
|
||||
t.Fatal("incomplete report accepted")
|
||||
}
|
||||
}
|
||||
// Section labels appearing inside a script are not real report sections.
|
||||
if err := validateUnifiedFindingReport("## 概述\ntext\n```bash\n" + completeFindingReviewReport + "\n```"); err == nil {
|
||||
t.Fatal("script comments counted as sections")
|
||||
}
|
||||
}
|
||||
|
||||
func TestFindingCaseReviewCompletionRequiresReadsAndFreshReport(t *testing.T) {
|
||||
s, task, ids := testCaseServer(t)
|
||||
runs, err := s.m.pg.CreateFindingCaseReviews(t.Context(), map[int64][]int64{task: ids})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
conv := runs[0].ConversationID
|
||||
defer s.m.pg.Exec(`DELETE FROM conversations WHERE id=$1`, conv)
|
||||
if _, err := s.m.pg.Exec(`UPDATE finding_case_review_runs SET state='running' WHERE conversation_id=$1`, conv); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ctx := intercept.WithConvID(context.Background(), conv)
|
||||
a := findingReviewConclusion{Summary: "根据对象权限检查的具体证据判断"}
|
||||
for _, id := range ids {
|
||||
a.Decisions = append(a.Decisions, findingReviewDecision{FindingID: id, Verdict: "merged", Reason: "同一 handler", RootCauseEvidence: "各记录的 baseline/proof 指向同一对象所有者校验缺失"})
|
||||
}
|
||||
if err := s.saveFindingReviewConclusion(ctx, conv, a); err == nil {
|
||||
t.Fatal("unread findings accepted")
|
||||
}
|
||||
for _, id := range ids {
|
||||
if _, err := s.performFindingCaseTool(ctx, "get_finding_record", findingCaseRequest{FindingID: json.RawMessage(fmt.Sprint(id))}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
cid, err := s.m.pg.MergeFindingCase(ctx, task, ids, "orders", "same concrete check", "reporter")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.saveFindingReviewConclusion(ctx, conv, a); err == nil {
|
||||
t.Fatal("missing unified report accepted")
|
||||
}
|
||||
c, _ := s.m.pg.GetFindingCase(cid)
|
||||
if err := s.m.pg.UpdateFindingCaseReport(ctx, cid, c.Version, "orders", completeFindingReviewReport, "high", "verified impact"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.saveFindingReviewConclusion(ctx, conv, a); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.validateFindingReviewCompletion(conv); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.checkCaseReviewScope(ctx, "update_finding_case_report", findingCaseRequest{CaseID: json.RawMessage(fmt.Sprint(cid))}); err == nil {
|
||||
t.Fatal("sealed review can still mutate")
|
||||
}
|
||||
if _, err := s.m.pg.Exec(`UPDATE findings SET evidence='new proof' WHERE id=$1`, ids[0]); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.validateFindingReviewCompletion(conv); err == nil {
|
||||
t.Fatal("stale group reported completed")
|
||||
}
|
||||
}
|
||||
|
||||
func TestFindingCaseReviewProtectsOriginalToolWrites(t *testing.T) {
|
||||
s, f, _ := trafficEvidenceServer(t)
|
||||
original, err := s.m.pg.GetFinding(f.FindingID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
runs, err := s.m.pg.CreateFindingCaseReviews(t.Context(), map[int64][]int64{*original.TaskID: {original.ID}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
conv := runs[0].ConversationID
|
||||
defer s.m.pg.Exec(`DELETE FROM conversations WHERE id=$1`, conv)
|
||||
ctx := intercept.WithConvID(context.Background(), conv)
|
||||
workflowCall(t, ctx, s.toolUpdateFindingReport(), map[string]any{"finding_id": f.NodeID, "report": "OVERWRITE", "evidence_version": original.EvidenceVersion}, true)
|
||||
if err := s.agentFindingTrafficAccess(ctx, f.FindingID, true); err == nil {
|
||||
t.Fatal("historical review can change evidence")
|
||||
}
|
||||
after, _ := s.m.pg.GetFinding(original.ID)
|
||||
if after.Report != original.Report || after.EvidenceVersion != original.EvidenceVersion || after.Status != original.Status || after.Severity != original.Severity {
|
||||
t.Fatal("original changed")
|
||||
}
|
||||
// Normal reporting is still able to write its own standalone report.
|
||||
workflowCall(t, context.Background(), s.toolUpdateFindingReport(), map[string]any{"finding_id": f.NodeID, "report": "normal report", "evidence_version": original.EvidenceVersion}, false)
|
||||
}
|
||||
|
||||
func TestFindingCaseReviewSuggestionNeedsSavedSuggestion(t *testing.T) {
|
||||
s, task, ids := testCaseServer(t)
|
||||
runs, err := s.m.pg.CreateFindingCaseReviews(t.Context(), map[int64][]int64{task: ids[:2]})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
conv := runs[0].ConversationID
|
||||
defer s.m.pg.Exec(`DELETE FROM conversations WHERE id=$1`, conv)
|
||||
s.m.pg.Exec(`UPDATE finding_case_review_runs SET state='running' WHERE conversation_id=$1`, conv)
|
||||
ctx := intercept.WithConvID(context.Background(), conv)
|
||||
a := findingReviewConclusion{Summary: "需人工确认共同组件"}
|
||||
for _, id := range ids[:2] {
|
||||
s.performFindingCaseTool(ctx, "get_finding_record", findingCaseRequest{FindingID: json.RawMessage(fmt.Sprint(id))})
|
||||
a.Decisions = append(a.Decisions, findingReviewDecision{FindingID: id, Verdict: "suggested", Reason: "同一边界但根因未确认", RootCauseEvidence: "原报告指向对象权限边界,缺少共同组件证据"})
|
||||
}
|
||||
if err := s.saveFindingReviewConclusion(ctx, conv, a); err == nil {
|
||||
t.Fatal("unpersisted suggestion accepted")
|
||||
}
|
||||
if _, err := s.m.pg.SuggestFindingCase(ctx, task, ids[0], ids[1], "orders", "common component unknown"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.saveFindingReviewConclusion(ctx, conv, a); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFindingCaseReviewCandidatesStayWithinSelection(t *testing.T) {
|
||||
s, task, ids := testCaseServer(t)
|
||||
runs, err := s.m.pg.CreateFindingCaseReviews(t.Context(), map[int64][]int64{task: ids[:2]})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
conv := runs[0].ConversationID
|
||||
defer s.m.pg.Exec(`DELETE FROM conversations WHERE id=$1`, conv)
|
||||
ctx := intercept.WithConvID(context.Background(), conv)
|
||||
a := findingCaseRequest{FindingID: json.RawMessage(fmt.Sprint(ids[0]))}
|
||||
v, err := s.performFindingCaseTool(ctx, "search_finding_duplicates", a)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if v.(map[string]any)["total"].(int) != 1 {
|
||||
t.Fatal("unselected candidates leaked", v)
|
||||
}
|
||||
v, err = s.performFindingCaseTool(context.Background(), "search_finding_duplicates", a)
|
||||
if err != nil || v.(map[string]any)["total"].(int) != 2 {
|
||||
t.Fatal("normal candidate search changed", v, err)
|
||||
}
|
||||
}
|
||||
+58
-32
@@ -7,7 +7,6 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/Autumn-27/artex/db"
|
||||
@@ -38,7 +37,7 @@ func (a findingCaseRequest) ids() []int64 {
|
||||
}
|
||||
func caseHTTPError(w http.ResponseWriter, err error) {
|
||||
code := 400
|
||||
if errors.Is(err, db.ErrFindingCaseConflict) {
|
||||
if errors.Is(err, db.ErrFindingCaseConflict) || errors.Is(err, db.ErrFindingCaseReviewBusy) {
|
||||
code = 409
|
||||
}
|
||||
writeErr(w, code, err.Error())
|
||||
@@ -211,6 +210,10 @@ func (s *Server) updateCaseReport(w http.ResponseWriter, r *http.Request) {
|
||||
if !decodeCaseRequest(w, r, &a) {
|
||||
return
|
||||
}
|
||||
if err := validateUnifiedFindingReport(a.Report); err != nil {
|
||||
caseHTTPError(w, err)
|
||||
return
|
||||
}
|
||||
if err := s.m.pg.UpdateFindingCaseReport(r.Context(), c.ID, a.Version, a.Title, a.Report, a.Severity, a.SeverityReason); err != nil {
|
||||
caseHTTPError(w, err)
|
||||
return
|
||||
@@ -260,6 +263,7 @@ func (s *Server) findingCaseTools() []actool.CoreTool {
|
||||
out = append(out, wrTool(spec.name, spec.desc, schema, handler))
|
||||
}
|
||||
}
|
||||
out = append(out, s.toolCompleteFindingCaseReview())
|
||||
return out
|
||||
}
|
||||
func (s *Server) performFindingCaseTool(ctx context.Context, name string, a findingCaseRequest) (any, error) {
|
||||
@@ -274,7 +278,15 @@ func (s *Server) performFindingCaseTool(ctx context.Context, name string, a find
|
||||
}
|
||||
switch name {
|
||||
case "search_finding_duplicates":
|
||||
items, total, err := s.m.pg.FindingCaseCandidates(fid, page, 20)
|
||||
scope, err := s.historicalFindingReviewSelection(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var scopes [][]int64
|
||||
if scope != nil {
|
||||
scopes = append(scopes, scope)
|
||||
}
|
||||
items, total, err := s.m.pg.FindingCaseCandidates(fid, page, 20, scopes...)
|
||||
return map[string]any{"items": items, "total": total, "page": page, "page_size": 20}, err
|
||||
case "get_finding_record":
|
||||
f, err := s.m.pg.GetFinding(fid)
|
||||
@@ -292,6 +304,11 @@ func (s *Server) performFindingCaseTool(ctx context.Context, name string, a find
|
||||
if cid > 0 {
|
||||
dto.CaseID = i64s(cid)
|
||||
}
|
||||
if conv := intercept.ConvIDFromContext(ctx); conv > 0 {
|
||||
if _, err := s.m.pg.Exec(`UPDATE finding_case_review_runs SET reviewed_ids=CASE WHEN reviewed_ids @> jsonb_build_array($2::bigint) THEN reviewed_ids ELSE reviewed_ids || jsonb_build_array($2::bigint) END WHERE conversation_id=$1 AND finding_ids @> jsonb_build_array($2::bigint)`, conv, f.ID); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return map[string]any{"finding": dto, "finding_node_id": f.NodeID}, nil
|
||||
case "merge_finding_records":
|
||||
id, err := s.m.pg.MergeFindingCase(ctx, parseProfileID(a.TaskID), a.ids(), a.Title, a.Reason, "reporter")
|
||||
@@ -318,6 +335,9 @@ func (s *Server) performFindingCaseTool(ctx context.Context, name string, a find
|
||||
}
|
||||
return map[string]any{"case": c, "members": members, "total": total, "page": page, "page_size": 20}, err
|
||||
case "update_finding_case_report":
|
||||
if err := validateUnifiedFindingReport(a.Report); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
err := s.m.pg.UpdateFindingCaseReport(ctx, cid, a.Version, a.Title, a.Report, a.Severity, a.SeverityReason)
|
||||
return map[string]bool{"ok": err == nil}, err
|
||||
}
|
||||
@@ -332,17 +352,20 @@ func (s *Server) seedFindingCaseTools() {
|
||||
if err != nil || a == nil {
|
||||
return
|
||||
}
|
||||
const flag = "finding_case_tools_v1"
|
||||
const flag = "finding_case_tools_v2_review"
|
||||
if v, _, _ := s.m.pg.GetSetting(flag); v == "true" {
|
||||
return
|
||||
}
|
||||
names := []string{}
|
||||
previous, _, _ := s.m.pg.GetSetting("finding_case_tools_v1")
|
||||
for _, t := range s.findingCaseTools() {
|
||||
schema, _ := json.Marshal(t.InputSchema())
|
||||
if err := s.m.pg.SeedTool(t.Name(), t.Description(), schema, json.RawMessage(`["reporter"]`)); err != nil {
|
||||
return
|
||||
}
|
||||
names = append(names, t.Name())
|
||||
if previous != "true" || t.Name() == "complete_finding_case_review" {
|
||||
names = append(names, t.Name())
|
||||
}
|
||||
}
|
||||
if err := s.m.pg.AddAgentToToolBinding("reporter", names); err != nil {
|
||||
return
|
||||
@@ -393,39 +416,36 @@ func (s *Server) reviewFindingCases(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
batches[*f.TaskID] = append(batches[*f.TaskID], fid)
|
||||
}
|
||||
// Validate every source before starting any batch.
|
||||
// Validate and snapshot every source before starting any batch.
|
||||
taskContexts := map[int64]triggeredRun{}
|
||||
for taskID := range batches {
|
||||
if _, ok := s.m.Task(i64s(taskID)); !ok {
|
||||
writeErr(w, 409, "任务不可用")
|
||||
return
|
||||
}
|
||||
}
|
||||
runs := []map[string]any{}
|
||||
for taskID, fids := range batches {
|
||||
t, ok := s.m.Task(strconv.FormatInt(taskID, 10))
|
||||
t, ok := s.m.Task(i64s(taskID))
|
||||
if !ok {
|
||||
writeErr(w, 409, "任务不可用")
|
||||
return
|
||||
}
|
||||
|
||||
taskContexts[taskID] = triggeredRun{taskDesc: t.Description, taskGoal: t.Goal}
|
||||
}
|
||||
reservations, err := s.m.pg.CreateFindingCaseReviews(r.Context(), batches)
|
||||
if err != nil {
|
||||
caseHTTPError(w, err)
|
||||
return
|
||||
}
|
||||
runs := []map[string]any{}
|
||||
for _, reservation := range reservations {
|
||||
taskID, fids := reservation.TaskID, reservation.FindingIDs
|
||||
taskContext := taskContexts[taskID]
|
||||
raw, _ := json.Marshal(fids)
|
||||
msg := fmt.Sprintf("人工选择整理:仅允许处理本任务所选 finding_ids=%s。先保留/生成各条独立报告,再在所选范围内判断同一缺陷,明确则归并,不确定提交建议,已成组则更新统一报告。不得归并未选择的记录,不探测目标。", raw)
|
||||
c, err := s.m.pg.CreateConversation("reporter", "漏洞整理 · task#"+t.ID, nil)
|
||||
if err != nil {
|
||||
caseHTTPError(w, err)
|
||||
return
|
||||
}
|
||||
if _, err := s.m.pg.Exec(`INSERT INTO finding_case_review_runs(conversation_id,task_id,finding_ids) VALUES($1,$2,$3)`, c.ID, taskID, string(raw)); err != nil {
|
||||
caseHTTPError(w, err)
|
||||
return
|
||||
}
|
||||
item := triggeredRun{agentKey: "reporter", title: c.Title, message: msg, taskID: taskID, taskDesc: t.Description, taskGoal: t.Goal, conversationID: c.ID}
|
||||
msg := fmt.Sprintf("人工选择整理(只读原始记录):本任务所选 finding_ids=%s。逐条读取已有报告,仅判断同一实际根因,明确则归并,不确定提交建议;已有组更新统一报告。禁止生成或覆盖原始报告、改评级状态、补绑证据,不归并未选记录,不探测目标。结束前调用 complete_finding_case_review 提交逐条判断并通过验收。", raw)
|
||||
item := triggeredRun{agentKey: "reporter", title: "漏洞整理 · task#" + i64s(taskID), message: msg, taskID: taskID, taskDesc: taskContext.taskDesc, taskGoal: taskContext.taskGoal, conversationID: reservation.ConversationID}
|
||||
cfg := s.readTriggerBehavior("reporter")
|
||||
s.queueMu.Lock()
|
||||
s.triggerCfg["reporter"] = cfg
|
||||
s.triggerQ["reporter"] = append(s.triggerQ["reporter"], item)
|
||||
s.pumpLocked("reporter")
|
||||
s.queueMu.Unlock()
|
||||
runs = append(runs, map[string]any{"conversation_id": c.ID, "task_id": i64s(taskID)})
|
||||
runs = append(runs, map[string]any{"conversation_id": reservation.ConversationID, "task_id": i64s(taskID)})
|
||||
}
|
||||
writeJSON(w, 202, map[string]any{"runs": runs})
|
||||
}
|
||||
@@ -460,8 +480,8 @@ func (s *Server) checkCaseReviewScope(ctx context.Context, name string, a findin
|
||||
if conv == 0 {
|
||||
return nil
|
||||
}
|
||||
var raw json.RawMessage
|
||||
err := s.m.pg.QueryRow(`SELECT finding_ids FROM finding_case_review_runs WHERE conversation_id=$1`, conv).Scan(&raw)
|
||||
var raw, conclusion json.RawMessage
|
||||
err := s.m.pg.QueryRow(`SELECT finding_ids,conclusion FROM finding_case_review_runs WHERE conversation_id=$1`, conv).Scan(&raw, &conclusion)
|
||||
if err != nil {
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return nil
|
||||
@@ -472,16 +492,22 @@ func (s *Server) checkCaseReviewScope(ctx context.Context, name string, a findin
|
||||
if err := json.Unmarshal(raw, &ids); err != nil {
|
||||
return err
|
||||
}
|
||||
if string(conclusion) != "{}" && (name == "merge_finding_records" || name == "suggest_finding_merge" || name == "update_finding_case_report") {
|
||||
return errors.New("整理判断已提交,不能在验收后继续修改")
|
||||
}
|
||||
allowed := map[int64]bool{}
|
||||
for _, id := range ids {
|
||||
allowed[id] = true
|
||||
}
|
||||
switch name {
|
||||
case "merge_finding_records", "suggest_finding_merge", "update_finding_report":
|
||||
checkIDs := a.ids()
|
||||
if name == "update_finding_report" {
|
||||
checkIDs = []int64{parseProfileID(a.FindingID)}
|
||||
case "search_finding_duplicates":
|
||||
if !allowed[parseProfileID(a.FindingID)] {
|
||||
return errors.New("历史整理只能检索所选记录的候选")
|
||||
}
|
||||
case "update_finding_report", "bind_finding_traffic", "report_finding":
|
||||
return errors.New("历史整理禁止修改原始报告、上报或证据;只能写归并关系及统一报告")
|
||||
case "merge_finding_records", "suggest_finding_merge":
|
||||
checkIDs := a.ids()
|
||||
for _, id := range checkIDs {
|
||||
if !allowed[id] {
|
||||
return errors.New("人工整理只能归并所选记录")
|
||||
|
||||
@@ -87,7 +87,7 @@ func TestFindingCaseAPIPaginationAndTools(t *testing.T) {
|
||||
}
|
||||
c := result.(map[string]any)["case"].(*db.FindingCase)
|
||||
a.Version = c.Version
|
||||
a.Report = "complete reproducible report"
|
||||
a.Report = completeFindingReviewReport
|
||||
a.Severity = "high"
|
||||
a.SeverityReason = "verified data disclosure"
|
||||
if _, err := s.performFindingCaseTool(ctx, "update_finding_case_report", a); err != nil {
|
||||
@@ -200,8 +200,8 @@ func TestFindingCaseSelectedReviewCannotRewriteOtherOriginal(t *testing.T) {
|
||||
if err := s.checkCaseReviewScope(ctx, "update_finding_report", findingCaseRequest{FindingID: json.RawMessage(fmt.Sprint(ids[1]))}); err == nil {
|
||||
t.Fatal("unselected original allowed")
|
||||
}
|
||||
if err := s.checkCaseReviewScope(ctx, "update_finding_report", findingCaseRequest{FindingID: json.RawMessage(fmt.Sprint(ids[0]))}); err != nil {
|
||||
t.Fatal(err)
|
||||
if err := s.checkCaseReviewScope(ctx, "update_finding_report", findingCaseRequest{FindingID: json.RawMessage(fmt.Sprint(ids[0]))}); err == nil {
|
||||
t.Fatal("selected original was allowed to be overwritten")
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -116,6 +116,11 @@ func objectProperty(parent map[string]any, key string) map[string]any {
|
||||
}
|
||||
|
||||
func (s *Server) agentFindingTrafficAccess(ctx context.Context, id int64, write bool) error {
|
||||
if write {
|
||||
if err := s.checkCaseReviewScope(ctx, "bind_finding_traffic", findingCaseRequest{}); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if id <= 0 {
|
||||
return errors.New("finding_id 必须为独立漏洞记录 ID;不是探索节点 ID")
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user