Files
ARTEX/report/findings.go
T
Xiaobo a0adc209ad feat(report): surface finding proof strength in the report and the export
The task report and the findings export asserted every finding with no
qualification: nothing said how far exploitation actually reached (PoE level),
whether the claim was machine-verified (verification status and note), whether
counterevidence was recorded, or whether any traffic was bound. The web UI
badges all of it (VERIFICATION_META, the detail page), so the report — the
artifact a client actually reads — was the last surface still asserting bare
claims.

Render it from one place:

- report/quality.go (new): two constructors and two pure renderers, no I/O, no
  DB handle, so the block is unit-tested without a database.
- Both surfaces call the same helpers, which is the point: the task report and
  the per-finding export cannot drift apart the way duplicated formatting does.
- Missing is explicit: a finding node with no standalone row prints
  "not assessed (no finding record)" instead of an invented zero — the honest
  gap the existing coverage work (#207) also insists on.
- Labels match the shipped UI wording (Verification, Confidence rationale,
  Counterevidence) and states are humanised ("Not assessed", "False positive"),
  with an unrecognised value printed verbatim so a new state cannot silently
  vanish from a report.
- Bound-traffic count appears once per document: as a Proof bullet in the task
  report (it has no traffic section), and in the export only when nothing is
  bound — otherwise the traffic section already states it.
- The detailed report is capped at 8 KiB in the task report only, rune-safe, with
  the cap derived into the truncation message; the export is the canonical
  per-finding document and is never silently shortened.
- The export keeps its document structure: the single-finding document gets
  "## Detailed Report" (a section like its siblings), the multi-finding summary
  gets a bold label.

Read paths only: no change to the write side of poe_level or verification_status,
no schema change (all five columns already exist), no API/DTO change (the widened
FindingMeta stays internal to the report path, and the findings list keeps
selecting only what it renders). One extra task-scoped query on GET /api/report,
because findings bodies stay off the list path.

docs/vulnerability-traffic-evidence.md §Export describes the new Markdown.
2026-11-17 08:40:37 +08:00

198 lines
7.1 KiB
Go

package report
import (
"bytes"
"encoding/csv"
"fmt"
"path"
"regexp"
"sort"
"strings"
"time"
"github.com/Autumn-27/artex/db"
)
// Rendering for the findings page "Export": renders a batch of findings table rows
// into a summary Markdown, a single-finding Markdown, or CSV. JSON is serialized
// directly from DTOs at the server layer, not here.
// sortFindingsForExport sorts by severity descending, then by time descending, consistent with the summary report's grouping.
func sortFindingsForExport(fs []*db.DBFinding) {
sort.SliceStable(fs, func(i, j int) bool {
ri, rj := sevRank[fs[i].Severity], sevRank[fs[j].Severity]
if ri != rj {
return ri < rj // smaller sevRank means more severe
}
return fs[i].CreatedAt.After(fs[j].CreatedAt)
})
}
// findingTitle returns the vulnerability's readable title: name → class → "Uncategorized".
func findingTitle(f *db.DBFinding) string {
return nz(f.Name, nz(f.VulnClass, "Uncategorized"))
}
// FindingsMarkdown combines a batch of findings into a summary report (summary + grouped by severity,
// each entry with class/status/owning task/evidence/detailed report).
func FindingsMarkdown(fs []*db.DBFinding, generatedAt time.Time) string {
items := append([]*db.DBFinding(nil), fs...)
sortFindingsForExport(items)
var b strings.Builder
b.WriteString("# Vulnerability Findings Summary Report\n\n")
fmt.Fprintf(&b, "- **Generated at**: %s\n", generatedAt.Format("2006-01-02 15:04:05"))
fmt.Fprintf(&b, "- **Total findings**: %d\n\n", len(items))
// Summary: counts per severity.
counts := map[string]int{}
for _, f := range items {
counts[f.Severity]++
}
b.WriteString("## Summary\n\n")
b.WriteString("| Severity | Count |\n| --- | --- |\n")
for _, s := range []struct{ key, label string }{
{"critical", "Critical"}, {"high", "High"}, {"medium", "Medium"}, {"low", "Low"},
} {
fmt.Fprintf(&b, "| %s | %d |\n", s.label, counts[s.key])
}
b.WriteString("\n")
if len(items) == 0 {
b.WriteString("_No matching vulnerabilities._\n")
return b.String()
}
b.WriteString("## Vulnerability Details\n\n")
for i, f := range items {
fmt.Fprintf(&b, "### %d. [%s] %s\n\n", i+1, strings.ToUpper(nz(f.Severity, "info")), findingTitle(f))
if f.VulnClass != "" {
fmt.Fprintf(&b, "- **Class**: %s\n", f.VulnClass)
}
fmt.Fprintf(&b, "- **Status**: %s\n", nz(f.Status, "pending"))
if desc := strings.TrimSpace(f.TaskDescription); desc != "" {
fmt.Fprintf(&b, "- **Task**: %s\n", desc)
}
fmt.Fprintf(&b, "- **Found at**: %s\n", f.CreatedAt.Format("2006-01-02 15:04:05"))
q := qualityFromDBFinding(f)
b.WriteString(qualityBullets(q, false))
if s := strings.TrimSpace(f.Summary); s != "" {
fmt.Fprintf(&b, "%s\n\n", s)
}
if e := strings.TrimSpace(f.Evidence); e != "" {
fmt.Fprintf(&b, "**Evidence:**\n\n```\n%s\n```\n\n", e)
}
b.WriteString(qualityNarrative(q))
b.WriteString(detailedReportFull(f.Report, "**Detailed report:**"))
b.WriteString(findingTrafficMarkdown(f, false))
b.WriteString("---\n\n")
}
return b.String()
}
// SingleFindingMarkdown renders a single vulnerability as a standalone Markdown (used for "one file per vulnerability" packaging).
func SingleFindingMarkdown(f *db.DBFinding, generatedAt time.Time) string {
var b strings.Builder
fmt.Fprintf(&b, "# [%s] %s\n\n", strings.ToUpper(nz(f.Severity, "info")), findingTitle(f))
if f.VulnClass != "" {
fmt.Fprintf(&b, "- **Class**: %s\n", f.VulnClass)
}
fmt.Fprintf(&b, "- **Severity**: %s\n", nz(f.Severity, "info"))
fmt.Fprintf(&b, "- **Status**: %s\n", nz(f.Status, "pending"))
if desc := strings.TrimSpace(f.TaskDescription); desc != "" {
fmt.Fprintf(&b, "- **Task**: %s\n", desc)
}
fmt.Fprintf(&b, "- **Found at**: %s\n", f.CreatedAt.Format("2006-01-02 15:04:05"))
fmt.Fprintf(&b, "- **Generated at**: %s\n", generatedAt.Format("2006-01-02 15:04:05"))
q := qualityFromDBFinding(f)
b.WriteString(qualityBullets(q, false))
if s := strings.TrimSpace(f.Summary); s != "" {
fmt.Fprintf(&b, "## Summary\n\n%s\n\n", s)
}
if e := strings.TrimSpace(f.Evidence); e != "" {
fmt.Fprintf(&b, "## Evidence\n\n```\n%s\n```\n\n", e)
}
b.WriteString(qualityNarrative(q))
b.WriteString(detailedReportFull(f.Report, "## Detailed Report"))
b.WriteString(findingTrafficMarkdown(f, true))
return b.String()
}
var unsafeFilenameChars = regexp.MustCompile(`[^\p{Han}\p{L}\p{N}._-]+`)
// FindingFilename generates a safe .md filename for "one file per vulnerability", e.g.
// `critical_SQL_injection_#123.md`. Strips path separators and control characters to avoid illegal paths inside the zip.
func FindingFilename(f *db.DBFinding) string {
sev := nz(f.Severity, "info")
title := findingTitle(f)
name := fmt.Sprintf("%s_%s_#%d", sev, title, f.ID)
name = unsafeFilenameChars.ReplaceAllString(name, "_")
name = strings.Trim(name, "._")
if name == "" {
name = fmt.Sprintf("finding_%d", f.ID)
}
// Defensive: strip one more path layer to rule out zip slip.
name = path.Base(name)
if len(name) > 120 {
name = name[:120]
}
return name + ".md"
}
// FindingsCSV renders a batch of findings as CSV (with a UTF-8 BOM so Excel detects the encoding correctly).
// It omits the long report/evidence full text and keeps only summary-level fields; use Markdown/JSON export for full text.
func FindingsCSV(fs []*db.DBFinding) []byte {
items := append([]*db.DBFinding(nil), fs...)
sortFindingsForExport(items)
var buf bytes.Buffer
buf.WriteString("\xEF\xBB\xBF") // UTF-8 BOM
w := csv.NewWriter(&buf)
_ = w.Write([]string{"ID", "Name", "Class", "Severity", "Status", "Task", "Found At", "Summary", "Traffic Evidence Count", "Traffic Evidence IDs"})
for _, f := range items {
_ = w.Write([]string{
fmt.Sprintf("%d", f.ID),
findingTitle(f),
f.VulnClass,
nz(f.Severity, "info"),
nz(f.Status, "pending"),
f.TaskDescription,
f.CreatedAt.Format("2006-01-02 15:04:05"),
strings.TrimSpace(f.Summary),
fmt.Sprint(len(f.TrafficBindings)), findingTrafficIDs(f),
})
}
w.Flush()
return buf.Bytes()
}
func findingTrafficIDs(f *db.DBFinding) string {
ids := make([]string, 0, len(f.TrafficBindings))
for _, b := range f.TrafficBindings {
ids = append(ids, fmt.Sprint(b.ID))
}
return strings.Join(ids, ",")
}
func findingTrafficMarkdown(f *db.DBFinding, attachments bool) string {
stale := reportStale(f.Report, f.EvidenceVersion, f.ReportEvidenceVersion)
if len(f.TrafficBindings) == 0 && !stale {
return ""
}
var out strings.Builder
out.WriteString("\n## Related Traffic Evidence\n\n")
fmt.Fprintf(&out, "Evidence version: %d; bindings: %d.\n\n", f.EvidenceVersion, len(f.TrafficBindings))
out.WriteString(staleReportNotice(stale))
for i, b := range f.TrafficBindings {
fmt.Fprintf(&out, "%d. **Evidence #%d · %s** — `%s %s`, status %d\n", i+1, b.ID, b.Role, b.Snapshot.Method, strings.ReplaceAll(b.Snapshot.URL, "`", "%60"), b.Snapshot.Status)
if b.Note != "" {
fmt.Fprintf(&out, " %s\n", strings.ReplaceAll(b.Note, "\n", "\n "))
}
if attachments {
fmt.Fprintf(&out, " [Request message](evidence/%d/%d/request.http) · [Response message](evidence/%d/%d/response.http)\n", f.ID, b.ID, f.ID, b.ID)
}
}
out.WriteString("\n")
return out.String()
}