fix(db): preserve rsi_lesson_evidence withdrawal history on re-confirmation (#269)

This commit is contained in:
BaaRai
2026-11-21 16:17:07 +01:00
parent 59d514e37c
commit d15166c476
5 changed files with 138 additions and 14 deletions
+2 -3
View File
@@ -170,9 +170,8 @@ func (d *DB) ExtractLessonsForTask(ctx context.Context, taskID int64) (int, erro
if _, err := d.ExecContext(ctx, `
INSERT INTO rsi_lesson_evidence(lesson_id,source_kind,source_id,detail)
VALUES($1,$2,$3,$4)
ON CONFLICT (lesson_id, source_kind, source_id) DO UPDATE SET
detail=EXCLUDED.detail,
withdrawn_at=NULL`,
ON CONFLICT (lesson_id, source_kind, source_id) WHERE withdrawn_at IS NULL
DO UPDATE SET detail=EXCLUDED.detail`,
id, sourceKind, sourceID, lessonText(detail, lessonDetailMax)); err != nil {
return err
}
+92
View File
@@ -2,6 +2,7 @@ package db
import (
"context"
"database/sql"
"fmt"
"strings"
"testing"
@@ -1482,3 +1483,94 @@ func lessonStatusSupport(t *testing.T, d *DB, lessonID int64) (status string, su
}
return status, support
}
// Re-confirming a previously withdrawn finding must NOT clear withdrawn_at on
// the old evidence row: the withdrawal row stays for history and re-confirmation
// inserts a new live row (#269).
func TestReconfirmingFindingPreservesWithdrawalHistory(t *testing.T) {
d := notifyTestDB(t)
ctx := context.Background()
task, err := d.CreateTaskWithOptions("withdraw-history", "test withdrawal history", TaskCreateOptions{})
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = d.DeleteTask(task.ID) })
es := d.Exploration(task.ExplorationID)
rec, err := es.RecordFinding(ctx, RecordFindingInput{
TaskID: task.ID,
ExplorationID: task.ExplorationID,
VulnClass: "ssrf",
Name: "SSRF on webhook",
Severity: "high",
Summary: "SSRF on webhook endpoint",
Worker: "worker-1",
})
if err != nil {
t.Fatal(err)
}
fid := rec.FindingID
// 1. Confirm -> positive lesson created with 1 live evidence row.
if _, _, _, err := d.SetFindingStatusWithNotify(ctx, fid, FindingConfirmed); err != nil {
t.Fatal(err)
}
var lessonID, firstRowID int64
if err := d.QueryRow(`SELECT e.lesson_id, e.id
FROM rsi_lesson_evidence e JOIN rsi_lessons l ON l.id=e.lesson_id
WHERE l.kind='positive' AND e.source_kind='finding' AND e.source_id=$1 AND e.withdrawn_at IS NULL`,
fid).Scan(&lessonID, &firstRowID); err != nil {
t.Fatalf("positive evidence row: %v", err)
}
// 2. Flip to false_positive -> firstRowID gets withdrawn_at set.
if _, _, _, err := d.SetFindingStatusWithNotify(ctx, fid, FindingFalsePositive); err != nil {
t.Fatal(err)
}
var withdrawnAt1 sql.NullTime
if err := d.QueryRow(`SELECT withdrawn_at FROM rsi_lesson_evidence WHERE id=$1`, firstRowID).Scan(&withdrawnAt1); err != nil {
t.Fatal(err)
}
if !withdrawnAt1.Valid {
t.Fatalf("expected firstRowID=%d to have withdrawn_at set after false_positive", firstRowID)
}
// 3. Re-confirm -> old withdrawal row stays untouched, new live row is inserted.
if _, _, _, err := d.SetFindingStatusWithNotify(ctx, fid, FindingConfirmed); err != nil {
t.Fatal(err)
}
var withdrawnAt2 sql.NullTime
if err := d.QueryRow(`SELECT withdrawn_at FROM rsi_lesson_evidence WHERE id=$1`, firstRowID).Scan(&withdrawnAt2); err != nil {
t.Fatal(err)
}
if !withdrawnAt2.Valid || !withdrawnAt2.Time.Equal(withdrawnAt1.Time) {
t.Fatalf("old withdrawal row %d was altered: got %v, want %v", firstRowID, withdrawnAt2, withdrawnAt1)
}
var secondRowID int64
if err := d.QueryRow(`SELECT id FROM rsi_lesson_evidence
WHERE lesson_id=$1 AND source_kind='finding' AND source_id=$2 AND withdrawn_at IS NULL`,
lessonID, fid).Scan(&secondRowID); err != nil {
t.Fatalf("new live evidence row missing after re-confirm: %v", err)
}
if secondRowID == firstRowID {
t.Fatalf("re-confirm reused old row %d instead of inserting a new live row", firstRowID)
}
// 4. Repeat extraction is idempotent: still 1 live + 1 withdrawn row.
if _, err := d.ExtractLessonsForTask(ctx, task.ID); err != nil {
t.Fatal(err)
}
var totalRows, liveRows, withdrawnRows int
if err := d.QueryRow(`SELECT COUNT(*), COUNT(*) FILTER (WHERE withdrawn_at IS NULL), COUNT(*) FILTER (WHERE withdrawn_at IS NOT NULL)
FROM rsi_lesson_evidence WHERE lesson_id=$1 AND source_kind='finding' AND source_id=$2`,
lessonID, fid).Scan(&totalRows, &liveRows, &withdrawnRows); err != nil {
t.Fatal(err)
}
if totalRows != 2 || liveRows != 1 || withdrawnRows != 1 {
t.Fatalf("evidence rows = total %d live %d withdrawn %d, want 2 / 1 / 1", totalRows, liveRows, withdrawnRows)
}
if status, support := lessonStatusSupport(t, d, lessonID); status != "candidate" || support != 1 {
t.Fatalf("lesson status=%s support=%d, want candidate / 1", status, support)
}
}
+14 -5
View File
@@ -139,9 +139,10 @@ func assertEmbeddedApplied(t *testing.T, d *DB) []appliedMigration {
}{{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"}, {7, "0007_finding_report_state.sql"},
{8, "0008_traffic_evidence_rewrite_flag.sql"}, {9, "0009_llm_context.sql"}, {10, "0010_dashboard_usage_indexes.sql"},
{11, "0011_traffic_tamper_hooks.sql"}, {12, "0012_lesson_withdrawn.sql"}}
{11, "0011_traffic_tamper_hooks.sql"}, {12, "0012_lesson_withdrawn.sql"},
{13, "0013_lesson_evidence_history.sql"}}
if len(applied) != len(want) {
t.Fatalf("schema_migrations = %+v, want versions 1 to 12", applied)
t.Fatalf("schema_migrations = %+v, want versions 1 to 13", applied)
}
for i, w := range want {
content, err := fs.ReadFile(migrationsFS(), w.name)
@@ -432,10 +433,11 @@ func TestLessonWithdrawnMigrationKeepsExistingEvidence(t *testing.T) {
}
// The migration file alone adds the column to a table without it.
for _, q := range []string{
`DROP INDEX IF EXISTS uq_rsi_lesson_evidence_live`,
`ALTER TABLE rsi_lesson_evidence DROP COLUMN withdrawn_at`,
string(migrationSQL),
`ALTER TABLE rsi_lesson_evidence DROP COLUMN withdrawn_at`,
`DELETE FROM schema_migrations WHERE version=12`,
`DELETE FROM schema_migrations WHERE version IN (12, 13)`,
`INSERT INTO rsi_lessons(dedupe_key,kind,cue,action,status)
VALUES ('legacy-lesson','positive','xss','Confirmed xss: legacy','adopted')`,
`INSERT INTO rsi_lesson_evidence(lesson_id,source_kind,source_id,detail)
@@ -479,8 +481,15 @@ func TestLessonWithdrawnMigrationKeepsExistingEvidence(t *testing.T) {
}
check(d)
before := readApplied(t, d)
if last := before[len(before)-1]; last.version != 12 || last.name != migrationName {
t.Fatalf("last applied migration = %+v, want 0012", last)
has12 := false
for _, m := range before {
if m.version == 12 && m.name == migrationName {
has12 = true
break
}
}
if !has12 {
t.Fatalf("applied migrations = %+v, missing 0012", before)
}
d.Close()
@@ -0,0 +1,22 @@
-- Keep withdrawal history on rsi_lesson_evidence (#269): replace the composite
-- primary key (lesson_id, source_kind, source_id) with a surrogate id and a
-- partial unique index over live rows (withdrawn_at IS NULL). Re-confirming a
-- previously withdrawn finding inserts a new live row while preserving the old
-- withdrawal row and its withdrawn_at timestamp.
ALTER TABLE rsi_lesson_evidence ADD COLUMN IF NOT EXISTS id BIGSERIAL;
DO $$
BEGIN
IF EXISTS (
SELECT 1 FROM pg_constraint
WHERE conrelid = 'rsi_lesson_evidence'::regclass
AND contype = 'p'
AND conname = 'rsi_lesson_evidence_pkey'
AND array_length(conkey, 1) > 1
) THEN
ALTER TABLE rsi_lesson_evidence DROP CONSTRAINT rsi_lesson_evidence_pkey;
ALTER TABLE rsi_lesson_evidence ADD PRIMARY KEY (id);
END IF;
END $$;
CREATE UNIQUE INDEX IF NOT EXISTS uq_rsi_lesson_evidence_live
ON rsi_lesson_evidence(lesson_id, source_kind, source_id)
WHERE withdrawn_at IS NULL;
+8 -6
View File
@@ -1560,19 +1560,21 @@ CREATE TABLE IF NOT EXISTS rsi_lessons (
CREATE INDEX IF NOT EXISTS idx_rsi_lessons_scope ON rsi_lessons(company_id, category_id, status);
CREATE INDEX IF NOT EXISTS idx_rsi_lessons_kind ON rsi_lessons(kind, updated_at DESC);
-- One row per (lesson, source). The primary key makes extraction idempotent:
-- a second run for the same task adds nothing and cannot inflate support.
-- withdrawn_at keeps a retracted source on the row. Support and selection
-- count only rows that are still live.
-- Live evidence is unique per (lesson, source) via uq_rsi_lesson_evidence_live,
-- making repeated extraction idempotent without inflating support. Withdrawn
-- rows keep withdrawn_at set for history; re-confirming inserts a new live row.
CREATE TABLE IF NOT EXISTS rsi_lesson_evidence (
id BIGSERIAL PRIMARY KEY,
lesson_id BIGINT NOT NULL REFERENCES rsi_lessons(id) ON DELETE CASCADE,
source_kind TEXT NOT NULL,
source_id BIGINT NOT NULL,
detail TEXT NOT NULL DEFAULT '',
withdrawn_at TIMESTAMPTZ,
PRIMARY KEY (lesson_id, source_kind, source_id)
withdrawn_at TIMESTAMPTZ
);
ALTER TABLE rsi_lesson_evidence ADD COLUMN IF NOT EXISTS withdrawn_at TIMESTAMPTZ;
CREATE UNIQUE INDEX IF NOT EXISTS uq_rsi_lesson_evidence_live
ON rsi_lesson_evidence(lesson_id, source_kind, source_id)
WHERE withdrawn_at IS NULL;
-- What was shown to which task, and in which mode (shadow = logged but not
-- injected; inject = appended to the planner/worker system prompt).