ARTEX/server/finding_verification_test.go
BaaRai dccb066169 fix(server): scope update_finding_report writes to the caller's task
The node-id write path (GHSA-ph8r) resolved the finding and wrote its
report/verification with no task check, so any agent holding the tool
could overwrite another task's finding. Refuse unless the caller's task
owns the finding; inherited findings stay read-only and an unknown caller
fails closed. Triggered chat runs carry their source task(s) as a
server-owned context value (RunInfo is empty for ChatAgent turns), never
from tool arguments.
2026-11-30 23:20:40 +01:00

292 lines
12 KiB
Go

package server
import (
"context"
"encoding/json"
"fmt"
"net/http/httptest"
"os"
"path/filepath"
"strconv"
"strings"
"testing"
"github.com/Autumn-27/artex/agent"
"github.com/Autumn-27/artex/db"
actool "github.com/Autumn-27/norma/tool"
)
const verificationBody = "HTTP/1.1 200 OK\nuser admin:\tx7\nend of dump"
func TestNormalizeEvidenceText(t *testing.T) {
cases := map[string]string{
" a\t\tb\r\n c ": "a b c",
"Admin User": "Admin User", // case is kept
"": "",
}
for in, want := range cases {
if got := normalizeEvidenceText(in); got != want {
t.Fatalf("normalize(%q) = %q, want %q", in, got, want)
}
}
}
func TestShortQuoteCapsAtSixtyRunes(t *testing.T) {
long := strings.Repeat("é", 100)
if got := []rune(shortQuote(long)); len(got) != verificationNoteQuoteLen {
t.Fatalf("shortQuote kept %d runes, want %d", len(got), verificationNoteQuoteLen)
}
}
// verificationFixture returns a server with one finding whose traffic "a" is
// bound with the given role and whose response body is verificationBody.
func verificationFixture(t *testing.T, role string) (*Server, *db.RecordedFinding, func(string, string, string) *httptest.ResponseRecorder) {
t.Helper()
s, f, req := trafficEvidenceServer(t)
seedServerEvidenceFlow(t, s, "a", []byte(verificationBody))
if role != "" {
base := fmt.Sprintf("/api/exploration/findings/%d/traffic", f.FindingID)
w := req("POST", base, fmt.Sprintf(`{"traffic_refs":[{"traffic_id":"a","role":%q}]}`, role))
if w.Code != 200 {
t.Fatalf("bind: %d %s", w.Code, w.Body)
}
}
return s, f, req
}
// updateReport calls update_finding_report with the node id, as the agent does.
// The call carries the finding's owning task, which is what scopes the write.
func updateReport(t *testing.T, s *Server, nodeID int64, extra string) (string, bool) {
t.Helper()
ctx := findingTaskContext(t, s, nodeID)
in := fmt.Sprintf(`{"finding_id":%d,"report":"# report","evidence_version":null%s}`, nodeID, extra)
res, err := s.toolUpdateFindingReport().Call(ctx, json.RawMessage(in), &actool.ToolContext{})
if err != nil {
t.Fatal(err)
}
return res.Flatten(), res.IsError
}
// findingTaskContext returns a tool ctx attributed to the task that owns the
// finding behind nodeID, i.e. the context a reporter run for that task carries.
func findingTaskContext(t *testing.T, s *Server, nodeID int64) context.Context {
t.Helper()
ctx := context.Background()
id, err := s.m.pg.FindingIDByNodeID(nodeID)
if err != nil {
t.Fatalf("resolve finding for node %d: %v", nodeID, err)
}
f, err := s.m.pg.GetFinding(id)
if err != nil || f == nil || f.TaskID == nil {
t.Fatalf("load finding %d: %v %+v", id, err, f)
}
return agent.WithRunInfo(ctx, agent.RunInfo{TaskID: *f.TaskID})
}
func storedVerification(t *testing.T, s *Server, findingID int64) (status string, poe int, note, report string) {
t.Helper()
if err := s.m.pg.QueryRow(`SELECT verification_status, poe_level, verification_note, report FROM findings WHERE id=$1`, findingID).
Scan(&status, &poe, &note, &report); err != nil {
t.Fatal(err)
}
return
}
func TestVerificationNoBindingPOE4Unverified(t *testing.T) {
s, f, _ := verificationFixture(t, "")
msg, isErr := updateReport(t, s, f.NodeID, `,"poe_level":4,"evidence_quotes":["x7"]`)
if isErr || !strings.Contains(msg, "verification: unverified - no proof traffic bound") {
t.Fatalf("unexpected result: err=%v %q", isErr, msg)
}
status, poe, note, report := storedVerification(t, s, f.FindingID)
if status != db.VerificationUnverified || poe != 4 || note != "no proof traffic bound" || report == "" {
t.Fatalf("stored: status=%s poe=%d note=%q report=%q", status, poe, note, report)
}
}
func TestVerificationProofPOE3MissingQuoteUnverified(t *testing.T) {
s, f, _ := verificationFixture(t, "proof")
msg, isErr := updateReport(t, s, f.NodeID, `,"poe_level":3,"evidence_quotes":["secret=999"]`)
if isErr || !strings.Contains(msg, "warning:") {
t.Fatalf("unexpected result: err=%v %q", isErr, msg)
}
status, _, note, report := storedVerification(t, s, f.FindingID)
if status != db.VerificationUnverified || !strings.HasPrefix(note, "quote not found in bound evidence: secret=999") || report == "" {
t.Fatalf("stored: status=%s note=%q report=%q", status, note, report)
}
}
func TestVerificationProofPOE3ExactQuoteVerified(t *testing.T) {
s, f, _ := verificationFixture(t, "verification")
// The quote differs from the body only in whitespace runs: it must still match.
msg, isErr := updateReport(t, s, f.NodeID, `,"poe_level":3,"evidence_quotes":["user admin: x7"]`)
if isErr || !strings.Contains(msg, "verification: verified (POE L3)") {
t.Fatalf("unexpected result: err=%v %q", isErr, msg)
}
status, poe, note, _ := storedVerification(t, s, f.FindingID)
if status != db.VerificationVerified || poe != 3 || note != "" {
t.Fatalf("stored: status=%s poe=%d note=%q", status, poe, note)
}
}
func TestVerificationShortQuoteUnverified(t *testing.T) {
s, f, _ := verificationFixture(t, "proof")
// "x7" is present in the body but below verificationMinQuoteRunes: it must not count.
msg, isErr := updateReport(t, s, f.NodeID, `,"poe_level":3,"evidence_quotes":["x7"]`)
if isErr || !strings.Contains(msg, "verification: unverified - evidence quote too short") {
t.Fatalf("unexpected result: err=%v %q", isErr, msg)
}
status, _, note, _ := storedVerification(t, s, f.FindingID)
if status != db.VerificationUnverified || note != "evidence quote too short" {
t.Fatalf("stored: status=%s note=%q", status, note)
}
}
func TestVerificationOldStyleCallUnverifiedWithoutError(t *testing.T) {
s, f, _ := verificationFixture(t, "proof")
msg, isErr := updateReport(t, s, f.NodeID, "")
if isErr || !strings.Contains(msg, "verification: unverified") {
t.Fatalf("unexpected result: err=%v %q", isErr, msg)
}
status, poe, _, report := storedVerification(t, s, f.FindingID)
if status != db.VerificationUnverified || poe != 0 || report == "" {
t.Fatalf("stored: status=%s poe=%d report=%q", status, poe, report)
}
}
func TestVerificationUnreadableStoreNotAssessedReportSaved(t *testing.T) {
s, f, _ := verificationFixture(t, "proof")
// Remove the blobs behind the bound snapshot: the evidence store cannot open the body.
if err := os.RemoveAll(filepath.Join(s.m.dir, "evidence")); err != nil {
t.Fatal(err)
}
msg, isErr := updateReport(t, s, f.NodeID, `,"poe_level":3,"evidence_quotes":["user admin: x7"]`)
if isErr || !strings.Contains(msg, "verification: not_assessed") {
t.Fatalf("unexpected result: err=%v %q", isErr, msg)
}
status, _, note, report := storedVerification(t, s, f.FindingID)
if status != db.VerificationNotAssessed || !strings.HasPrefix(note, "evidence body unreadable") || report == "" {
t.Fatalf("stored: status=%s note=%q report=%q", status, note, report)
}
}
func TestVerificationRejectsOutOfRangePOE(t *testing.T) {
s, f, _ := verificationFixture(t, "proof")
msg, isErr := updateReport(t, s, f.NodeID, `,"poe_level":9`)
if !isErr || !strings.Contains(msg, "invalid poe_level 9") {
t.Fatalf("unexpected result: err=%v %q", isErr, msg)
}
if _, _, _, report := storedVerification(t, s, f.FindingID); report != "" {
t.Fatal("report must not be written when the input is rejected")
}
}
func TestVerificationColumnsExistWithHonestDefaults(t *testing.T) {
s, f, _ := trafficEvidenceServer(t)
var n int
if err := s.m.pg.QueryRow(`SELECT count(*) FROM information_schema.columns
WHERE table_name='findings' AND column_name IN ('poe_level','verification_status','verification_note')`).Scan(&n); err != nil {
t.Fatal(err)
}
if n != 3 {
t.Fatalf("expected 3 verification columns, found %d", n)
}
status, poe, note, _ := storedVerification(t, s, f.FindingID)
if status != db.VerificationUnverified || poe != 0 || note != "" {
t.Fatalf("new row: status=%s poe=%d note=%q", status, poe, note)
}
}
// reportCall invokes update_finding_report with the given ctx, asserting only the
// transport (not the tool's IsError, which the caller decides).
func reportCall(t *testing.T, s *Server, ctx context.Context, nodeID int64, report, extra string) (string, bool) {
t.Helper()
in := fmt.Sprintf(`{"finding_id":%d,"report":%q%s}`, nodeID, report, extra)
res, err := s.toolUpdateFindingReport().Call(ctx, json.RawMessage(in), &actool.ToolContext{})
if err != nil {
t.Fatal(err)
}
return res.Flatten(), res.IsError
}
// TestUpdateFindingReportScopedToOwningTask is the GHSA-ph8r regression: the
// node-id write path used to be task-agnostic, so any agent holding the tool
// could overwrite another task's report and verification. The caller's task
// (RunInfo for task runs, SourceTasks for triggered chat runs) must own the
// finding; inherited findings stay read-only; an unknown caller fails closed.
func TestUpdateFindingReportScopedToOwningTask(t *testing.T) {
s, f, _ := trafficEvidenceServer(t)
pg := s.m.pg
stored, err := pg.GetFinding(f.FindingID)
if err != nil || stored == nil || stored.TaskID == nil {
t.Fatalf("load finding: %v %+v", err, stored)
}
ownerID := *stored.TaskID
// The owning task may write its own finding.
ownCtx := agent.WithRunInfo(context.Background(), agent.RunInfo{TaskID: ownerID})
msg, isErr := reportCall(t, s, ownCtx, f.NodeID, "## owner report", "")
if isErr {
t.Fatalf("owner update refused: %q", msg)
}
if _, _, _, report := storedVerification(t, s, f.FindingID); report != "## owner report" {
t.Fatalf("owner report not stored: %q", report)
}
// Seed a distinctive verification state; no foreign write may disturb it.
if err := pg.SetFindingVerification(f.FindingID, db.VerificationVerified, 3, "existing proof"); err != nil {
t.Fatal(err)
}
assertUntouched := func(when string) {
t.Helper()
status, poe, note, report := storedVerification(t, s, f.FindingID)
if status != db.VerificationVerified || poe != 3 || note != "existing proof" || report != "## owner report" {
t.Fatalf("%s changed the finding: status=%s poe=%d note=%q report=%q", when, status, poe, note, report)
}
}
// An unrelated task cannot overwrite the report or verification.
foreign, err := s.m.CreateTaskWithOptions("foreign scope", "fixture", db.TaskCreateOptions{})
if err != nil {
t.Fatal(err)
}
foreignID, _ := strconv.ParseInt(foreign.ID, 10, 64)
t.Cleanup(func() { _ = pg.DeleteTask(foreignID) })
foreignCtx := agent.WithRunInfo(context.Background(), agent.RunInfo{TaskID: foreignID})
msg, isErr = reportCall(t, s, foreignCtx, f.NodeID, "## foreign report", `,"poe_level":4,"evidence_quotes":["x7"]`)
if !isErr || !strings.Contains(msg, "belongs to another task") {
t.Fatalf("foreign task write not refused: err=%v %q", isErr, msg)
}
assertUntouched("foreign task write")
// A task that inherited the finding reads it but cannot write it.
child, err := s.m.CreateTaskWithOptions("inherited scope", "fixture", db.TaskCreateOptions{SourceTaskIDs: []int64{ownerID}})
if err != nil {
t.Fatal(err)
}
childID, _ := strconv.ParseInt(child.ID, 10, 64)
t.Cleanup(func() { _ = pg.DeleteTask(childID) })
childCtx := agent.WithRunInfo(context.Background(), agent.RunInfo{TaskID: childID})
msg, isErr = reportCall(t, s, childCtx, f.NodeID, "## inherited report", "")
if !isErr || !strings.Contains(msg, "read-only") {
t.Fatalf("inherited write not refused: err=%v %q", isErr, msg)
}
assertUntouched("inherited task write")
// With no task context at all (a manual chat), the write fails closed.
msg, isErr = reportCall(t, s, context.Background(), f.NodeID, "## chat report", "")
if !isErr || !strings.Contains(msg, "requires a task context") {
t.Fatalf("unknown task write not refused: err=%v %q", isErr, msg)
}
assertUntouched("unknown task write")
// A triggered chat run carries its source task as a server-owned ctx value,
// so the reporter path is allowed for the owning task and refused for others.
triggeredOwn := agent.WithSourceTasks(context.Background(), []int64{ownerID})
if msg, isErr = reportCall(t, s, triggeredOwn, f.NodeID, "## triggered owner report", ""); isErr {
t.Fatalf("triggered owner update refused: %q", msg)
}
triggeredForeign := agent.WithSourceTasks(context.Background(), []int64{foreignID})
if msg, isErr = reportCall(t, s, triggeredForeign, f.NodeID, "## triggered foreign report", ""); !isErr || !strings.Contains(msg, "belongs to another task") {
t.Fatalf("triggered foreign update not refused: err=%v %q", isErr, msg)
}
}