Skip to content

armgit / ARTEX

Public Imported from GitHub
0

ARTEX - AI autonomous penetration testing system (English translation; upstream: Autumn-27/ARTEX, AGPL-3.0)

agent: close the review blockers on the advisory duplicate check

Николай Гусевa3e44d3f05d9
diff --git a/agent/tools.go b/agent/tools.go
index 4814fb9..0aedcd7 100644
--- a/agent/tools.go
+++ b/agent/tools.go
@@ -4,6 +4,7 @@ import (
"context"
"encoding/json"
"fmt"
+ "log"
"strconv"
"strings"
"time"
@@ -1529,11 +1530,13 @@ func (t *ToolSet) addFinding() actool.CoreTool {
"items": obj(map[string]any{"traffic_id": str("a real traffic ID returned by traffic_search"), "role": map[string]any{"type": "string", "enum": []string{"baseline", "proof", "verification", "supporting"}}, "note": str("how this traffic supports the finding's conclusion")}, "traffic_id")},
"counterevidence": str("optional: what you tested that did not work (variants, paths, or bypasses that were blocked or came back negative). Fill it when your confidence is not high; omitting it never blocks reporting."),
"confidence_rationale": str("optional: why the conclusion holds (which observation rules out the benign explanation). Fill it when your confidence is not high; omitting it never blocks reporting."),
+ "force_register": map[string]any{"type": "boolean", "description": "optional: register even though the advisory duplicate check would suppress this finding. Use it only after a suppression when the new evidence is in fact a distinct defect (different endpoint, parameter or root cause); the suppression answer says so and names the finding it matched."},
}, "vulnclass", "severity", "summary"), func(ctx context.Context, in json.RawMessage) (actool.Result, error) {
var a struct {
VulnClass, Name, Severity, Summary, Evidence string
Counterevidence string `json:"counterevidence"`
ConfidenceRationale string `json:"confidence_rationale"`
+ ForceRegister bool `json:"force_register"`
IntentID json.RawMessage `json:"intent_id"`
AssetIDs []json.RawMessage `json:"asset_ids"`
TrafficRefs []db.TrafficRef `json:"traffic_refs"`
@@ -1576,17 +1579,25 @@ func (t *ToolSet) addFinding() actool.CoreTool {
// the caller is told which finding to extend. Every failure path (no client,
// no existing findings, transport error, low confidence) falls through to
// the normal registration below.
- if ans, ok := t.triageDuplicate(ctx, input); ok && triageDuplicateHit(ans) {
+ //
+ // force_register is the way back out of a wrong suppression: without it the
+ // advice "register it again if it is distinct" is unactionable, because the
+ // retry hits the same check and is suppressed again.
+ if a.ForceRegister {
+ log.Printf("[triage] override: force_register set, registering %q without the duplicate check", a.Name)
+ } else if ans, ok := t.triageDuplicate(ctx, input); ok && triageDuplicateHit(ans) {
res := map[string]any{
- "duplicate_of_finding_id": ans.DuplicateOf,
- "triage_confidence": ans.Confidence,
- "evidence_status": "duplicate_not_registered",
- "note": "Triage matched this finding to an already registered one, so no new finding was created. " +
- "If the new evidence adds detail, extend that finding with update_finding_report; if it is in fact a " +
- "distinct defect (different endpoint, parameter or root cause), register it again explicitly.",
+ "duplicate_of_finding_id": ans.DuplicateOf,
+ "duplicate_of_finding_node_id": ans.DuplicateOfNode,
+ "triage_confidence": ans.Confidence,
+ "evidence_status": "duplicate_not_registered",
+ "note": fmt.Sprintf("Triage matched this finding to already registered finding_id %d (exploration node %d), so no new finding was created. "+
+ "To extend that finding, 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.",
+ ans.DuplicateOf, ans.DuplicateOfNode, ans.DuplicateOfNode),
}
raw, _ := json.Marshal(res)
- return actool.Text(fmt.Sprintf("finding matched to existing finding_id %d (triage confidence %.2f) — not registered again\n%s", ans.DuplicateOf, ans.Confidence, raw)), nil
+ return actool.Text(fmt.Sprintf("finding matched to existing finding_id %d (node %d, triage confidence %.2f) — not registered again\n%s", ans.DuplicateOf, ans.DuplicateOfNode, ans.Confidence, raw)), nil
}
var recorded *db.RecordedFinding
if t.findingRecorder != nil {
diff --git a/agent/triage.go b/agent/triage.go
index 8021312..84fbddf 100644
--- a/agent/triage.go
+++ b/agent/triage.go
@@ -13,6 +13,7 @@ import (
"strconv"
"strings"
"time"
+ "unicode/utf8"
"github.com/Autumn-27/artex/db"
)
@@ -68,6 +69,11 @@ const (
// TriageCandidate is a finding reduced to what a dedup question needs.
type TriageCandidate struct {
FindingID int64
+ // NodeID is the exploration node id of the same finding. The agent extends a
+ // finding through update_finding_report, which addresses the NODE, while the
+ // question and the suppression answer carry the findings-table id — both have
+ // to come back to the caller or it passes the wrong one.
+ NodeID int64
Name string
VulnClass string
Severity string
@@ -80,7 +86,9 @@ type TriageCandidate struct {
// DuplicateAnswer is the parsed verdict: DuplicateOf == 0 means "genuinely distinct".
type DuplicateAnswer struct {
DuplicateOf int64
- Confidence float64
+ // DuplicateOfNode is the exploration node id of DuplicateOf (0 when unknown).
+ DuplicateOfNode int64
+ Confidence float64
}
// TriageClient answers the closed-list questions the agent asks.
@@ -101,13 +109,15 @@ type SystemOneClient struct {
// (stage3_width.py 2026-11-22), 3.83-3.96 с на 27B-варианте (этап 0, 2026-11-21); у пула
// conc=2 и нет очереди, занятость добавляет ожидание. запас ~5x к худшему замеру.
// при превышении: ошибка -> fail open, находка регистрируется как раньше.
-const triageHTTPTimeout = 20 * time.Second // замер: 0.26-3.96 с наблюдаемо; запас 5x
+// Экспортирован, чтобы сервер, собирающий клиенту guarded-транспорт, брал тот же
+// бюджет, а не заводил второй таймаут с другим числом.
+const TriageHTTPTimeout = 20 * time.Second // замер: 0.26-3.96 с наблюдаемо; запас 5x
func (c *SystemOneClient) http() *http.Client {
if c.HTTP != nil {
return c.HTTP
}
- return &http.Client{Timeout: triageHTTPTimeout}
+ return &http.Client{Timeout: TriageHTTPTimeout}
}
// Duplicate asks which existing finding, if any, is the same defect as cand.
@@ -183,7 +193,7 @@ func buildDuplicateState(cand TriageCandidate, existing []TriageCandidate) strin
}
out := b.String()
if len(out) > triageMaxStateChars {
- out = out[:triageMaxStateChars]
+ out = cutRunes(out, triageMaxStateChars)
}
return out
}
@@ -249,11 +259,26 @@ func parseDuplicateAnswer(raw []byte, existingIDs map[int64]bool) (DuplicateAnsw
func capText(s string, n int) string {
if n > 0 && len(s) > n {
- return s[:n] + "…"
+ return cutRunes(s, n) + "…"
}
return s
}
+// cutRunes truncates s to at most n BYTES without splitting a multi-byte rune.
+// The caps above are byte budgets (they bound a request), but a byte-index cut
+// through a CJK or Cyrillic summary leaves a broken rune — the JSON encoder then
+// sends U+FFFD and the question loses the tail of the evidence.
+func cutRunes(s string, n int) string {
+ if n <= 0 || len(s) <= n {
+ return s
+ }
+ cut := n
+ for cut > 0 && !utf8.RuneStart(s[cut]) {
+ cut--
+ }
+ return s[:cut]
+}
+
func triageFirstLine(b []byte) string {
s := strings.TrimSpace(string(b))
if i := strings.IndexByte(s, '\n'); i >= 0 {
@@ -324,10 +349,30 @@ func (t *ToolSet) triageDuplicate(ctx context.Context, in db.RecordFindingInput)
log.Printf("[triage] client error (fail open): %v", err)
return DuplicateAnswer{}, false
}
- log.Printf("[triage] answer: dup=%d conf=%.2f", ans.DuplicateOf, ans.Confidence)
+ // Carry the node id of the matched finding alongside its findings-table id:
+ // the agent extends a finding through update_finding_report, which takes the
+ // node id, so an answer that names only the table id sends it to the wrong call.
+ ans = withNodeID(ans, existing)
+ log.Printf("[triage] answer: dup=%d node=%d conf=%.2f", ans.DuplicateOf, ans.DuplicateOfNode, ans.Confidence)
return ans, true
}
+// withNodeID resolves the exploration node id of the matched finding from the
+// candidates the question offered. Pure, so the mapping is testable without a
+// decision-model round trip.
+func withNodeID(ans DuplicateAnswer, existing []TriageCandidate) DuplicateAnswer {
+ if ans.DuplicateOf <= 0 {
+ return ans
+ }
+ for _, e := range existing {
+ if e.FindingID == ans.DuplicateOf {
+ ans.DuplicateOfNode = e.NodeID
+ break
+ }
+ }
+ return ans
+}
+
// triageCandidates reduces finding nodes to question candidates: nodes without a
// finding row are skipped, the rest ranked by relevance to the candidate (see
// triageRelevant) and capped. Findings inherited from a directly related task are
@@ -347,6 +392,7 @@ func triageCandidates(nodes []*db.Node, in db.RecordFindingInput) []TriageCandid
_ = json.Unmarshal(n.Payload, &p)
out = append(out, TriageCandidate{
FindingID: n.FindingID,
+ NodeID: n.ID,
Name: strField(p, "name"),
VulnClass: strField(p, "vulnclass"),
Severity: strField(p, "severity"),
diff --git a/agent/triage_override_test.go b/agent/triage_override_test.go
new file mode 100644
index 0000000..bd71f7b
--- /dev/null
+++ b/agent/triage_override_test.go
@@ -0,0 +1,113 @@
+package agent
+
+import (
+ "context"
+ "encoding/json"
+ "strconv"
+ "strings"
+ "testing"
+
+ "github.com/Autumn-27/artex/db"
+)
+
+// dupTriageClient answers "the same defect" every time, so the suppression path
+// runs without a decision-model server.
+type dupTriageClient struct{ target int64 }
+
+func (c dupTriageClient) Duplicate(context.Context, TriageCandidate, []TriageCandidate) (DuplicateAnswer, error) {
+ return DuplicateAnswer{DuplicateOf: c.target, Confidence: 0.99}, nil
+}
+
+func findingNodes(t *testing.T, ts *ToolSet) []*db.Node {
+ t.Helper()
+ nodes, err := ts.ts.ListByKindWithSources(db.KindFinding, 50)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := ts.ts.PopulateFindingTrafficIDs(nodes); err != nil {
+ t.Fatal(err)
+ }
+ return nodes
+}
+
+// The suppression answer tells the agent to register a genuinely distinct defect
+// again — that advice is unactionable unless a retry can bypass the check. This
+// walks the whole path: suppress, then override, and checks the answer names the
+// NODE id update_finding_report needs, not only the findings-table id.
+func TestReportFindingForceRegisterOverridesSuppression(t *testing.T) {
+ d := testDB(t)
+ t.Cleanup(func() { _ = d.Close() })
+ task, err := d.CreateTaskWithOptions("triage override", "exercise the duplicate override", db.TaskCreateOptions{})
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { _ = d.DeleteTask(task.ID) })
+
+ ts := NewToolSet(d.Exploration(task.ExplorationID), "worker-1")
+ ts.SetTaskID(task.ID)
+ body := `{"vulnclass":"sqli","severity":"high","summary":"GET /rest/products/search?q= is concatenated into SQL; UNION SELECT dumps Users."}`
+
+ if res := callGuardTool(t, ts.addFinding(), body); res.IsError {
+ t.Fatalf("first report_finding failed: %s", res.Flatten())
+ }
+ nodes := findingNodes(t, ts)
+ if len(nodes) != 1 {
+ t.Fatalf("findings after the first call = %d, want 1", len(nodes))
+ }
+ fid, nid := nodes[0].FindingID, nodes[0].ID
+ if fid <= 0 || nid <= 0 {
+ t.Fatalf("fixture ids = finding %d / node %d", fid, nid)
+ }
+
+ ts.SetTriageClient(dupTriageClient{target: fid})
+ res := callGuardTool(t, ts.addFinding(), body)
+ if res.IsError {
+ t.Fatalf("suppressed report_finding returned an error: %s", res.Flatten())
+ }
+ text := res.Flatten()
+ if !strings.Contains(text, "duplicate_not_registered") {
+ t.Fatalf("second call was not suppressed: %s", text)
+ }
+ // The caller must be able to act on the answer: both ids, and the node id is
+ // the one update_finding_report takes.
+ var ans struct {
+ DuplicateOfFindingID int64 `json:"duplicate_of_finding_id"`
+ DuplicateOfNodeID int64 `json:"duplicate_of_finding_node_id"`
+ }
+ payload := text[strings.Index(text, "{"):]
+ if err := json.Unmarshal([]byte(payload), &ans); err != nil {
+ t.Fatalf("suppression answer is not JSON: %v (%s)", err, text)
+ }
+ if ans.DuplicateOfFindingID != fid || ans.DuplicateOfNodeID != nid {
+ t.Fatalf("answer ids = finding %d / node %d, want %d / %d", ans.DuplicateOfFindingID, ans.DuplicateOfNodeID, fid, nid)
+ }
+ if !strings.Contains(text, "finding_id="+strconv.FormatInt(nid, 10)) {
+ t.Fatalf("answer does not point at the node id: %s", text)
+ }
+ if got := len(findingNodes(t, ts)); got != 1 {
+ t.Fatalf("findings after suppression = %d, want 1", got)
+ }
+
+ // force_register is the way out: the same call now registers.
+ forced := `{"force_register":true,"vulnclass":"sqli","severity":"high","summary":"GET /rest/products/search?q= is concatenated into SQL; UNION SELECT dumps Users."}`
+ if res := callGuardTool(t, ts.addFinding(), forced); res.IsError {
+ t.Fatalf("forced report_finding failed: %s", res.Flatten())
+ } else if strings.Contains(res.Flatten(), "duplicate_not_registered") {
+ t.Fatalf("force_register was ignored: %s", res.Flatten())
+ }
+ if got := len(findingNodes(t, ts)); got != 2 {
+ t.Fatalf("findings after force_register = %d, want 2", got)
+ }
+}
+
+// The parameter has to be advertised, or the model never learns the way out.
+func TestReportFindingAdvertisesForceRegister(t *testing.T) {
+ schema := NewToolSet(nil, "").addFinding().InputSchema()
+ raw, err := json.Marshal(schema)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !strings.Contains(string(raw), "force_register") {
+ t.Fatalf("report_finding schema does not advertise force_register: %s", raw)
+ }
+}
diff --git a/agent/triage_review_test.go b/agent/triage_review_test.go
new file mode 100644
index 0000000..20d650c
--- /dev/null
+++ b/agent/triage_review_test.go
@@ -0,0 +1,92 @@
+package agent
+
+import (
+ "strings"
+ "testing"
+ "unicode/utf8"
+
+ "github.com/Autumn-27/artex/db"
+)
+
+// The caps bound a request in BYTES, but a byte-index cut through a multi-byte
+// rune leaves a broken character: the JSON encoder sends U+FFFD and the decider
+// reads garbage where the evidence tail was. Every cut must land on a boundary.
+func TestCapTextCutsOnRuneBoundary(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ text string
+ cap int
+ }{
+ {"cyrillic", strings.Repeat("уязвимость ", 80), 51},
+ {"cjk", strings.Repeat("数据泄露", 100), 401},
+ {"mixed", "SQLi: " + strings.Repeat("инъекция ", 90), 333},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ out := capText(tc.text, tc.cap)
+ if !utf8.ValidString(out) {
+ t.Fatalf("capText(%d) produced invalid UTF-8", tc.cap)
+ }
+ if !strings.HasSuffix(out, "…") {
+ t.Fatalf("capText(%d) dropped the ellipsis", tc.cap)
+ }
+ body := strings.TrimSuffix(out, "…")
+ if len(body) > tc.cap {
+ t.Fatalf("capText(%d) kept %d bytes", tc.cap, len(body))
+ }
+ if !strings.HasPrefix(tc.text, body) {
+ t.Fatalf("capText(%d) is not a prefix of the input", tc.cap)
+ }
+ })
+ }
+}
+
+// The assembled state has its own byte ceiling; the same rule applies there, and
+// the whole state must still parse as text.
+func TestBuildDuplicateStateCutsOnRuneBoundary(t *testing.T) {
+ existing := make([]TriageCandidate, 0, 40)
+ for i := 0; i < 40; i++ {
+ existing = append(existing, TriageCandidate{
+ FindingID: int64(i + 1),
+ Name: "数据泄露",
+ Summary: strings.Repeat("утечка данных через параметр ", 20),
+ })
+ }
+ state := buildDuplicateState(TriageCandidate{Name: "SQLi", Summary: strings.Repeat("данные ", 200)}, existing)
+ if len(state) > triageMaxStateChars {
+ t.Fatalf("state is %d bytes, cap is %d", len(state), triageMaxStateChars)
+ }
+ if !utf8.ValidString(state) {
+ t.Fatal("state was cut mid-rune")
+ }
+}
+
+// The question and the suppression answer carry the findings-table id, while
+// update_finding_report addresses the exploration node — the candidate list has
+// to keep both so the answer can name the one the agent needs to act on.
+func TestTriageCandidatesCarryNodeID(t *testing.T) {
+ nodes := []*db.Node{
+ {ID: 41, FindingID: 7, Payload: []byte(`{"name":"SQLi","vulnclass":"sqli","severity":"high","summary":"s"}`)},
+ {ID: 42, FindingID: 0, Payload: []byte(`{"name":"no finding row"}`)},
+ }
+ out := triageCandidates(nodes, db.RecordFindingInput{})
+ if len(out) != 1 {
+ t.Fatalf("candidates = %d, want 1 (node without a finding row is skipped)", len(out))
+ }
+ if out[0].NodeID != 41 || out[0].FindingID != 7 {
+ t.Fatalf("candidate ids = node %d / finding %d, want 41 / 7", out[0].NodeID, out[0].FindingID)
+ }
+}
+
+func TestWithNodeIDMapsFindingToNode(t *testing.T) {
+ existing := []TriageCandidate{{FindingID: 7, NodeID: 41}, {FindingID: 9, NodeID: 55}}
+ if got := withNodeID(DuplicateAnswer{DuplicateOf: 9, Confidence: 0.8}, existing); got.DuplicateOfNode != 55 {
+ t.Fatalf("DuplicateOfNode = %d, want 55", got.DuplicateOfNode)
+ }
+ if got := withNodeID(DuplicateAnswer{}, existing); got.DuplicateOfNode != 0 {
+ t.Fatalf("distinct answer carried node %d", got.DuplicateOfNode)
+ }
+ // An id the question never offered must not invent a node.
+ if got := withNodeID(DuplicateAnswer{DuplicateOf: 999}, existing); got.DuplicateOfNode != 0 {
+ t.Fatalf("unoffered id mapped to node %d", got.DuplicateOfNode)
+ }
+}
diff --git a/server/server.go b/server/server.go
index aaf2dd0..ae98539 100644
--- a/server/server.go
+++ b/server/server.go
@@ -4039,6 +4039,26 @@ func (s *Server) putSettings(w http.ResponseWriter, r *http.Request) {
}
egress.SetProfile(noise)
}
+ // Triage settings are checked before either is stored. A profile id that does
+ // not exist resolves to "off" at run time, which reads as a broken dedup rather
+ // than as a rejected setting; a threshold outside 0..1 is silently ignored by
+ // the agent. Reject both here instead of storing them.
+ if req.TriageProfileID != nil {
+ if *req.TriageProfileID < 0 {
+ writeErr(w, 400, "triage_profile_id must be >= 0 (0 turns the duplicate check off)")
+ return
+ }
+ if *req.TriageProfileID > 0 {
+ if p, err := s.m.pg.ProfileByID(*req.TriageProfileID); err != nil || p == nil {
+ writeErr(w, 400, fmt.Sprintf("triage_profile_id %d does not match any LLM profile", *req.TriageProfileID))
+ return
+ }
+ }
+ }
+ if req.TriageMinConfidence != nil && (*req.TriageMinConfidence < 0 || *req.TriageMinConfidence > 1) {
+ writeErr(w, 400, "triage_min_confidence must be between 0 and 1")
+ return
+ }
// A masked placeholder echoed back keeps the stored secret, like null.
req.BraveKey, req.TavilyKey, req.KeenableKey = keepIfMasked(req.BraveKey), keepIfMasked(req.TavilyKey), keepIfMasked(req.KeenableKey)
req.WebSearchProxy, req.GlobalProxy = keepIfMasked(req.WebSearchProxy), keepIfMasked(req.GlobalProxy)
diff --git a/server/triage.go b/server/triage.go
index cf5033b..c23913b 100644
--- a/server/triage.go
+++ b/server/triage.go
@@ -1,9 +1,14 @@
package server
import (
+ "context"
+ "fmt"
"log"
+ "net"
+ "net/http"
"strconv"
"strings"
+ "time"
"github.com/Autumn-27/artex/agent"
)
@@ -29,7 +34,42 @@ func (s *Server) triageClient() agent.TriageClient {
if strings.TrimSpace(p.BaseURL) == "" || strings.TrimSpace(p.Model) == "" {
return nil
}
- return &agent.SystemOneClient{BaseURL: p.BaseURL, APIKey: p.APIKey, Model: p.Model}
+ client := s.triageHTTPClient(p.BaseURL)
+ if client == nil {
+ return nil
+ }
+ return &agent.SystemOneClient{BaseURL: p.BaseURL, APIKey: p.APIKey, Model: p.Model, HTTP: client}
+}
+
+// triageHTTPClient builds the HTTP client for the decision endpoint under the same
+// endpoint guard the model-list path uses (ARTEX_LLM_PRIVATE_ENDPOINTS, private and
+// metadata addresses refused, redirects not followed). A triage profile is a stored
+// base_url: without the guard, pointing it at an internal host makes the server dial
+// that host on every report_finding. A refused base_url returns nil and triage stays
+// off — the same fail-open path as every other triage failure.
+func (s *Server) triageHTTPClient(baseURL string) *http.Client {
+ g := newModelURLGuard(s)
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ defer cancel()
+ if _, err := g.validateURL(ctx, baseURL, "triage"); err != nil {
+ log.Printf("[triage] base_url refused (%v); dedup stays off", err)
+ return nil
+ }
+ var tr *http.Transport
+ if base, ok := http.DefaultTransport.(*http.Transport); ok {
+ tr = base.Clone()
+ } else {
+ tr = &http.Transport{}
+ }
+ tr.Proxy = nil // a proxy fetches the target itself and would bypass the dial guard
+ tr.DialContext = (&net.Dialer{Timeout: 10 * time.Second, Control: g.blockDial}).DialContext
+ return &http.Client{
+ Transport: tr,
+ Timeout: agent.TriageHTTPTimeout,
+ CheckRedirect: func(*http.Request, []*http.Request) error {
+ return fmt.Errorf("triage: redirects are not followed")
+ },
+ }
}
// applyTriageThreshold pushes the stored threshold into the agent package. Called on
diff --git a/server/triage_review_test.go b/server/triage_review_test.go
new file mode 100644
index 0000000..05a0d26
--- /dev/null
+++ b/server/triage_review_test.go
@@ -0,0 +1,114 @@
+package server
+
+import (
+ "context"
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "strconv"
+ "strings"
+ "testing"
+
+ "github.com/Autumn-27/artex/db"
+)
+
+// A triage profile is a stored base_url, so the decision endpoint has to pass the
+// same guard the model-list path uses: without it, pointing the profile at an
+// internal host makes the server dial that host on every report_finding.
+func TestTriageHTTPClientGuard(t *testing.T) {
+ s := &Server{}
+ t.Setenv(LLMPrivateEndpointsEnv, "")
+ if c := s.triageHTTPClient("http://127.0.0.1:8099/v1"); c != nil {
+ t.Fatal("private triage endpoint was accepted without an allow-list entry")
+ }
+ if c := s.triageHTTPClient("http://169.254.169.254/latest"); c != nil {
+ t.Fatal("metadata address was accepted as a triage endpoint")
+ }
+ t.Setenv(LLMPrivateEndpointsEnv, "127.0.0.1:8099")
+ if c := s.triageHTTPClient("http://127.0.0.1:8099/v1"); c == nil {
+ t.Fatal("allow-listed private triage endpoint was refused")
+ }
+}
+
+// A stored profile id that matches nothing resolves to "off" at run time, which
+// reads as a broken dedup instead of a rejected setting; out-of-range thresholds
+// are silently ignored by the agent. Both are rejected at save time now.
+func TestTriageSettingsValidation(t *testing.T) {
+ skipWithoutDSN(t)
+ m, err := NewManager(t.TempDir(), "")
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer m.Close()
+ clear := func() {
+ for _, k := range []string{settingTriageProfile, settingTriageMinConfidence} {
+ if _, err := m.pg.Exec(`DELETE FROM settings WHERE key=$1`, k); err != nil {
+ t.Error(err)
+ }
+ }
+ }
+ clear()
+ defer clear()
+
+ pid, err := m.pg.SaveProfile(&db.LLMProfile{Name: "triage-test", Format: "openai",
+ BaseURL: "http://127.0.0.1:8099/v1", Model: "pplx-decider", APIKey: "sk-test"})
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ ctx, cancel := context.WithCancel(context.Background())
+ s := New(ctx, m, t.TempDir(), t.TempDir(), t.TempDir())
+ defer stopTestServer(t, s, cancel)
+ token, err := signJWT(s.jwtKey)
+ if err != nil {
+ t.Fatal(err)
+ }
+ do := func(body string) int {
+ t.Helper()
+ req := httptest.NewRequest(http.MethodPut, "/api/settings", strings.NewReader(body))
+ req.Header.Set("Authorization", "Bearer "+token)
+ rec := httptest.NewRecorder()
+ s.Handler().ServeHTTP(rec, req)
+ return rec.Code
+ }
+
+ for _, bad := range []string{
+ `{"triage_profile_id":-5}`,
+ `{"triage_profile_id":999888777}`,
+ `{"triage_min_confidence":-0.2}`,
+ `{"triage_min_confidence":1.7}`,
+ } {
+ if code := do(bad); code != 400 {
+ t.Errorf("PUT %s: %d, want 400", bad, code)
+ }
+ }
+ if v, ok, _ := m.pg.GetSetting(settingTriageProfile); ok {
+ t.Fatalf("rejected PUT stored triage_profile_id=%q", v)
+ }
+
+ good := `{"triage_profile_id":` + strconv.FormatInt(pid, 10) + `,"triage_min_confidence":0.45}`
+ if code := do(good); code != 200 {
+ t.Fatalf("PUT %s: %d, want 200", good, code)
+ }
+ if v, _, _ := m.pg.GetSetting(settingTriageProfile); v != strconv.FormatInt(pid, 10) {
+ t.Fatalf("stored triage_profile_id = %q, want %d", v, pid)
+ }
+ if v, _, _ := m.pg.GetSetting(settingTriageMinConfidence); v != "0.450" {
+ t.Fatalf("stored triage_min_confidence = %q, want 0.450", v)
+ }
+ // 0 is the documented way to turn the check off and must stay accepted.
+ if code := do(`{"triage_profile_id":0}`); code != 200 {
+ t.Fatalf("PUT triage_profile_id=0: %d, want 200", code)
+ }
+ var got map[string]any
+ req := httptest.NewRequest(http.MethodGet, "/api/settings", nil)
+ req.Header.Set("Authorization", "Bearer "+token)
+ rec := httptest.NewRecorder()
+ s.Handler().ServeHTTP(rec, req)
+ if err := json.Unmarshal(rec.Body.Bytes(), &got); err != nil {
+ t.Fatal(err)
+ }
+ if v, _ := got["triage_profile_id"].(float64); int64(v) != 0 {
+ t.Fatalf("GET settings triage_profile_id = %v, want 0", got["triage_profile_id"])
+ }
+}