Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
109 changes: 102 additions & 7 deletions db/findings.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ type DBFinding struct {
Worker string
AssetIDs []int64
Status string
ReportState string // none / submitted / accepted / rejected / duplicate; separate from Status
PoELevel int // proof-of-exploitation level 0-4 (S1); 0 = none declared
VerificationStatus string // verified / unverified / blocked / not_assessed / false_positive
VerificationNote string // why the status was reached; empty when verified
Expand Down Expand Up @@ -65,6 +66,27 @@ func ValidFindingStatus(s string) bool {
return false
}

// Finding report stages (findings.report_state). A workflow stage after triage,
// not a verdict: a finding can be confirmed and submitted at the same time.
// RSI lesson extraction still reads findings.status.
const (
FindingReportNone = "none"
FindingReportSubmitted = "submitted"
FindingReportAccepted = "accepted"
FindingReportRejected = "rejected"
FindingReportDuplicate = "duplicate"
)

// ValidFindingReportState reports whether s is a known report stage.
func ValidFindingReportState(s string) bool {
switch s {
case FindingReportNone, FindingReportSubmitted, FindingReportAccepted,
FindingReportRejected, FindingReportDuplicate:
return true
}
return false
}

// Finding severity levels (findings.severity).
const (
SeverityCritical = "critical" // Critical
Expand Down Expand Up @@ -109,7 +131,7 @@ func (d *DB) AddFinding(taskID, nodeID int64, vulnclass, name, severity, summary
// findingSelectCols is the column list (with task_description join) every finding
// list query selects, so scanFinding stays in sync across callers.
const findingSelectCols = `f.id, f.task_id, f.node_id, f.vulnclass, COALESCE(f.name, ''), f.severity, f.summary,
f.evidence, f.worker, f.asset_ids, COALESCE(f.status, 'pending'), f.created_at,
f.evidence, f.worker, f.asset_ids, COALESCE(f.status, 'pending'), COALESCE(f.report_state, 'none'), f.created_at,
COALESCE(t.description, '') AS task_description, f.evidence_version, f.report_evidence_version,
f.poe_level, COALESCE(f.verification_status, 'unverified'), COALESCE(f.verification_note, ''),
f.counterevidence, f.confidence_rationale,
Expand All @@ -126,7 +148,7 @@ func scanFindings(rows interface {
f := &DBFinding{}
var aidsJSON string
if err := rows.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.PoELevel, &f.VerificationStatus, &f.VerificationNote, &f.Counterevidence, &f.ConfidenceRationale, &f.TrafficCount); err != nil {
&f.Summary, &f.Evidence, &f.Worker, &aidsJSON, &f.Status, &f.ReportState, &f.CreatedAt, &f.TaskDescription, &f.EvidenceVersion, &f.ReportEvidenceVersion, &f.PoELevel, &f.VerificationStatus, &f.VerificationNote, &f.Counterevidence, &f.ConfidenceRationale, &f.TrafficCount); err != nil {
return nil, err
}
_ = json.Unmarshal([]byte(aidsJSON), &f.AssetIDs)
Expand Down Expand Up @@ -160,6 +182,7 @@ func (d *DB) ListFindings(limit int) ([]*DBFinding, error) {
type FindingFilter struct {
Severity string // high | medium | low
Status string // pending | false_positive | ignored | resolved
ReportState string // none | submitted | accepted | rejected | duplicate
VerificationStatus string // verified | unverified | blocked | not_assessed | false_positive
VulnClass string
TaskID string // task id (in string form; empty/invalid = do not filter by task)
Expand Down Expand Up @@ -197,6 +220,7 @@ func (f FindingFilter) where() (string, []any) {
}
add("severity", f.Severity)
add("status", f.Status)
add("report_state", f.ReportState)
add("verification_status", f.VerificationStatus)
add("vulnclass", f.VulnClass)
// task_id is a bigint column, compared as an integer (it cannot go through
Expand Down Expand Up @@ -528,7 +552,7 @@ func (d *DB) ListFindingsForExport(f FindingFilter, ids []int64) ([]*DBFinding,
f := &DBFinding{}
var aidsJSON string
if err := rows.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.Summary, &f.Evidence, &f.Worker, &aidsJSON, &f.Status, &f.ReportState, &f.CreatedAt,
&f.TaskDescription, &f.EvidenceVersion, &f.ReportEvidenceVersion, &f.PoELevel, &f.VerificationStatus, &f.VerificationNote, &f.Counterevidence, &f.ConfidenceRationale, &f.TrafficCount, &f.Report); err != nil {
return nil, err
}
Expand All @@ -544,6 +568,8 @@ func (d *DB) ListFindingsForExport(f FindingFilter, ids []int64) ([]*DBFinding,
type FindingStats struct {
Total int `json:"total"`
Pending int `json:"pending"`
Submitted int `json:"submitted"`
Accepted int `json:"accepted"`
Critical int `json:"critical"`
High int `json:"high"`
Medium int `json:"medium"`
Expand All @@ -563,18 +589,20 @@ type FindingTaskOption struct {
Count int `json:"count"`
}

// FindingStats returns whole-table counts (by severity + pending) and the sorted
// set of distinct vuln classes.
// FindingStats returns whole-table counts (by severity, pending, and report
// stage) and the sorted set of distinct vuln classes.
func (d *DB) FindingStats() (*FindingStats, error) {
st := &FindingStats{VulnClasses: []string{}, Tasks: []FindingTaskOption{}}
err := d.QueryRow(`SELECT
COUNT(*),
COUNT(*) FILTER (WHERE status = 'pending'),
COUNT(*) FILTER (WHERE report_state = 'submitted'),
COUNT(*) FILTER (WHERE report_state = 'accepted'),
COUNT(*) FILTER (WHERE severity = 'critical'),
COUNT(*) FILTER (WHERE severity = 'high'),
COUNT(*) FILTER (WHERE severity = 'medium'),
COUNT(*) FILTER (WHERE severity = 'low')
FROM findings`).Scan(&st.Total, &st.Pending, &st.Critical, &st.High, &st.Medium, &st.Low)
FROM findings`).Scan(&st.Total, &st.Pending, &st.Submitted, &st.Accepted, &st.Critical, &st.High, &st.Medium, &st.Low)
if err != nil {
return nil, err
}
Expand Down Expand Up @@ -629,6 +657,8 @@ func (d *DB) FindingStats() (*FindingStats, error) {
cold := aggregate.FindingStats
st.Total += cold.Total
st.Pending += cold.Pending
st.Submitted += cold.Submitted
st.Accepted += cold.Accepted
st.Critical += cold.Critical
st.High += cold.High
st.Medium += cold.Medium
Expand Down Expand Up @@ -658,7 +688,7 @@ func (d *DB) GetFinding(id int64) (*DBFinding, error) {
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.Summary, &f.Evidence, &f.Worker, &aidsJSON, &f.Status, &f.ReportState, &f.CreatedAt,
&f.TaskDescription, &f.EvidenceVersion, &f.ReportEvidenceVersion, &f.PoELevel, &f.VerificationStatus, &f.VerificationNote, &f.Counterevidence, &f.ConfidenceRationale, &f.TrafficCount, &f.Report)
if err == sql.ErrNoRows {
return nil, nil
Expand Down Expand Up @@ -723,6 +753,71 @@ func (d *DB) SetFindingStatus(id int64, status string) (int64, error) {
return d.setFindingCol(id, "status", "status", status)
}

// SetFindingReportState updates one finding's report stage and mirrors it onto
// the originating exploration node's payload under "report_state". It does not
// register a status-change notification: report_state is a workflow stage, not
// a triage verdict. Returns rows affected.
func (d *DB) SetFindingReportState(id int64, state string) (int64, error) {
return d.setFindingCol(id, "report_state", "report_state", state)
}

// FindingReportStateBatchResult is one id's outcome in a bulk report-stage update.
type FindingReportStateBatchResult struct {
ID int64 `json:"id"`
From string `json:"from,omitempty"`
Found bool `json:"found"`
Changed bool `json:"changed"`
}

// SetFindingReportStates updates several findings to the same report stage in
// one transaction. Unknown ids come back as found=false instead of hiding the
// others; a database error rolls the whole batch back. No notification event
// is written — status-change pushes stay on findings.status.
func (d *DB) SetFindingReportStates(ctx context.Context, ids []int64, state string) ([]FindingReportStateBatchResult, error) {
out := make([]FindingReportStateBatchResult, 0, len(ids))
err := d.WithEvidenceTx(ctx, func(tx *sql.Tx) error {
for _, id := range ids {
from, found, changed, err := setFindingReportStateTx(ctx, tx, id, state)
if err != nil {
return err
}
out = append(out, FindingReportStateBatchResult{ID: id, From: from, Found: found, Changed: changed})
}
return nil
})
if err != nil {
return nil, err
}
return out, nil
}

func setFindingReportStateTx(ctx context.Context, tx *sql.Tx, id int64, state string) (from string, found bool, changed bool, err error) {
var nodeID sql.NullInt64
scanErr := tx.QueryRowContext(ctx, `SELECT COALESCE(report_state,'none'), node_id
FROM findings WHERE id=$1 FOR UPDATE`, id).Scan(&from, &nodeID)
if scanErr == sql.ErrNoRows {
return "", false, false, nil
}
if scanErr != nil {
return "", false, false, scanErr
}
found = true
if from == state {
return from, true, false, nil
}
if _, err := tx.ExecContext(ctx, `UPDATE findings SET report_state=$2 WHERE id=$1`, id, state); err != nil {
return from, true, false, err
}
if nodeID.Valid {
if _, err := tx.ExecContext(ctx, `UPDATE exploration_nodes
SET payload = jsonb_set(payload, '{report_state}', to_jsonb($1::text))
WHERE id = $2`, state, nodeID.Int64); err != nil {
return from, true, false, err
}
}
return from, true, true, nil
}

// SetFindingReportByNodeID sets the Markdown report on the standalone finding row
// whose node_id matches — report_finding returns that node id, so an agent tool
// can address the finding it just created. Returns rows affected (0 when no row).
Expand Down
131 changes: 131 additions & 0 deletions db/findings_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,25 @@ import (

// TestDeleteFinding verifies that deleting a finding removes both the findings
// row and its originating exploration node (kind='finding').
func TestValidFindingReportState(t *testing.T) {
for _, s := range []string{
FindingReportNone, FindingReportSubmitted, FindingReportAccepted,
FindingReportRejected, FindingReportDuplicate,
} {
if !ValidFindingReportState(s) {
t.Fatalf("%q should be valid", s)
}
}
for _, s := range []string{"", "confirmed", "pending", "SUBMITTED", "submitted "} {
if ValidFindingReportState(s) {
t.Fatalf("%q should be invalid", s)
}
}
if ValidFindingStatus(FindingReportSubmitted) {
t.Fatal("submitted must not be a triage status")
}
}

func TestDeleteFinding(t *testing.T) {
d, err := Open(testDSN(t))
if err != nil {
Expand Down Expand Up @@ -122,6 +141,115 @@ func TestSetFindingStatusMirrorsNodePayload(t *testing.T) {
}
}

func TestFindingReportState(t *testing.T) {
d, err := Open(testDSN(t))
if err != nil {
t.Skipf("postgres unavailable (%v) — skipping", err)
}
defer d.Close()

tk, err := d.CreateTask("finding report state", "goal", nil, 0, 0)
if err != nil {
t.Fatal(err)
}
defer d.DeleteTask(tk.ID)

es := d.Exploration(tk.ExplorationID)
nodeID, err := es.AddNode(KindFinding, map[string]any{"summary": "x", "severity": "high"}, 5, "confirmed", "worker", nil)
if err != nil {
t.Fatal(err)
}
fid, err := d.AddFinding(tk.ID, nodeID, "XSS", "reflected XSS", "high", "summary", "poc", "worker", nil)
if err != nil {
t.Fatal(err)
}
second, err := d.AddFinding(tk.ID, 0, "XSS", "other", "low", "summary", "poc", "worker", nil)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { d.Exec(`DELETE FROM notification_events WHERE finding_id IN ($1,$2)`, fid, second) })

one, err := d.GetFinding(fid)
if err != nil || one == nil || one.ReportState != FindingReportNone {
t.Fatalf("new finding report_state: %+v err=%v", one, err)
}

n, err := d.SetFindingReportState(fid, FindingReportSubmitted)
if err != nil || n != 1 {
t.Fatalf("SetFindingReportState: n=%d err=%v", n, err)
}
one, _ = d.GetFinding(fid)
if one.ReportState != FindingReportSubmitted {
t.Fatalf("report_state=%q", one.ReportState)
}
if one.Status != FindingPending {
t.Fatalf("triage status changed: %q", one.Status)
}

var payload []byte
if err := d.QueryRow(`SELECT payload FROM exploration_nodes WHERE id=$1`, nodeID).Scan(&payload); err != nil {
t.Fatal(err)
}
var p map[string]any
if err := json.Unmarshal(payload, &p); err != nil {
t.Fatal(err)
}
if p["report_state"] != FindingReportSubmitted {
t.Fatalf("payload report_state=%v", p["report_state"])
}

listed, total, err := d.ListFindingsPage(FindingFilter{TaskID: fmt.Sprintf("%d", tk.ID), ReportState: FindingReportSubmitted}, 1, 20)
if err != nil || total != 1 || len(listed) != 1 || listed[0].ID != fid {
t.Fatalf("filter submitted: total=%d listed=%d err=%v", total, len(listed), err)
}

st, err := d.FindingStats()
if err != nil || st.Submitted < 1 {
t.Fatalf("stats submitted undercount: %+v err=%v", st, err)
}

const missingID = int64(999999999)
results, err := d.SetFindingReportStates(context.Background(), []int64{fid, second, missingID}, FindingReportAccepted)
if err != nil {
t.Fatal(err)
}
if len(results) != 3 {
t.Fatalf("want 3 results, got %d", len(results))
}
if !results[0].Found || !results[0].Changed || results[0].From != FindingReportSubmitted {
t.Fatalf("first: %+v", results[0])
}
if !results[1].Found || !results[1].Changed || results[1].From != FindingReportNone {
t.Fatalf("second: %+v", results[1])
}
if results[2].Found || results[2].Changed {
t.Fatalf("missing: %+v", results[2])
}

again, err := d.SetFindingReportStates(context.Background(), []int64{fid}, FindingReportAccepted)
if err != nil || len(again) != 1 || again[0].Changed {
t.Fatalf("noop batch: %v %v", again, err)
}

var events int
if err := d.QueryRow(`SELECT count(*) FROM notification_events WHERE finding_id IN ($1,$2)`, fid, second).Scan(&events); err != nil || events != 0 {
t.Fatalf("report_state must not write notification_events: %d (%v)", events, err)
}

one, _ = d.GetFinding(fid)
if one.Status != FindingPending {
t.Fatalf("bulk report_state mutated triage: %q", one.Status)
}
if one.ReportState != FindingReportAccepted {
t.Fatalf("bulk report_state=%q", one.ReportState)
}

st, err = d.FindingStats()
if err != nil || st.Accepted < 2 {
t.Fatalf("stats accepted undercount: %+v err=%v", st, err)
}
}

// TestFindingsPageAndStats exercises ListFindingsPage (filter/sort/paging) and
// FindingStats against the live dev PG. It tags its rows with a unique vulnclass
// so assertions are isolated from any pre-existing data, and cleans up after.
Expand Down Expand Up @@ -226,6 +354,9 @@ func TestFindingsPageAndStats(t *testing.T) {
if one == nil || one.ID != ids[0] || one.Severity != "critical" || one.Name != "Critical Vulnerability Title" {
t.Fatalf("GetFinding mismatch: %+v", one)
}
if one.ReportState != FindingReportNone {
t.Fatalf("new finding report_state should be none, got %q", one.ReportState)
}
if one.Report != "" {
t.Fatalf("new finding report should be empty, got %q", one.Report)
}
Expand Down
4 changes: 2 additions & 2 deletions db/migrate_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -137,9 +137,9 @@ func assertEmbeddedApplied(t *testing.T, d *DB) []appliedMigration {
version int
name string
}{{1, llmRecordsMigration}, {2, llmUsageMigration}, {3, "0003_task_scope_icp_index.sql"}, {4, "0004_llm_usage_ts_index.sql"},
{5, "0005_traffic_rewrite_rules.sql"}, {6, "0006_activity_outbox.sql"}}
{5, "0005_traffic_rewrite_rules.sql"}, {6, "0006_activity_outbox.sql"}, {7, "0007_finding_report_state.sql"}}
if len(applied) != len(want) {
t.Fatalf("schema_migrations = %+v, want versions 1 to 6", applied)
t.Fatalf("schema_migrations = %+v, want versions 1 to 7", applied)
}
for i, w := range want {
content, err := fs.ReadFile(migrationsFS(), w.name)
Expand Down
5 changes: 5 additions & 0 deletions db/migrations/0007_finding_report_state.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
-- Report stage on findings, separate from triage status. Existing rows stay
-- 'none'. Values are validated server-side (no CHECK): none / submitted /
-- accepted / rejected / duplicate. RSI lessons still read findings.status.
ALTER TABLE findings ADD COLUMN IF NOT EXISTS report_state TEXT NOT NULL DEFAULT 'none';
CREATE INDEX IF NOT EXISTS idx_findings_report_state ON findings (report_state, created_at DESC);
5 changes: 5 additions & 0 deletions db/schema.sql
Original file line number Diff line number Diff line change
Expand Up @@ -1256,6 +1256,11 @@ ALTER TABLE findings ADD COLUMN IF NOT EXISTS verification_note TEXT NOT NULL DE
-- tested and did not work; confidence_rationale is why the conclusion holds.
ALTER TABLE findings ADD COLUMN IF NOT EXISTS counterevidence TEXT NOT NULL DEFAULT '';
ALTER TABLE findings ADD COLUMN IF NOT EXISTS confidence_rationale TEXT NOT NULL DEFAULT '';
-- Report stage after triage (none / submitted / accepted / rejected / duplicate).
-- Separate from status so a finding can be confirmed and submitted at once; RSI
-- lessons still read status. Server whitelist, no CHECK (same as status).
ALTER TABLE findings ADD COLUMN IF NOT EXISTS report_state TEXT NOT NULL DEFAULT 'none';
CREATE INDEX IF NOT EXISTS idx_findings_report_state ON findings (report_state, created_at DESC);

CREATE TABLE IF NOT EXISTS traffic_evidence_snapshots (
id TEXT PRIMARY KEY,
Expand Down
2 changes: 2 additions & 0 deletions db/task_archives.go
Original file line number Diff line number Diff line change
Expand Up @@ -770,6 +770,8 @@ FROM skill_usage WHERE (task_id=$1 OR exploration_id=$2) AND NOT found GROUP BY
{"findings", `SELECT COALESCE(jsonb_object_agg(name,n),'{}'::jsonb) FROM (SELECT COALESCE(NULLIF(severity,''),'unknown') name,count(*) n FROM findings WHERE task_id=$1 GROUP BY severity) x`, []any{taskID}},
{"finding_stats", `SELECT jsonb_build_object(
'total',count(*),'pending',count(*) FILTER (WHERE status='pending'),
'submitted',count(*) FILTER (WHERE report_state='submitted'),
'accepted',count(*) FILTER (WHERE report_state='accepted'),
'critical',count(*) FILTER (WHERE severity='critical'),'high',count(*) FILTER (WHERE severity='high'),
'medium',count(*) FILTER (WHERE severity='medium'),'low',count(*) FILTER (WHERE severity='low'),
'vulnclasses',COALESCE(jsonb_agg(DISTINCT vulnclass) FILTER (WHERE vulnclass<>''),'[]'::jsonb))
Expand Down
Loading
Loading