feat(findings): structured reproduction steps with per-step traffic bind

Align finding detail reproduction with AntiFox: store reproduction JSONB
(entry_point/prerequisites/steps/provenance), bind traffic via step_index,
syntax-highlight HTTP in steps/traffic panel, fall back to legacy evidence
when reproduction is absent. Old findings are not backfilled.
This commit is contained in:
MuCheng committed 2026-10-27 17:17:34 +08:00
1 parent a94b67ffd6
commit 93dc83165c
19 files changed
+493 -71

No files matched your search

+2 -2
View File
@@ -2016,6 +2016,6 @@ func (s *ExplorationStore) ActivityByIDsForTerminalIntents(ids []int64) ([]Activ
// AddStandaloneFinding writes a finding to the standalone findings table, which
// persists across task deletion (task_id / node_id become NULL when the task or
// exploration node is deleted). taskID and nodeID may be 0 (stored as NULL).
func (s *ExplorationStore) AddStandaloneFinding(taskID, nodeID int64, vulnclass, name, severity, summary, evidence, worker string, assetIDs []int64) (int64, error) {
return s.db.AddFinding(taskID, nodeID, vulnclass, name, severity, summary, evidence, worker, assetIDs)
func (s *ExplorationStore) AddStandaloneFinding(taskID, nodeID int64, vulnclass, name, severity, summary, evidence, worker string, assetIDs []int64, reproduction ...json.RawMessage) (int64, error) {
return s.db.AddFinding(taskID, nodeID, vulnclass, name, severity, summary, evidence, worker, assetIDs, reproduction...)
}
+71
View File
@@ -0,0 +1,71 @@
package db
import (
"database/sql"
"encoding/json"
"testing"
)
func TestFindingReproductionAndTrafficStepIndex(t *testing.T) {
d, err := Open(testDSN(t))
if err != nil {
t.Skipf("postgres unavailable (%v) — skipping", err)
}
defer d.Close()
repro := json.RawMessage(`{"entry_point":"POST /upload.php","steps":[{"request":"POST /upload.php HTTP/1.1","expected":"201","proves":"upload accepted"}]}`)
fid, err := d.AddFinding(0, 0, "upload", "upload", SeverityHigh, "summary", "poc", "test", nil, repro)
if err != nil {
t.Fatal(err)
}
defer d.DeleteFinding(fid)
f, err := d.GetFinding(fid)
if err != nil || string(f.Reproduction) != string(repro) {
t.Fatalf("reproduction round trip: %#v, %v", f, err)
}
snapshot := TrafficEvidenceSnapshot{SourceTrafficID: "source-1", CapturedAt: 1, URL: "https://example.test/upload.php", Method: "POST", Status: 201, ReqHash: "req", RespHash: "resp"}
snapshot.ID = TrafficSnapshotID(snapshot)
prepared := []PreparedTrafficEvidence{{Ref: TrafficRef{TrafficID: "source-1", StepIndex: 2, Role: "proof"}, Snapshot: snapshot}}
if err := d.WithEvidenceTx(t.Context(), func(tx *sql.Tx) error {
if err := InsertEvidenceSnapshotTx(tx, snapshot); err != nil {
return err
}
return AddFindingTrafficTx(tx, fid, prepared)
}); err != nil {
t.Fatal(err)
}
traffic, err := d.GetFindingTraffic(t.Context(), fid)
if err != nil || len(traffic.Bindings) != 1 || traffic.Bindings[0].StepIndex != 2 {
t.Fatalf("step binding round trip: %#v, %v", traffic, err)
}
zero := 0
if err := d.EditFindingTrafficStep(t.Context(), fid, traffic.Bindings[0].ID, traffic.Version, nil, nil, &zero, false, nil); err != nil {
t.Fatal(err)
}
traffic, err = d.GetFindingTraffic(t.Context(), fid)
if err != nil || traffic.Bindings[0].StepIndex != 0 {
t.Fatalf("step edit: %#v, %v", traffic, err)
}
if err := d.EditFindingTraffic(t.Context(), fid, traffic.Bindings[0].ID, traffic.Version, nil, nil, true, nil); err != nil {
t.Fatal(err)
}
}
func TestFindingWithoutReproductionLoadsNull(t *testing.T) {
d, err := Open(testDSN(t))
if err != nil {
t.Skipf("postgres unavailable (%v) — skipping", err)
}
defer d.Close()
fid, err := d.AddFinding(0, 0, "legacy", "legacy", SeverityLow, "summary", "evidence", "test", nil)
if err != nil {
t.Fatal(err)
}
defer d.DeleteFinding(fid)
f, err := d.GetFinding(fid)
if err != nil {
t.Fatal(err)
}
if f.Reproduction != nil {
t.Fatalf("legacy reproduction = %s, want nil", f.Reproduction)
}
}
+33 -8
View File
@@ -43,6 +43,7 @@ type TrafficRef struct {
TrafficID string `json:"traffic_id"`
Role string `json:"role"`
Note string `json:"note"`
StepIndex int `json:"step_index,omitempty"`
}
func NormalizeTrafficRefs(refs []TrafficRef) ([]TrafficRef, error) {
@@ -56,6 +57,9 @@ func NormalizeTrafficRefs(refs []TrafficRef) ([]TrafficRef, error) {
if ref.Role == "" {
ref.Role = "supporting"
}
if ref.StepIndex < 0 {
return nil, errors.New("step_index 不能为负数")
}
if !ValidTrafficRole(ref.Role) {
return nil, fmt.Errorf("无效的流量用途 %q", ref.Role)
}
@@ -95,6 +99,7 @@ type FindingTrafficBinding struct {
Role string `json:"role"`
Note string `json:"note"`
Position int `json:"position"`
StepIndex int `json:"step_index"`
CreatedAt time.Time `json:"created_at"`
Snapshot TrafficEvidenceSnapshot `json:"snapshot"`
}
@@ -215,8 +220,8 @@ func AddFindingTrafficTx(tx *sql.Tx, findingID int64, prepared []PreparedTraffic
if _, err := tx.Exec(`UPDATE traffic_evidence_snapshots SET unreferenced_at=NULL WHERE id=$1`, item.Snapshot.ID); err != nil {
return err
}
res, err := tx.Exec(`INSERT INTO finding_traffic_bindings(finding_id,snapshot_id,role,note,position)
VALUES($1,$2,$3,$4,$5) ON CONFLICT(finding_id,snapshot_id) DO NOTHING`, findingID, item.Snapshot.ID, item.Ref.Role, item.Ref.Note, position)
res, err := tx.Exec(`INSERT INTO finding_traffic_bindings(finding_id,snapshot_id,role,note,position,step_index)
VALUES($1,$2,$3,$4,$5,$6) ON CONFLICT(finding_id,snapshot_id) DO NOTHING`, findingID, item.Snapshot.ID, item.Ref.Role, item.Ref.Note, position, item.Ref.StepIndex)
if err != nil {
return err
}
@@ -248,7 +253,7 @@ func FindingTrafficTx(tx *sql.Tx, findingID int64) (*FindingTraffic, error) {
}
return nil, err
}
rows, err := tx.Query(`SELECT b.id,b.finding_id,b.snapshot_id,b.role,b.note,b.position,b.created_at,to_jsonb(s)
rows, err := tx.Query(`SELECT b.id,b.finding_id,b.snapshot_id,b.role,b.note,b.position,b.step_index,b.created_at,to_jsonb(s)
FROM finding_traffic_bindings b JOIN traffic_evidence_snapshots s ON s.id=b.snapshot_id WHERE b.finding_id=$1 ORDER BY b.position,b.id`, findingID)
if err != nil {
return nil, err
@@ -257,7 +262,7 @@ FROM finding_traffic_bindings b JOIN traffic_evidence_snapshots s ON s.id=b.snap
for rows.Next() {
var b FindingTrafficBinding
var raw []byte
if err := rows.Scan(&b.ID, &b.FindingID, &b.SnapshotID, &b.Role, &b.Note, &b.Position, &b.CreatedAt, &raw); err != nil {
if err := rows.Scan(&b.ID, &b.FindingID, &b.SnapshotID, &b.Role, &b.Note, &b.Position, &b.StepIndex, &b.CreatedAt, &raw); err != nil {
return nil, err
}
if err := json.Unmarshal(raw, &b.Snapshot); err != nil {
@@ -274,9 +279,16 @@ func (d *DB) GetFindingTraffic(ctx context.Context, findingID int64) (out *Findi
}
func (d *DB) EditFindingTraffic(ctx context.Context, findingID, bindingID, version int64, role, note *string, remove bool, order []int64) error {
return d.EditFindingTrafficStep(ctx, findingID, bindingID, version, role, note, nil, remove, order)
}
func (d *DB) EditFindingTrafficStep(ctx context.Context, findingID, bindingID, version int64, role, note *string, stepIndex *int, remove bool, order []int64) error {
if role != nil && !ValidTrafficRole(*role) {
return errors.New("无效的流量用途")
}
if stepIndex != nil && *stepIndex < 0 {
return errors.New("step_index 不能为负数")
}
return d.WithEvidenceTx(ctx, func(tx *sql.Tx) error {
if err := LockFindingEvidenceTx(tx, findingID, &version); err != nil {
return err
@@ -308,7 +320,7 @@ func (d *DB) EditFindingTraffic(ctx context.Context, findingID, bindingID, versi
if remove {
res, err = tx.Exec(`DELETE FROM finding_traffic_bindings WHERE finding_id=$1 AND id=$2`, findingID, bindingID)
} else {
res, err = tx.Exec(`UPDATE finding_traffic_bindings SET role=COALESCE($3,role),note=COALESCE($4,note) WHERE finding_id=$1 AND id=$2`, findingID, bindingID, role, note)
res, err = tx.Exec(`UPDATE finding_traffic_bindings SET role=COALESCE($3,role),note=COALESCE($4,note),step_index=COALESCE($5,step_index) WHERE finding_id=$1 AND id=$2`, findingID, bindingID, role, note, stepIndex)
}
if err != nil {
return err
@@ -329,6 +341,7 @@ type RecordFindingInput struct {
TaskID, ExplorationID, IntentID int64
VulnClass, Name, Severity, Summary, Evidence, Worker string
AssetIDs []int64
Reproduction json.RawMessage
}
type RecordedFinding struct {
@@ -361,7 +374,15 @@ func RecordFindingTx(ctx context.Context, tx *sql.Tx, in RecordFindingInput, pre
return nil, errors.New("intent_id 必须是本任务的意图(关联任务意图只读)")
}
}
payload, _ := json.Marshal(map[string]any{"vulnclass": in.VulnClass, "name": in.Name, "severity": in.Severity, "summary": in.Summary, "evidence": map[string]any{"by": in.Worker, "poc": in.Evidence}})
payloadMap := map[string]any{"vulnclass": in.VulnClass, "name": in.Name, "severity": in.Severity, "summary": in.Summary, "evidence": map[string]any{"by": in.Worker, "poc": in.Evidence}}
if len(in.Reproduction) > 0 && string(in.Reproduction) != "null" {
var reproduction any
if err := json.Unmarshal(in.Reproduction, &reproduction); err != nil {
return nil, fmt.Errorf("reproduction JSON 无效: %w", err)
}
payloadMap["reproduction"] = reproduction
}
payload, _ := json.Marshal(payloadMap)
out := &RecordedFinding{}
if err := tx.QueryRow(`INSERT INTO exploration_nodes(exploration_id,kind,payload,priority,state,origin)
VALUES($1,'finding',$2,9,'confirmed',$3) RETURNING id`, in.ExplorationID, string(payload), in.Worker).Scan(&out.NodeID); err != nil {
@@ -382,8 +403,12 @@ VALUES($1,'finding',$2,9,'confirmed',$3) RETURNING id`, in.ExplorationID, string
assets = []int64{}
}
raw, _ := json.Marshal(assets)
if err := tx.QueryRow(`INSERT INTO findings(task_id,node_id,vulnclass,name,severity,summary,evidence,worker,asset_ids)
VALUES(NULLIF($1,0),$2,$3,$4,$5,$6,$7,$8,$9) RETURNING id`, in.TaskID, out.NodeID, in.VulnClass, in.Name, in.Severity, in.Summary, in.Evidence, in.Worker, string(raw)).Scan(&out.FindingID); err != nil {
var repro any
if len(in.Reproduction) > 0 && string(in.Reproduction) != "null" {
repro = string(in.Reproduction)
}
if err := tx.QueryRow(`INSERT INTO findings(task_id,node_id,vulnclass,name,severity,summary,evidence,worker,asset_ids,reproduction)
VALUES(NULLIF($1,0),$2,$3,$4,$5,$6,$7,$8,$9,$10) RETURNING id`, in.TaskID, out.NodeID, in.VulnClass, in.Name, in.Severity, in.Summary, in.Evidence, in.Worker, string(raw), repro).Scan(&out.FindingID); err != nil {
return nil, err
}
// 在**同一事务**里登记一条推送事件:提交即保证「漏洞落库」与「推送任务存在」
+10 -1
View File
@@ -51,6 +51,12 @@ func restoreFindingTrafficTx(tx *sql.Tx, snapshot *TaskArchiveSnapshot) error {
if !allowed[sid] || !ValidTrafficRole(role) {
return errors.New("invalid archived evidence binding")
}
if rawStep, exists := row["step_index"]; exists && rawStep != nil {
step, ok := jsonInt64(rawStep)
if !ok || step < 0 {
return errors.New("invalid archived evidence step index")
}
}
var owned bool
if err = tx.QueryRow(`SELECT EXISTS(SELECT 1 FROM findings WHERE id=$1 AND task_id=$2)`, fid, snapshot.TaskID).Scan(&owned); err != nil {
return err
@@ -61,7 +67,10 @@ func restoreFindingTrafficTx(tx *sql.Tx, snapshot *TaskArchiveSnapshot) error {
}
if len(rows) > 0 {
raw, _ := json.Marshal(rows)
if _, err = tx.Exec(`INSERT INTO finding_traffic_bindings SELECT * FROM json_populate_recordset(NULL::finding_traffic_bindings,$1::json)`, string(raw)); err != nil {
if _, err = tx.Exec(`INSERT INTO finding_traffic_bindings
(id,finding_id,snapshot_id,role,note,position,created_at,step_index)
SELECT id,finding_id,snapshot_id,role,note,position,created_at,COALESCE(step_index,0)
FROM json_to_recordset($1::json) AS x(id bigint,finding_id bigint,snapshot_id text,role text,note text,position integer,created_at timestamptz,step_index integer)`, string(raw)); err != nil {
return err
}
_, err = tx.Exec(`UPDATE traffic_evidence_snapshots s SET unreferenced_at=NULL WHERE EXISTS(SELECT 1 FROM finding_traffic_bindings b WHERE b.snapshot_id=s.id)`)
+34 -8
View File
@@ -34,11 +34,30 @@ type DBFinding struct {
Worker string
AssetIDs []int64
Status string
Report string // 详细报告(Markdown);仅 GetFinding 填充,列表查询不带
Report string // 详细报告(Markdown);仅 GetFinding 填充,列表查询不带
Reproduction json.RawMessage // 结构化复现过程; NULL 表示未提供
CreatedAt time.Time
TaskDescription string // populated via LEFT JOIN on tasks
}
// Reproduction is the structured reproduction recipe captured by report_finding.
// It is kept as JSON in the findings table so older rows remain nullable while
// callers that need the shape can decode it without inventing steps from prose.
type Reproduction struct {
EntryPoint string `json:"entry_point,omitempty"`
Prerequisites []string `json:"prerequisites,omitempty"`
Steps []ReproStep `json:"steps,omitempty"`
Provenance string `json:"provenance,omitempty"`
}
type ReproStep struct {
Request string `json:"request"`
Response string `json:"response,omitempty"`
Expected string `json:"expected,omitempty"`
Proves string `json:"proves,omitempty"`
TrafficIDs []string `json:"traffic_ids,omitempty"`
}
// Finding triage states (findings.status).
const (
FindingPending = "pending" // 待处理
@@ -82,7 +101,7 @@ func ValidSeverity(s string) bool {
// AddFinding inserts a finding into the standalone findings table. taskID and
// nodeID may be 0 (stored as NULL). name may be "" (frontend falls back to
// vulnclass). Returns the new finding id.
func (d *DB) AddFinding(taskID, nodeID int64, vulnclass, name, severity, summary, evidence, worker string, assetIDs []int64) (int64, error) {
func (d *DB) AddFinding(taskID, nodeID int64, vulnclass, name, severity, summary, evidence, worker string, assetIDs []int64, reproduction ...json.RawMessage) (int64, error) {
aidsJSON, _ := json.Marshal(assetIDs)
if assetIDs == nil {
aidsJSON = []byte("[]")
@@ -94,11 +113,15 @@ func (d *DB) AddFinding(taskID, nodeID int64, vulnclass, name, severity, summary
if nodeID > 0 {
nid = &nodeID
}
var repro any
if len(reproduction) > 0 && len(reproduction[0]) > 0 && string(reproduction[0]) != "null" {
repro = string(reproduction[0])
}
var id int64
err := d.QueryRow(
`INSERT INTO findings (task_id, node_id, vulnclass, name, severity, summary, evidence, worker, asset_ids)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9) RETURNING id`,
tid, nid, vulnclass, name, severity, summary, evidence, worker, string(aidsJSON),
`INSERT INTO findings (task_id, node_id, vulnclass, name, severity, summary, evidence, worker, asset_ids, reproduction)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10) RETURNING id`,
tid, nid, vulnclass, name, severity, summary, evidence, worker, string(aidsJSON), repro,
).Scan(&id)
return id, err
}
@@ -646,14 +669,14 @@ func (d *DB) FindingStats() (*FindingStats, error) {
// it also selects `report` — that column is only needed on the detail page.
func (d *DB) GetFinding(id int64) (*DBFinding, error) {
f := &DBFinding{}
var aidsJSON string
err := d.QueryRow(`SELECT `+findingSelectCols+`, COALESCE(f.report, '')
var aidsJSON, reproduction string
err := d.QueryRow(`SELECT `+findingSelectCols+`, COALESCE(f.report, ''), COALESCE(f.reproduction::text, '')
FROM findings f
LEFT JOIN tasks t ON f.task_id = t.id
WHERE f.id = $1`, id).Scan(
&f.ID, &f.TaskID, &f.NodeID, &f.VulnClass, &f.Name, &f.Severity,
&f.Summary, &f.Evidence, &f.Worker, &aidsJSON, &f.Status, &f.CreatedAt,
&f.TaskDescription, &f.EvidenceVersion, &f.ReportEvidenceVersion, &f.TrafficCount, &f.Report)
&f.TaskDescription, &f.EvidenceVersion, &f.ReportEvidenceVersion, &f.TrafficCount, &f.Report, &reproduction)
if err == sql.ErrNoRows {
return nil, nil
}
@@ -661,6 +684,9 @@ func (d *DB) GetFinding(id int64) (*DBFinding, error) {
return nil, err
}
_ = json.Unmarshal([]byte(aidsJSON), &f.AssetIDs)
if reproduction != "" {
f.Reproduction = json.RawMessage(reproduction)
}
return f, nil
}
+4
View File
@@ -1167,6 +1167,7 @@ CREATE TABLE IF NOT EXISTS findings (
ALTER TABLE findings ADD COLUMN IF NOT EXISTS status TEXT NOT NULL DEFAULT 'pending';
ALTER TABLE findings ADD COLUMN IF NOT EXISTS name TEXT NOT NULL DEFAULT '';
ALTER TABLE findings ADD COLUMN IF NOT EXISTS report TEXT NOT NULL DEFAULT '';
ALTER TABLE findings ADD COLUMN IF NOT EXISTS reproduction JSONB;
CREATE INDEX IF NOT EXISTS idx_findings_task ON findings(task_id, created_at DESC);
CREATE INDEX IF NOT EXISTS idx_findings_time ON findings(created_at DESC);
CREATE INDEX IF NOT EXISTS idx_findings_status ON findings(status, created_at DESC);
@@ -1231,11 +1232,14 @@ CREATE TABLE IF NOT EXISTS finding_traffic_bindings (
snapshot_id TEXT NOT NULL REFERENCES traffic_evidence_snapshots(id),
role TEXT NOT NULL DEFAULT 'supporting',
note TEXT NOT NULL DEFAULT '',
step_index INTEGER NOT NULL DEFAULT 0,
position INTEGER NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
UNIQUE(finding_id, snapshot_id)
);
ALTER TABLE finding_traffic_bindings ADD COLUMN IF NOT EXISTS step_index INTEGER NOT NULL DEFAULT 0;
CREATE INDEX IF NOT EXISTS idx_finding_traffic_order ON finding_traffic_bindings(finding_id, position, id);
CREATE INDEX IF NOT EXISTS idx_finding_traffic_step ON finding_traffic_bindings(finding_id, step_index, position, id);
CREATE INDEX IF NOT EXISTS idx_finding_traffic_snapshot ON finding_traffic_bindings(snapshot_id);
-- =====================================================================