mirror of
https://github.com/BaaRai/ARTEX.git
synced 2026-11-27 18:30:54 +08:00
feat(agent): add deterministic finding fingerprint deduplication complementing LLM triage (#473)
This commit is contained in:
@@ -0,0 +1,317 @@
|
||||
package agent
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"log/slog"
|
||||
"net/url"
|
||||
"regexp"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/Autumn-27/artex/db"
|
||||
)
|
||||
|
||||
// findingFingerprintMatch is a deterministic duplicate hit against an already
|
||||
// registered finding (#473), complementing the advisory LLM triage pass.
|
||||
type findingFingerprintMatch struct {
|
||||
FindingID int64
|
||||
NodeID int64
|
||||
Fingerprint string
|
||||
}
|
||||
|
||||
var (
|
||||
fpURLRe = regexp.MustCompile(`(?i)\bhttps?://[^\s"'<>\]\)]+`)
|
||||
fpMethodPathRe = regexp.MustCompile(`(?i)\b(?:GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS)\s+(/[^\s"'<>\]\)]+)`)
|
||||
fpBarePathRe = regexp.MustCompile(`(?:^|[\s(\["'])(/[a-zA-Z0-9._~/%{}:-]+(?:\?[a-zA-Z0-9._~=&%-]+)?)`)
|
||||
fpParamRe = regexp.MustCompile(`(?i)\b(?:param(?:eter)?|field|query\s+param(?:eter)?)\s*(?:=|:|\s+)\s*["'\x60]?([a-zA-Z_][a-zA-Z0-9_.-]{0,63})["'\x60]?`)
|
||||
fpNonAlnumRe = regexp.MustCompile(`[^a-z0-9]+`)
|
||||
)
|
||||
|
||||
// FindingFingerprint returns a deterministic SHA-256 fingerprint for a finding
|
||||
// from three required axes (#473):
|
||||
// 1. normalized vulnerability class / CWE,
|
||||
// 2. canonical asset IDs (sorted/deduplicated) or URL host,
|
||||
// 3. normalized affected endpoint path and/or parameter name.
|
||||
//
|
||||
// If any of the three axes cannot be extracted unambiguously, it returns "" so
|
||||
// callers fall through to LLM triage / normal registration without false
|
||||
// collisions.
|
||||
func FindingFingerprint(in db.RecordFindingInput) string {
|
||||
vulnClass := normalizeFingerprintToken(in.VulnClass)
|
||||
if vulnClass == "" {
|
||||
return ""
|
||||
}
|
||||
corpus := strings.Join([]string{in.Name, in.Summary, in.Evidence}, "\n")
|
||||
assetKey := canonicalFindingAssetKey(in.AssetIDs, corpus)
|
||||
if assetKey == "" {
|
||||
return ""
|
||||
}
|
||||
endpointKey := canonicalFindingEndpointKey(corpus)
|
||||
if endpointKey == "" {
|
||||
return ""
|
||||
}
|
||||
h := sha256.Sum256([]byte(vulnClass + "\x00" + assetKey + "\x00" + endpointKey))
|
||||
return "fp:" + hex.EncodeToString(h[:16])
|
||||
}
|
||||
|
||||
func normalizeFingerprintToken(s string) string {
|
||||
s = strings.ToLower(strings.TrimSpace(s))
|
||||
if s == "" {
|
||||
return ""
|
||||
}
|
||||
s = fpNonAlnumRe.ReplaceAllString(s, "_")
|
||||
return strings.Trim(s, "_")
|
||||
}
|
||||
|
||||
func canonicalFindingAssetKey(assetIDs []int64, corpus string) string {
|
||||
if len(assetIDs) > 0 {
|
||||
seen := make(map[int64]struct{}, len(assetIDs))
|
||||
ids := make([]int64, 0, len(assetIDs))
|
||||
for _, id := range assetIDs {
|
||||
if id > 0 {
|
||||
if _, ok := seen[id]; !ok {
|
||||
seen[id] = struct{}{}
|
||||
ids = append(ids, id)
|
||||
}
|
||||
}
|
||||
}
|
||||
if len(ids) > 0 {
|
||||
sort.Slice(ids, func(i, j int) bool { return ids[i] < ids[j] })
|
||||
parts := make([]string, len(ids))
|
||||
for i, id := range ids {
|
||||
parts[i] = strconv.FormatInt(id, 10)
|
||||
}
|
||||
return "ids:" + strings.Join(parts, ",")
|
||||
}
|
||||
}
|
||||
for _, raw := range fpURLRe.FindAllString(corpus, 4) {
|
||||
raw = strings.TrimRight(raw, ".,;:!?)")
|
||||
u, err := url.Parse(raw)
|
||||
if err != nil || strings.TrimSpace(u.Host) == "" {
|
||||
continue
|
||||
}
|
||||
return "host:" + strings.ToLower(strings.TrimSuffix(u.Host, "."))
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func canonicalFindingEndpointKey(corpus string) string {
|
||||
var pathSig string
|
||||
var paramNames []string
|
||||
|
||||
// Prefer explicit URLs first so scheme/host are stripped cleanly.
|
||||
for _, raw := range fpURLRe.FindAllString(corpus, 4) {
|
||||
raw = strings.TrimRight(raw, ".,;:!?)")
|
||||
u, err := url.Parse(raw)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
p := normalizeEndpointPath(u.Path)
|
||||
if p != "" {
|
||||
pathSig = p
|
||||
paramNames = append(paramNames, sortedQueryParamNames(u.RawQuery)...)
|
||||
break
|
||||
}
|
||||
}
|
||||
if pathSig == "" {
|
||||
if m := fpMethodPathRe.FindStringSubmatch(corpus); len(m) == 2 {
|
||||
pathSig, paramNames = splitPathAndQuery(m[1])
|
||||
}
|
||||
}
|
||||
if pathSig == "" {
|
||||
for _, m := range fpBarePathRe.FindAllStringSubmatch(corpus, 8) {
|
||||
if len(m) != 2 {
|
||||
continue
|
||||
}
|
||||
candidate := strings.TrimRight(m[1], ".,;:!?)")
|
||||
// Ignore common filesystem/OS paths unless nothing else; require
|
||||
// at least one route character after '/'.
|
||||
if len(candidate) <= 1 || strings.HasPrefix(candidate, "//") {
|
||||
continue
|
||||
}
|
||||
pathSig, paramNames = splitPathAndQuery(candidate)
|
||||
if pathSig != "" {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, m := range fpParamRe.FindAllStringSubmatch(corpus, 4) {
|
||||
if len(m) == 2 {
|
||||
if name := strings.ToLower(strings.TrimSpace(m[1])); name != "" {
|
||||
paramNames = append(paramNames, name)
|
||||
}
|
||||
}
|
||||
}
|
||||
paramNames = dedupSortedStrings(paramNames)
|
||||
if pathSig == "" && len(paramNames) == 0 {
|
||||
return ""
|
||||
}
|
||||
if len(paramNames) == 0 {
|
||||
return "path:" + pathSig
|
||||
}
|
||||
return "path:" + pathSig + "|params:" + strings.Join(paramNames, ",")
|
||||
}
|
||||
|
||||
func splitPathAndQuery(raw string) (string, []string) {
|
||||
raw = strings.TrimRight(strings.TrimSpace(raw), ".,;:!?)")
|
||||
pathPart, queryPart, _ := strings.Cut(raw, "?")
|
||||
return normalizeEndpointPath(pathPart), sortedQueryParamNames(queryPart)
|
||||
}
|
||||
|
||||
func normalizeEndpointPath(p string) string {
|
||||
p = strings.TrimSpace(p)
|
||||
if p == "" || p == "/" {
|
||||
return ""
|
||||
}
|
||||
p = strings.ToLower(p)
|
||||
for strings.Contains(p, "//") {
|
||||
p = strings.ReplaceAll(p, "//", "/")
|
||||
}
|
||||
p = strings.TrimRight(p, "/")
|
||||
if p == "" {
|
||||
return ""
|
||||
}
|
||||
return p
|
||||
}
|
||||
|
||||
func sortedQueryParamNames(rawQuery string) []string {
|
||||
if strings.TrimSpace(rawQuery) == "" {
|
||||
return nil
|
||||
}
|
||||
var names []string
|
||||
for _, pair := range strings.Split(rawQuery, "&") {
|
||||
if pair == "" {
|
||||
continue
|
||||
}
|
||||
k, _, _ := strings.Cut(pair, "=")
|
||||
if k = strings.ToLower(strings.TrimSpace(k)); k != "" {
|
||||
names = append(names, k)
|
||||
}
|
||||
}
|
||||
return dedupSortedStrings(names)
|
||||
}
|
||||
|
||||
func dedupSortedStrings(in []string) []string {
|
||||
if len(in) == 0 {
|
||||
return nil
|
||||
}
|
||||
seen := make(map[string]struct{}, len(in))
|
||||
out := make([]string, 0, len(in))
|
||||
for _, s := range in {
|
||||
if _, ok := seen[s]; !ok {
|
||||
seen[s] = struct{}{}
|
||||
out = append(out, s)
|
||||
}
|
||||
}
|
||||
sort.Strings(out)
|
||||
return out
|
||||
}
|
||||
|
||||
func isDismissedFindingStatus(status string) bool {
|
||||
switch strings.ToLower(strings.TrimSpace(status)) {
|
||||
case "false_positive", "ignored", "duplicate":
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// fingerprintDuplicate checks already registered active findings in this task,
|
||||
// its directly related tasks, and tasks sharing the same assets for an exact
|
||||
// deterministic fingerprint match (#473).
|
||||
func (t *ToolSet) fingerprintDuplicate(in db.RecordFindingInput) (findingFingerprintMatch, bool) {
|
||||
if t.ts == nil {
|
||||
return findingFingerprintMatch{}, false
|
||||
}
|
||||
candFP := FindingFingerprint(in)
|
||||
if candFP == "" {
|
||||
return findingFingerprintMatch{}, false
|
||||
}
|
||||
nodes, err := t.ts.ListByKindWithSources(db.KindFinding, 500)
|
||||
if err != nil {
|
||||
slog.Warn("[dedup] fingerprint lookup skipped: failed to list findings", "err", err)
|
||||
return findingFingerprintMatch{}, false
|
||||
}
|
||||
if len(in.AssetIDs) > 0 {
|
||||
if cross, err := t.ts.FindingsSharingAssets(in.AssetIDs, t.taskID, 100); err == nil {
|
||||
seen := make(map[int64]bool, len(nodes))
|
||||
for _, n := range nodes {
|
||||
if n != nil {
|
||||
seen[n.ID] = true
|
||||
}
|
||||
}
|
||||
for _, n := range cross {
|
||||
if n != nil && !seen[n.ID] {
|
||||
nodes = append(nodes, n)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if len(nodes) == 0 {
|
||||
return findingFingerprintMatch{}, false
|
||||
}
|
||||
if err := t.ts.PopulateFindingTrafficIDs(nodes); err != nil {
|
||||
slog.Warn("[dedup] fingerprint lookup skipped: populate finding ids failed", "err", err)
|
||||
return findingFingerprintMatch{}, false
|
||||
}
|
||||
findingIDs := make([]int64, 0, len(nodes))
|
||||
for _, n := range nodes {
|
||||
if n != nil && n.FindingID > 0 {
|
||||
findingIDs = append(findingIDs, n.FindingID)
|
||||
}
|
||||
}
|
||||
if len(findingIDs) == 0 {
|
||||
return findingFingerprintMatch{}, false
|
||||
}
|
||||
meta, err := t.ts.FindingDedupMetadata(findingIDs)
|
||||
if err != nil {
|
||||
slog.Warn("[dedup] fingerprint lookup skipped: load finding metadata failed", "err", err)
|
||||
return findingFingerprintMatch{}, false
|
||||
}
|
||||
// Check newest first for deterministic match selection.
|
||||
sort.SliceStable(nodes, func(i, j int) bool { return nodes[i].ID > nodes[j].ID })
|
||||
for _, n := range nodes {
|
||||
if n == nil || n.FindingID <= 0 {
|
||||
continue
|
||||
}
|
||||
m := meta[n.FindingID]
|
||||
if isDismissedFindingStatus(m.Status) {
|
||||
continue
|
||||
}
|
||||
var payload struct {
|
||||
VulnClass string `json:"vulnclass"`
|
||||
Name string `json:"name"`
|
||||
Summary string `json:"summary"`
|
||||
Status string `json:"status"`
|
||||
Evidence struct {
|
||||
PoC string `json:"poc"`
|
||||
} `json:"evidence"`
|
||||
}
|
||||
if json.Unmarshal(n.Payload, &payload) != nil {
|
||||
continue
|
||||
}
|
||||
if isDismissedFindingStatus(payload.Status) {
|
||||
continue
|
||||
}
|
||||
existingFP := FindingFingerprint(db.RecordFindingInput{
|
||||
VulnClass: payload.VulnClass,
|
||||
Name: payload.Name,
|
||||
Summary: payload.Summary,
|
||||
Evidence: payload.Evidence.PoC,
|
||||
AssetIDs: m.AssetIDs,
|
||||
})
|
||||
if existingFP != "" && existingFP == candFP {
|
||||
slog.Info("[dedup] deterministic fingerprint matched existing finding",
|
||||
"finding_id", n.FindingID, "node_id", n.ID, "fingerprint", candFP)
|
||||
return findingFingerprintMatch{
|
||||
FindingID: n.FindingID,
|
||||
NodeID: n.ID,
|
||||
Fingerprint: candFP,
|
||||
}, true
|
||||
}
|
||||
}
|
||||
return findingFingerprintMatch{}, false
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
package agent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
|
||||
"github.com/Autumn-27/artex/db"
|
||||
)
|
||||
|
||||
func TestFindingFingerprintDeterminismAndDistinctness(t *testing.T) {
|
||||
base := db.RecordFindingInput{
|
||||
VulnClass: "SQLi",
|
||||
Name: "SQL Injection on search",
|
||||
Summary: "GET https://app.example.test/api/v1/products/search?q=1&sort=asc is injectable",
|
||||
AssetIDs: []int64{42, 10},
|
||||
}
|
||||
sameReordered := db.RecordFindingInput{
|
||||
VulnClass: "sqli",
|
||||
Name: "Re-verified SQLi",
|
||||
Summary: "Confirmed again on https://APP.EXAMPLE.TEST/api/v1/products/search/?sort=desc&q=2",
|
||||
AssetIDs: []int64{10, 42, 10},
|
||||
}
|
||||
fp1 := FindingFingerprint(base)
|
||||
fp2 := FindingFingerprint(sameReordered)
|
||||
if fp1 == "" || fp1 != fp2 {
|
||||
t.Fatalf("equivalent findings must yield identical non-empty fingerprint: fp1=%q fp2=%q", fp1, fp2)
|
||||
}
|
||||
|
||||
// Distinct endpoint on same host/asset must produce a different fingerprint.
|
||||
diffEndpoint := base
|
||||
diffEndpoint.Summary = "GET https://app.example.test/api/v1/users/search?q=1 is injectable"
|
||||
if fp3 := FindingFingerprint(diffEndpoint); fp3 == "" || fp3 == fp1 {
|
||||
t.Fatalf("different endpoint must yield different fingerprint: fp1=%q fp3=%q", fp1, fp3)
|
||||
}
|
||||
|
||||
// Distinct parameter on same path must produce a different fingerprint.
|
||||
diffParam := base
|
||||
diffParam.Summary = "GET https://app.example.test/api/v1/products/search?category=1 is injectable"
|
||||
if fp4 := FindingFingerprint(diffParam); fp4 == "" || fp4 == fp1 {
|
||||
t.Fatalf("different parameter must yield different fingerprint: fp1=%q fp4=%q", fp1, fp4)
|
||||
}
|
||||
|
||||
// Distinct vulnerability class on same endpoint must produce a different fingerprint.
|
||||
diffClass := base
|
||||
diffClass.VulnClass = "XSS"
|
||||
if fp5 := FindingFingerprint(diffClass); fp5 == "" || fp5 == fp1 {
|
||||
t.Fatalf("different vulnclass must yield different fingerprint: fp1=%q fp5=%q", fp1, fp5)
|
||||
}
|
||||
|
||||
// Missing endpoint or missing asset/host returns "" (no false collision).
|
||||
noEndpoint := db.RecordFindingInput{VulnClass: "SQLi", Summary: "generic database error", AssetIDs: []int64{10}}
|
||||
if fp := FindingFingerprint(noEndpoint); fp != "" {
|
||||
t.Fatalf("missing endpoint must return empty fingerprint, got %q", fp)
|
||||
}
|
||||
noAssetOrHost := db.RecordFindingInput{VulnClass: "SQLi", Summary: "GET /login?user=a is injectable"}
|
||||
if fp := FindingFingerprint(noAssetOrHost); fp != "" {
|
||||
t.Fatalf("missing asset/host must return empty fingerprint, got %q", fp)
|
||||
}
|
||||
}
|
||||
|
||||
type countingTriageClient struct {
|
||||
calls atomic.Int64
|
||||
ans DuplicateAnswer
|
||||
}
|
||||
|
||||
func (c *countingTriageClient) Duplicate(_ context.Context, _ TriageCandidate, _ []TriageCandidate) (DuplicateAnswer, error) {
|
||||
c.calls.Add(1)
|
||||
return c.ans, nil
|
||||
}
|
||||
|
||||
func TestReportFindingFingerprintDedupWithoutTriageClientAndComplementsTriage(t *testing.T) {
|
||||
d := testDB(t)
|
||||
t.Cleanup(func() { _ = d.Close() })
|
||||
task, err := d.CreateTaskWithOptions("fingerprint dedup", "verify deterministic dedup", db.TaskCreateOptions{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
_, _ = d.DeleteFindingsByTask(task.ID)
|
||||
_ = d.DeleteTask(task.ID)
|
||||
})
|
||||
|
||||
ts := NewToolSet(d.Exploration(task.ExplorationID), "worker-1")
|
||||
ts.SetTaskID(task.ID)
|
||||
|
||||
// 1. First registration with URL host + vulnclass + endpoint succeeds.
|
||||
first := `{"vulnclass":"SQLi","severity":"high","name":"Login SQLi","summary":"POST https://target.lab.local/api/login?user=admin vulnerable to boolean SQLi"}`
|
||||
if res := callGuardTool(t, ts.addFinding(), first); res.IsError {
|
||||
t.Fatalf("first report_finding failed: %s", res.Flatten())
|
||||
}
|
||||
nodes := findingNodes(t, ts)
|
||||
if len(nodes) != 1 {
|
||||
t.Fatalf("expected 1 finding after first report, got %d", len(nodes))
|
||||
}
|
||||
origFID, origNID := nodes[0].FindingID, nodes[0].ID
|
||||
|
||||
// 2. Re-verification with reworded summary on the same host+endpoint+param+class
|
||||
// is suppressed deterministically even with NO triage client configured.
|
||||
triageMock := &countingTriageClient{}
|
||||
ts.SetTriageClient(triageMock)
|
||||
dup := `{"vulnclass":"sqli","severity":"high","name":"Re-verified login SQLi","summary":"Re-confirmed SQL injection on https://TARGET.LAB.LOCAL/api/login/?user=test"}`
|
||||
res := callGuardTool(t, ts.addFinding(), dup)
|
||||
if res.IsError {
|
||||
t.Fatalf("duplicate suppression returned error: %s", res.Flatten())
|
||||
}
|
||||
text := res.Flatten()
|
||||
if !strings.Contains(text, "duplicate_not_registered") || !strings.Contains(text, `"dedup_source":"fingerprint"`) {
|
||||
t.Fatalf("expected deterministic fingerprint suppression, got: %s", text)
|
||||
}
|
||||
if triageMock.calls.Load() != 0 {
|
||||
t.Fatalf("fingerprint hit must short-circuit before LLM triage, got %d triage calls", triageMock.calls.Load())
|
||||
}
|
||||
var ans struct {
|
||||
DuplicateOfFindingID int64 `json:"duplicate_of_finding_id"`
|
||||
DuplicateOfNodeID int64 `json:"duplicate_of_finding_node_id"`
|
||||
Fingerprint string `json:"fingerprint"`
|
||||
}
|
||||
if err := json.Unmarshal([]byte(text[strings.Index(text, "{"):]), &ans); err != nil {
|
||||
t.Fatalf("parse suppression json: %v (%s)", err, text)
|
||||
}
|
||||
if ans.DuplicateOfFindingID != origFID || ans.DuplicateOfNodeID != origNID || !strings.HasPrefix(ans.Fingerprint, "fp:") {
|
||||
t.Fatalf("unexpected suppression payload: %+v (want finding=%d node=%d)", ans, origFID, origNID)
|
||||
}
|
||||
if !strings.Contains(text, "finding_id="+strconv.FormatInt(origNID, 10)) {
|
||||
t.Fatalf("suppression note must reference node id %d: %s", origNID, text)
|
||||
}
|
||||
if got := len(findingNodes(t, ts)); got != 1 {
|
||||
t.Fatalf("expected still 1 finding after suppression, got %d", got)
|
||||
}
|
||||
|
||||
// 3. A distinct endpoint on the same host is NOT suppressed by fingerprint and
|
||||
// falls through to LLM triage (which returns distinct -> registers).
|
||||
distinct := `{"vulnclass":"sqli","severity":"high","name":"Search SQLi","summary":"GET https://target.lab.local/api/search?q=abc vulnerable to UNION SQLi"}`
|
||||
if res := callGuardTool(t, ts.addFinding(), distinct); res.IsError || strings.Contains(res.Flatten(), "duplicate_not_registered") {
|
||||
t.Fatalf("distinct endpoint should register, got: %s", res.Flatten())
|
||||
}
|
||||
if triageMock.calls.Load() != 1 {
|
||||
t.Fatalf("non-matching fingerprint must fall through to LLM triage, got %d calls", triageMock.calls.Load())
|
||||
}
|
||||
if got := len(findingNodes(t, ts)); got != 2 {
|
||||
t.Fatalf("expected 2 findings after distinct endpoint, got %d", got)
|
||||
}
|
||||
|
||||
// 4. force_register=true overrides deterministic fingerprint suppression.
|
||||
forced := `{"force_register":true,"vulnclass":"sqli","severity":"high","name":"Distinct root cause on login","summary":"POST https://target.lab.local/api/login?user=admin second bug"}`
|
||||
if res := callGuardTool(t, ts.addFinding(), forced); res.IsError || strings.Contains(res.Flatten(), "duplicate_not_registered") {
|
||||
t.Fatalf("force_register must override fingerprint suppression, got: %s", res.Flatten())
|
||||
}
|
||||
if got := len(findingNodes(t, ts)); got != 3 {
|
||||
t.Fatalf("expected 3 findings after force_register, got %d", got)
|
||||
}
|
||||
|
||||
// 5. Dismissed (false_positive) findings must not suppress a new registration.
|
||||
if _, err := d.Exec(`UPDATE findings SET status='false_positive' WHERE task_id=$1`, task.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ts.SetTriageClient(nil)
|
||||
if res := callGuardTool(t, ts.addFinding(), dup); res.IsError || strings.Contains(res.Flatten(), "duplicate_not_registered") {
|
||||
t.Fatalf("false_positive finding must not suppress re-discovery, got: %s", res.Flatten())
|
||||
}
|
||||
if got := len(findingNodes(t, ts)); got != 4 {
|
||||
t.Fatalf("expected 4 findings after false_positive re-discovery, got %d", got)
|
||||
}
|
||||
}
|
||||
@@ -1630,6 +1630,20 @@ func (t *ToolSet) addFinding() actool.CoreTool {
|
||||
// retry hits the same check and is suppressed again.
|
||||
if a.ForceRegister {
|
||||
slog.Info("[triage] override: force_register set, registering without duplicate check", "candidate", a.Name)
|
||||
} else if dup, ok := t.fingerprintDuplicate(input); ok {
|
||||
res := map[string]any{
|
||||
"duplicate_of_finding_id": dup.FindingID,
|
||||
"duplicate_of_finding_node_id": dup.NodeID,
|
||||
"dedup_source": "fingerprint",
|
||||
"fingerprint": dup.Fingerprint,
|
||||
"evidence_status": "duplicate_not_registered",
|
||||
"note": fmt.Sprintf("Deterministic fingerprint (%s) matched already registered finding_id %d (exploration node %d), so no new finding was created. "+
|
||||
"To extend that finding with new evidence, call update_finding_report with finding_id=%d (it addresses the NODE id, not the findings-table id). "+
|
||||
"If the new evidence is in fact a distinct defect (different endpoint, parameter or root cause), call report_finding again with force_register=true.",
|
||||
dup.Fingerprint, dup.FindingID, dup.NodeID, dup.NodeID),
|
||||
}
|
||||
raw, _ := json.Marshal(res)
|
||||
return actool.Text(fmt.Sprintf("finding matched existing finding_id %d (node %d, fingerprint %s) — not registered again\n%s", dup.FindingID, dup.NodeID, dup.Fingerprint, raw)), nil
|
||||
} else if ans, ok := t.triageDuplicate(ctx, input); ok && triageDuplicateHit(ans) {
|
||||
res := map[string]any{
|
||||
"duplicate_of_finding_id": ans.DuplicateOf,
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"strings"
|
||||
)
|
||||
|
||||
@@ -69,3 +70,55 @@ func (s *ExplorationStore) FindingsSharingAssets(assetIDs []int64, excludeTask i
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// FindingDedupMeta carries the finding metadata needed by deterministic
|
||||
// fingerprint deduplication (#473) without requiring any schema migration.
|
||||
type FindingDedupMeta struct {
|
||||
AssetIDs []int64
|
||||
Status string
|
||||
}
|
||||
|
||||
// FindingDedupMetadata returns asset_ids and status keyed by finding id.
|
||||
func (s *ExplorationStore) FindingDedupMetadata(findingIDs []int64) (map[int64]FindingDedupMeta, error) {
|
||||
out := make(map[int64]FindingDedupMeta, len(findingIDs))
|
||||
if len(findingIDs) == 0 {
|
||||
return out, nil
|
||||
}
|
||||
placeholders := make([]string, 0, len(findingIDs))
|
||||
args := make([]any, 0, len(findingIDs))
|
||||
seen := make(map[int64]struct{}, len(findingIDs))
|
||||
for _, id := range findingIDs {
|
||||
if id <= 0 {
|
||||
continue
|
||||
}
|
||||
if _, ok := seen[id]; ok {
|
||||
continue
|
||||
}
|
||||
seen[id] = struct{}{}
|
||||
args = append(args, id)
|
||||
placeholders = append(placeholders, "$"+itoa(int64(len(args))))
|
||||
}
|
||||
if len(args) == 0 {
|
||||
return out, nil
|
||||
}
|
||||
rows, err := s.db.Query(
|
||||
`SELECT id, COALESCE(asset_ids, '[]'::jsonb), COALESCE(status, 'pending') FROM findings WHERE id IN (`+strings.Join(placeholders, ",")+`)`,
|
||||
args...,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
for rows.Next() {
|
||||
var id int64
|
||||
var rawAssets []byte
|
||||
var status string
|
||||
if err := rows.Scan(&id, &rawAssets, &status); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var aids []int64
|
||||
_ = json.Unmarshal(rawAssets, &aids)
|
||||
out[id] = FindingDedupMeta{AssetIDs: aids, Status: status}
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user