mirror of
https://github.com/BaaRai/ARTEX.git
synced 2026-11-25 01:10:54 +08:00
Compare commits
26
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0c64c3958c | ||
|
|
1094e9697f | ||
|
|
6ebb2b3d0a | ||
|
|
e17ab07a8a | ||
|
|
b1d2d776f8 | ||
|
|
b6748f8ec0 | ||
|
|
a37403d1e7 | ||
|
|
deba1d1c7a | ||
|
|
fca37610a2 | ||
|
|
a2d011a390 | ||
|
|
5ce4e1eae9 | ||
|
|
2d39964bac | ||
|
|
d2ccabff98 | ||
|
|
9d615bb1ec | ||
|
|
f3b00d204e | ||
|
|
3112fef438 | ||
|
|
f58365c83e | ||
|
|
c8c6df423c | ||
|
|
0b4a0d135e | ||
|
|
528e5230cd | ||
|
|
8e1c88e803 | ||
|
|
b708ea6b9a | ||
|
|
a3e44d3f05 | ||
|
|
24cd7da9af | ||
|
|
ad4c976732 | ||
|
|
10afb2e79a |
@@ -6,6 +6,7 @@ All notable changes to this project are documented in this file. The format is b
|
||||
|
||||
### Added
|
||||
|
||||
- **Wildcard domains in asset scope**: a scope line such as `*.example.com`, the way bug bounty programs write a domain and its subdomains, is accepted in company and task asset scope and stored as the `example.com` domain rule, which already covers its subdomains. A URL form (`https://*.example.com/`) works too. The wildcard is accepted only on a registrable domain: `*.api.example.com`, `*.co.uk` and `*.<IP>` are still rejected, because no rule covers only a subdomain's subdomains (#519).
|
||||
- **Stream viewer direction filter** (follow-up to #380): the Traffic detail's Stream tab can show all messages, client-to-server messages or server-to-client messages. Pagination and refresh keep the selected direction, changing the filter resets the list, and opening another exchange resets the direction to all. Recording-limit warnings remain visible but are excluded from the displayed message counts.
|
||||
- **Security response headers on every response**: `X-Content-Type-Options: nosniff`, a same-origin referrer policy, `X-Frame-Options: SAMEORIGIN` and a `frame-ancestors 'self'` CSP are now set by one wrapper around the whole handler tree, so the JSON API carries them too; previously only the console route did. Console documents additionally get `Permissions-Policy` and COOP/CORP. `Strict-Transport-Security` is sent only when the request is known to be HTTPS: directly over TLS, or via `X-Forwarded-Proto: https` from a peer in `ARTEX_TRUSTED_PROXIES`, so a direct client cannot claim HTTPS on its own. The README reverse-proxy recipe now starts with an 80 to 443 redirect.
|
||||
- **Global company switcher**: the sidebar header carries a company picker (search, an explicit "all companies", the asset count). It persists per browser and narrows these views on the server: the findings list, grouped view, asset tree and stat cards (`GET /api/exploration/findings`, `/groups`, `/asset-tree`, `/stats` take `company`), the dashboard findings panels (same list endpoint), the task list (`GET /api/tasks?company=`), the traffic list (`GET /api/traffic?company=`, the hosts the company owns) and the asset tabs (`GET /api/assets?company_id=`, plain and DSL path; the company clause is ANDed outside the compiled DSL). A finding belongs to a company through its live assets. A finding with no live asset belongs to a company only when its task is scoped to that company (`task_scope` kind `company`); otherwise it shows under "all companies" only. An unknown or non-numeric company id returns nothing (#425).
|
||||
@@ -13,6 +14,7 @@ All notable changes to this project are documented in this file. The format is b
|
||||
|
||||
### Fixed
|
||||
|
||||
- **Missing Docker buildx is reported before the build**: without the buildx plugin, Compose only warns and falls back to the legacy builder, which fails on the Dockerfile's first `FROM --platform=$BUILDPLATFORM` with `failed to parse platform`. `install.sh` (all-Docker) and `update.sh` (Docker update) now check `docker buildx version` first and stop with an install hint, and the automatic Docker install on apt-based distros not covered by get.docker.com installs the buildx package as well. The README Docker section names buildx as a requirement.
|
||||
- **A goal URL followed by punctuation is still seeded**: a goal such as `Assess http://juiceshop:3000.` no longer logs `could not parse a target host/IP` and skips the site. Trailing punctuation, including full-width `。` and a closing bracket that has no matching opener, is trimmed from the URL before it is parsed, so `http://[::1]` is left alone. The scheme the goal names is kept and a final period does not end up in the host.
|
||||
- **Task timeout triggers fire for every task**: `on_task_timeout` used the task id as a watermark, but tasks time out in deadline order. Once a newer task timed out first, an older task that timed out later was never fired for. Fired timeouts are now kept in a persisted set, like met goals; on first start the set is seeded with the tasks already timed out, so nothing replays.
|
||||
- **A named pipe in the task workspace no longer hangs the archive worker**: packing opened every non-directory entry, and opening a FIFO blocks until a writer appears, so the single archive worker stopped there and every later archive, restore and delete job waited behind it. A socket failed the archive instead, and a device was packed but refused on restore. The packer now skips every entry that is neither a directory nor a regular file, as it already did for symlinks.
|
||||
|
||||
@@ -344,6 +344,12 @@ docker compose up -d --build
|
||||
# → http://localhost:8787
|
||||
```
|
||||
|
||||
The checkout build needs the Docker **buildx** plugin (BuildKit). Docker Desktop and
|
||||
get.docker.com include it; distro packages and Homebrew's docker CLI (Colima) may not. If
|
||||
`docker buildx version` fails, install `docker-buildx-plugin` or `docker-buildx`, or on macOS
|
||||
`brew install docker-buildx`. Without it the build stops at the first stage with
|
||||
`failed to parse platform`.
|
||||
|
||||
The release workflow publishes a multi-arch image (`linux/amd64`, `linux/arm64`) to GitHub
|
||||
Container Registry on each `v*` tag, with tags `:latest`, `:v<version>`, and `:<version>`.
|
||||
v0.7.0 predates that step, so there is no `artex` package yet: until the next tagged release,
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
package agent
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// The «proved but not registered» block must reach the planner's situational block.
|
||||
// Without it the counter exists and the planner never sees it. Calls without a
|
||||
// lookup (nil factOnly) must not panic and must not print the block.
|
||||
func TestPlannerSituationalCarriesFactOnlyBlock(t *testing.T) {
|
||||
with := plannerSituational(nil, triggerLookup{
|
||||
factOnly: func(dataEnvelope) string {
|
||||
return "\n\n[Proved but not registered: 2 finished intent(s) produced facts and NO finding.]\n"
|
||||
},
|
||||
}, nil, newDataEnvelope())
|
||||
if !strings.Contains(with, "Proved but not registered") {
|
||||
t.Fatalf("situational block lost the fact-only nudge:\n%s", with)
|
||||
}
|
||||
|
||||
without := plannerSituational(nil, triggerLookup{}, nil, newDataEnvelope())
|
||||
if strings.Contains(without, "Proved but not registered") {
|
||||
t.Fatalf("empty lookup should not print the block:\n%s", without)
|
||||
}
|
||||
}
|
||||
|
||||
// The lookup receives the round's envelope, so the block can frame its data with it.
|
||||
func TestFactOnlyLookupReceivesRoundEnvelope(t *testing.T) {
|
||||
env := newDataEnvelope()
|
||||
var got dataEnvelope
|
||||
look := triggerLookup{factOnly: func(e dataEnvelope) string {
|
||||
got = e
|
||||
return ""
|
||||
}}
|
||||
_ = plannerSituational(nil, look, nil, env)
|
||||
if got.nonce != env.nonce {
|
||||
t.Fatalf("lookup got nonce %q, want the round nonce %q", got.nonce, env.nonce)
|
||||
}
|
||||
}
|
||||
+44
-1
@@ -4,6 +4,7 @@ import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
@@ -23,6 +24,7 @@ import (
|
||||
// into the frontier. It is the sole intent generator.
|
||||
type Planner struct {
|
||||
findingRecorder FindingRecorder
|
||||
triage TriageClient // advisory decision-model client (agent/triage.go); nil = off
|
||||
prov llm.Provider
|
||||
model string
|
||||
tx *transcript.Store // raw LLM conversation persistence (nil = off)
|
||||
@@ -394,6 +396,9 @@ type triggerLookup struct {
|
||||
intentSummary func(int64) string
|
||||
workerOutput func(int64) string
|
||||
factIDs func(int64) string
|
||||
// factOnly renders the «proved but not registered» block: intents that produced
|
||||
// facts and no finding. Nil in tests that do not care about it.
|
||||
factOnly func(dataEnvelope) string
|
||||
}
|
||||
|
||||
func storeTriggerLookup(ts *db.ExplorationStore) triggerLookup {
|
||||
@@ -401,13 +406,50 @@ func storeTriggerLookup(ts *db.ExplorationStore) triggerLookup {
|
||||
intentSummary: func(id int64) string { return intentSummary(ts, id) },
|
||||
workerOutput: func(id int64) string { return workerOutput(ts, id) },
|
||||
factIDs: func(id int64) string { return factIDsYielded(ts, id) },
|
||||
factOnly: func(env dataEnvelope) string { return factOnlyBlock(ts, env) },
|
||||
}
|
||||
}
|
||||
|
||||
// factOnlyBlock names the intents whose work proved something and registered no
|
||||
// finding — the defect the run record shows plainly (three runs in twelve had every
|
||||
// fact-producing intent register nothing). A fact carries no "this is a defect"
|
||||
// flag, so the planner is the only place that can turn one into a finding; without
|
||||
// the counter it has to notice by reading every fact again.
|
||||
func factOnlyBlock(ts *db.ExplorationStore, env dataEnvelope) string {
|
||||
if ts == nil {
|
||||
return ""
|
||||
}
|
||||
rows, err := ts.FactOnlyIntents(0)
|
||||
if err != nil || len(rows) == 0 {
|
||||
return ""
|
||||
}
|
||||
var b strings.Builder
|
||||
var list strings.Builder
|
||||
b.WriteString("\n\n[Proved but not registered: ")
|
||||
b.WriteString(strconv.Itoa(len(rows)))
|
||||
b.WriteString(" finished intent(s) produced facts and NO finding. For each, decide explicitly: " +
|
||||
"either register the defect as a finding (report_finding, with the executed request as evidence) " +
|
||||
"or state why the fact is not a defect. Facts carry no defect flag — only you can turn one into a finding.]\n")
|
||||
for _, r := range rows {
|
||||
// 140: one sentence of intent summary; 140 characters is enough to tell the
|
||||
// directions apart (the full text is in one node_detail). The cut is shared
|
||||
// with the triggers so the block does not become a second context source.
|
||||
fmt.Fprintf(&list, " #%d (%d fact(s)): %s\n", r.IntentID, r.Facts, truncOutput(r.Summary, 140))
|
||||
}
|
||||
// The summaries come from agent output: they are data and go inside the envelope.
|
||||
b.WriteString(env.wrap("fact_only_intents", strings.TrimRight(list.String(), "\n")))
|
||||
b.WriteString("\n")
|
||||
return b.String()
|
||||
}
|
||||
|
||||
// plannerSituational is the planner's situational block for one round: the
|
||||
// envelope intro, the triggers, then the overview, all framed with env.
|
||||
func plannerSituational(evs []TriggerEvent, look triggerLookup, data map[string]any, env dataEnvelope) string {
|
||||
return env.intro() + renderTriggers(evs, env, look) + renderGraphOverview(data, env)
|
||||
block := ""
|
||||
if look.factOnly != nil {
|
||||
block = look.factOnly(env)
|
||||
}
|
||||
return env.intro() + renderTriggers(evs, env, look) + renderGraphOverview(data, env) + block
|
||||
}
|
||||
|
||||
// plannerDefaultTmpl is the built-in EDITABLE body (section [A]) of the planner
|
||||
@@ -482,6 +524,7 @@ func (p *Planner) Plan(ctx context.Context, taskID int64, as *db.AssetStore, ts
|
||||
p.compactor.OnPlannerRound(ctx, ts)
|
||||
tsx := NewToolSet(ts, "planner")
|
||||
tsx.SetFindingRecorder(p.findingRecorder)
|
||||
tsx.SetTriageClient(p.triage)
|
||||
// The host's finding recorder owns the live capture; prove_goal checks bound
|
||||
// traffic_refs against it. No checker means finding proofs are refused.
|
||||
if c, ok := p.findingRecorder.(TrafficCaptureChecker); ok {
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
@@ -139,6 +140,10 @@ func compactIntents(ns []*db.Node, parentsOf, yieldsOf map[int64][]int64) []map[
|
||||
// One ToolSet is created per planner/worker run; per-run signals live here.
|
||||
type ToolSet struct {
|
||||
findingRecorder FindingRecorder
|
||||
// triage, if set, is an advisory decision-model client used for closed-list
|
||||
// judgements (currently the duplicate check in report_finding). nil = the
|
||||
// judgement is left to the main model, exactly as before. See agent/triage.go.
|
||||
triage TriageClient
|
||||
// trafficProofChecker verifies that a bound snapshot's source_traffic_id
|
||||
// exists in the live capture store during prove_goal. Planner.Plan wires it
|
||||
// from the finding recorder; nil or any error fails closed.
|
||||
@@ -1525,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"`
|
||||
@@ -1566,6 +1573,32 @@ func (t *ToolSet) addFinding() actool.CoreTool {
|
||||
}
|
||||
}
|
||||
input := db.RecordFindingInput{TaskID: t.taskID, ExplorationID: t.ts.ID(), IntentID: pid(a.IntentID), VulnClass: a.VulnClass, Name: a.Name, Severity: a.Severity, Summary: a.Summary, Evidence: a.Evidence, Worker: t.worker, AssetIDs: pidList(a.AssetIDs), Counterevidence: a.Counterevidence, ConfidenceRationale: a.ConfidenceRationale}
|
||||
// Advisory dedup (agent/triage.go): a decision model answers "same defect as
|
||||
// an already registered finding?" in one small request instead of a
|
||||
// main-model turn. A confident duplicate is not registered a second time —
|
||||
// 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.
|
||||
//
|
||||
// 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,
|
||||
"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 (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 {
|
||||
recorded, err = t.findingRecorder.Record(ctx, input, refs)
|
||||
|
||||
+500
@@ -0,0 +1,500 @@
|
||||
package agent
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"math"
|
||||
"net/http"
|
||||
"regexp"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/Autumn-27/artex/db"
|
||||
)
|
||||
|
||||
// Triage through a decision model (the llama.cpp /v1/systemone contract).
|
||||
//
|
||||
// A decision model answers a closed-list question with probabilities and generates
|
||||
// no text, so a judgement that otherwise costs a main-model turn over a six-figure
|
||||
// context costs one small request instead. Measured on our own findings (15
|
||||
// candidates, hand labels): picking the duplicate 8/8 on the 27B model and 7/8 on
|
||||
// the flash one, against 7/15 for the constant "always distinct", at 0.66 s and
|
||||
// ~1.7k input tokens per call with zero output tokens.
|
||||
//
|
||||
// It is ADVISORY by construction: every failure path falls back to today's
|
||||
// behaviour, and only a confident answer changes an outcome.
|
||||
|
||||
// Порог уверенности, выше которого ответ «дубль» гасит регистрацию.
|
||||
// Переменная, а не константа: уверенность падает с шириной вопроса, и один
|
||||
// фиксированный 0.5 не обслуживает оба конца. Снижать не страшно — результат
|
||||
// подавления велит агенту перерегистрировать находку, если она различна.
|
||||
// замер: калибровка stage3_calibrate.py 2026-11-22 — recall 1.00 при FP 0.47 на 75
|
||||
// жёстких негативах; на истинных дублях в живом прогоне 0.30-0.79. при превышении
|
||||
// порога: находка не регистрируется, вызывающий получает finding_id.
|
||||
const defaultTriageMinConfidence = 0.5
|
||||
|
||||
// triageDupMinConfidenceBits holds the threshold as float64 bits. It is written by the
|
||||
// settings path (an HTTP goroutine) and read by the report_finding worker, so it is
|
||||
// atomic: a plain float global is a data race under -race.
|
||||
var triageDupMinConfidenceBits atomic.Uint64
|
||||
|
||||
func init() {
|
||||
triageDupMinConfidenceBits.Store(math.Float64bits(defaultTriageMinConfidence))
|
||||
}
|
||||
|
||||
// SetTriageMinConfidence overrides the suppression threshold. v <= 0 restores the default.
|
||||
func SetTriageMinConfidence(v float64) {
|
||||
if v <= 0 {
|
||||
v = defaultTriageMinConfidence
|
||||
}
|
||||
triageDupMinConfidenceBits.Store(math.Float64bits(v))
|
||||
}
|
||||
|
||||
// triageDupThreshold returns the current suppression threshold.
|
||||
func triageDupThreshold() float64 {
|
||||
return math.Float64frombits(triageDupMinConfidenceBits.Load())
|
||||
}
|
||||
|
||||
const (
|
||||
// Потолок кандидатов в вопросе; отбор по релевантности, а не «новейшие N» —
|
||||
// при широком графе верный партнёр выпадает из новейших по возрасту (triageRelevant).
|
||||
// замер: ширина вопроса на реальном дубле, stage3_width.py 2026-11-22 — уверенность
|
||||
// 0.81-0.91 до 11 кандидатов, 0.64 на 19, 0.56 на 29; латентность 0.44->1.29 с.
|
||||
// при превышении: лишние кандидаты отбрасываются по релевантности.
|
||||
triageMaxExisting = 10
|
||||
// Обрезка ОДНОЙ сводки; обрезка по записи, а не по состоянию целиком — иначе
|
||||
// режется посреди строки и criteria остаётся с id, строки которого в состоянии нет.
|
||||
// замер: распределение длин сводок в графе 2026-11-22 — p50 189, p90 334, max 564
|
||||
// (53 находки), то есть 400 сохраняет 90% сводок целиком. при превышении: сводка
|
||||
// обрезается с «…», запись остаётся опознаваемой.
|
||||
triageMaxSummaryChars = 400
|
||||
// Страховка на собранное состояние при потолке 10 записей.
|
||||
// запас посчитан: 10*(400+60) + кандидат 480 ≈ 5.1 КБ против 6000, то есть 1.17x;
|
||||
// при поштучной обрезке срабатывает только на патологических сводках.
|
||||
// при превышении: состояние режется по границе записи.
|
||||
triageMaxStateChars = 6000
|
||||
)
|
||||
|
||||
// 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
|
||||
Summary string
|
||||
// RelatedTask is non-zero when the finding belongs to a directly related task
|
||||
// (read-only here); it rides into the question so the model can weigh it.
|
||||
RelatedTask int64
|
||||
}
|
||||
|
||||
// DuplicateAnswer is the parsed verdict: DuplicateOf == 0 means "genuinely distinct".
|
||||
type DuplicateAnswer struct {
|
||||
DuplicateOf int64
|
||||
// DuplicateOfNode is the exploration node id of DuplicateOf (0 when unknown).
|
||||
DuplicateOfNode int64
|
||||
Confidence float64
|
||||
}
|
||||
|
||||
// TriageClient answers the closed-list questions the agent asks.
|
||||
type TriageClient interface {
|
||||
Duplicate(ctx context.Context, cand TriageCandidate, existing []TriageCandidate) (DuplicateAnswer, error)
|
||||
}
|
||||
|
||||
// SystemOneClient is a TriageClient over a decision-model endpoint. BaseURL is the
|
||||
// OpenAI-style base ("https://host:8088/v1"); "/systemone" is appended.
|
||||
type SystemOneClient struct {
|
||||
BaseURL string
|
||||
APIKey string
|
||||
Model string
|
||||
HTTP *http.Client
|
||||
}
|
||||
|
||||
// Таймаут запроса к decider. замер: латентность 0.26-0.57 с при ширине до 11 и 1.29 с на 29
|
||||
// (stage3_width.py 2026-11-22), 3.83-3.96 с на 27B-варианте (этап 0, 2026-11-21); у пула
|
||||
// conc=2 и нет очереди, занятость добавляет ожидание. запас ~5x к худшему замеру.
|
||||
// при превышении: ошибка -> fail open, находка регистрируется как раньше.
|
||||
// Экспортирован, чтобы сервер, собирающий клиенту 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}
|
||||
}
|
||||
|
||||
// Duplicate asks which existing finding, if any, is the same defect as cand.
|
||||
func (c *SystemOneClient) Duplicate(ctx context.Context, cand TriageCandidate, existing []TriageCandidate) (DuplicateAnswer, error) {
|
||||
if strings.TrimSpace(c.BaseURL) == "" || strings.TrimSpace(c.Model) == "" {
|
||||
return DuplicateAnswer{}, fmt.Errorf("triage: base_url and model are required")
|
||||
}
|
||||
if len(existing) == 0 || strings.TrimSpace(cand.Summary) == "" {
|
||||
return DuplicateAnswer{}, nil
|
||||
}
|
||||
body, err := json.Marshal(map[string]any{
|
||||
"model": c.Model,
|
||||
"state": buildDuplicateState(cand, existing),
|
||||
"questions": map[string]any{
|
||||
"duplicate_of": map[string]any{
|
||||
"type": "choice",
|
||||
"instructions": duplicateInstructions,
|
||||
"criteria": duplicateCriteria(existing),
|
||||
},
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
return DuplicateAnswer{}, err
|
||||
}
|
||||
url := strings.TrimRight(c.BaseURL, "/") + "/systemone"
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(body))
|
||||
if err != nil {
|
||||
return DuplicateAnswer{}, err
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
if c.APIKey != "" {
|
||||
req.Header.Set("Authorization", "Bearer "+c.APIKey)
|
||||
}
|
||||
resp, err := c.http().Do(req)
|
||||
if err != nil {
|
||||
return DuplicateAnswer{}, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
// 1 MiB: ответ decider — это JSON вероятностей, замеренный 0.3-2 КБ (живые прогоны),
|
||||
// то есть запас ~500x; потолок страхует от чатоподобного эндпоинта вместо decision.
|
||||
// при превышении: тело читается частично, JSON может не распарситься -> fail open.
|
||||
raw, err := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
|
||||
if err != nil {
|
||||
return DuplicateAnswer{}, err
|
||||
}
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return DuplicateAnswer{}, fmt.Errorf("triage: status %d: %s", resp.StatusCode, triageFirstLine(raw))
|
||||
}
|
||||
ids := make(map[int64]bool, len(existing))
|
||||
for _, e := range existing {
|
||||
ids[e.FindingID] = true
|
||||
}
|
||||
return parseDuplicateAnswer(raw, ids)
|
||||
}
|
||||
|
||||
const duplicateInstructions = "The CANDIDATE finding is new. Decide whether it is the SAME defect as one of " +
|
||||
"the REGISTERED findings (same endpoint, same parameter, same root cause) or a genuinely distinct finding. " +
|
||||
"Answer 'none' when the candidate is distinct even if it shares the vulnerability class with a registered one."
|
||||
|
||||
// buildDuplicateState renders the question's state. Deterministic: findings in the
|
||||
// order given, candidate first.
|
||||
func buildDuplicateState(cand TriageCandidate, existing []TriageCandidate) string {
|
||||
var b strings.Builder
|
||||
fmt.Fprintf(&b, "CANDIDATE FINDING\nclass: %s\nseverity: %s\nname: %s\nsummary: %s\n\nREGISTERED FINDINGS\n",
|
||||
cand.VulnClass, cand.Severity, cand.Name, capText(cand.Summary, triageMaxSummaryChars))
|
||||
for _, e := range existing {
|
||||
rel := ""
|
||||
if e.RelatedTask > 0 {
|
||||
rel = fmt.Sprintf(" (related task %d)", e.RelatedTask)
|
||||
}
|
||||
fmt.Fprintf(&b, "[%d]%s class=%s severity=%s name=%s | %s\n",
|
||||
e.FindingID, rel, e.VulnClass, e.Severity, e.Name, capText(e.Summary, triageMaxSummaryChars))
|
||||
}
|
||||
out := b.String()
|
||||
if len(out) > triageMaxStateChars {
|
||||
out = cutRunes(out, triageMaxStateChars)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// duplicateCriteria builds the closed list: "none" plus one key per finding id.
|
||||
func duplicateCriteria(existing []TriageCandidate) map[string]any {
|
||||
c := map[string]any{"none": "a genuinely distinct finding (different endpoint, parameter or root cause)"}
|
||||
for _, e := range existing {
|
||||
desc := strings.TrimSpace(e.Name)
|
||||
if s := strings.TrimSpace(e.Summary); s != "" {
|
||||
if desc != "" {
|
||||
desc += " | "
|
||||
}
|
||||
desc += s
|
||||
}
|
||||
if desc == "" {
|
||||
desc = "registered finding"
|
||||
}
|
||||
c[strconv.FormatInt(e.FindingID, 10)] = desc
|
||||
}
|
||||
return c
|
||||
}
|
||||
|
||||
// triageDuplicateHit reports whether an answer should suppress registration.
|
||||
// Split out so the threshold is testable without an HTTP round trip.
|
||||
func triageDuplicateHit(ans DuplicateAnswer) bool {
|
||||
return ans.DuplicateOf > 0 && ans.Confidence >= triageDupThreshold()
|
||||
}
|
||||
|
||||
// parseDuplicateAnswer reads answers.duplicate_of. A choice that is not one of the
|
||||
// offered ids is treated as "none" rather than as an error: the model naming an
|
||||
// unknown id must not suppress a finding.
|
||||
func parseDuplicateAnswer(raw []byte, existingIDs map[int64]bool) (DuplicateAnswer, error) {
|
||||
var resp struct {
|
||||
Answers map[string]struct {
|
||||
Type string `json:"type"`
|
||||
Choice string `json:"choice"`
|
||||
Confidence float64 `json:"confidence"`
|
||||
Probabilities map[string]float64 `json:"probabilities"`
|
||||
} `json:"answers"`
|
||||
}
|
||||
if err := json.Unmarshal(raw, &resp); err != nil {
|
||||
return DuplicateAnswer{}, fmt.Errorf("triage: bad answer json: %w", err)
|
||||
}
|
||||
a, ok := resp.Answers["duplicate_of"]
|
||||
if !ok {
|
||||
return DuplicateAnswer{}, fmt.Errorf("triage: answer has no duplicate_of")
|
||||
}
|
||||
conf := a.Confidence
|
||||
if conf == 0 && a.Probabilities != nil {
|
||||
conf = a.Probabilities[a.Choice] // some runtimes only fill probabilities
|
||||
}
|
||||
choice := strings.TrimSpace(a.Choice)
|
||||
if choice == "" || choice == "none" {
|
||||
return DuplicateAnswer{Confidence: conf}, nil
|
||||
}
|
||||
id, err := strconv.ParseInt(choice, 10, 64)
|
||||
if err != nil || !existingIDs[id] {
|
||||
return DuplicateAnswer{Confidence: conf}, nil
|
||||
}
|
||||
return DuplicateAnswer{DuplicateOf: id, Confidence: conf}, nil
|
||||
}
|
||||
|
||||
func capText(s string, n int) string {
|
||||
if n > 0 && len(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 {
|
||||
s = s[:i]
|
||||
}
|
||||
if len(s) > 200 {
|
||||
s = s[:200]
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// --- wiring into report_finding ---
|
||||
|
||||
// SetTriageClient installs (or, with nil, removes) the advisory triage client.
|
||||
func (t *ToolSet) SetTriageClient(c TriageClient) { t.triage = c }
|
||||
|
||||
// SetTriageClient mirrors ToolSet.SetTriageClient for the worker and planner: the
|
||||
// per-run ToolSet is built inside their Plan/Run, so the client has to ride on the
|
||||
// agent the same way the finding recorder does.
|
||||
func (w *Worker) SetTriageClient(c TriageClient) { w.triage = c }
|
||||
func (p *Planner) SetTriageClient(c TriageClient) { p.triage = c }
|
||||
|
||||
// triageDuplicate asks the client about the finding being registered, against the
|
||||
// task's already registered findings. Ordering and truncation keep the question
|
||||
// bounded: newest findings first (a duplicate of a fresh finding is the common case).
|
||||
func (t *ToolSet) triageDuplicate(ctx context.Context, in db.RecordFindingInput) (DuplicateAnswer, bool) {
|
||||
if t.triage == nil || t.ts == nil {
|
||||
log.Printf("[triage] skip: client=%v store=%v", t.triage != nil, t.ts != nil)
|
||||
return DuplicateAnswer{}, false
|
||||
}
|
||||
nodes, err := t.ts.ListByKindWithSources(db.KindFinding, 500)
|
||||
if err != nil || len(nodes) == 0 {
|
||||
log.Printf("[triage] skip: nodes=%d err=%v", len(nodes), err)
|
||||
return DuplicateAnswer{}, false
|
||||
}
|
||||
// Findings from independently created tasks on the same assets are NOT in the
|
||||
// own-task pool (task_relations only links spawned tasks), yet they are exactly
|
||||
// the duplicates a human would merge. The candidate's own asset ids are the join.
|
||||
if len(in.AssetIDs) > 0 {
|
||||
if cross, err := t.ts.FindingsSharingAssets(in.AssetIDs, t.taskID, triageMaxExisting); err == nil {
|
||||
seen := make(map[int64]bool, len(nodes))
|
||||
for _, n := range nodes {
|
||||
seen[n.ID] = true
|
||||
}
|
||||
for _, n := range cross {
|
||||
if n != nil && !seen[n.ID] {
|
||||
nodes = append(nodes, n)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// FindingID lives in the findings table, not on the node: without this the
|
||||
// candidate list is built from nodes whose FindingID is still 0 and every
|
||||
// entry is dropped (observed live: "nodes=6, no usable existing findings").
|
||||
if err := t.ts.PopulateFindingTrafficIDs(nodes); err != nil {
|
||||
log.Printf("[triage] populate finding ids failed: %v", err)
|
||||
}
|
||||
existing := triageCandidates(nodes, in)
|
||||
if len(existing) == 0 {
|
||||
log.Printf("[triage] skip: no usable existing findings (nodes=%d)", len(nodes))
|
||||
return DuplicateAnswer{}, false
|
||||
}
|
||||
log.Printf("[triage] asking: existing=%d candidate=%q", len(existing), in.Name)
|
||||
ans, err := t.triage.Duplicate(ctx, TriageCandidate{
|
||||
Name: in.Name, VulnClass: in.VulnClass, Severity: in.Severity, Summary: in.Summary,
|
||||
}, existing)
|
||||
if err != nil {
|
||||
log.Printf("[triage] client error (fail open): %v", err)
|
||||
return DuplicateAnswer{}, false
|
||||
}
|
||||
// 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
|
||||
// kept — the agent sees them in list_findings too — and marked so the model knows
|
||||
// they are not this task's own.
|
||||
func triageCandidates(nodes []*db.Node, in db.RecordFindingInput) []TriageCandidate {
|
||||
usable := make([]*db.Node, 0, len(nodes))
|
||||
for _, n := range nodes {
|
||||
if n != nil && n.FindingID > 0 {
|
||||
usable = append(usable, n)
|
||||
}
|
||||
}
|
||||
sort.SliceStable(usable, func(i, j int) bool { return usable[i].ID > usable[j].ID })
|
||||
out := make([]TriageCandidate, 0, triageMaxExisting)
|
||||
for _, n := range triageRelevant(usable, in, triageMaxExisting) {
|
||||
var p map[string]any
|
||||
_ = 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"),
|
||||
Summary: strField(p, "summary"),
|
||||
RelatedTask: func() int64 {
|
||||
if n.Inherited {
|
||||
return n.SourceTaskID
|
||||
}
|
||||
return 0
|
||||
}(),
|
||||
})
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// triageRelevant ranks candidate findings for the question and keeps the best cap.
|
||||
//
|
||||
// Ranking, strongest first: the same vulnerability class, an overlapping endpoint,
|
||||
// membership in another task that shares an asset (those nodes arrive pre-filtered
|
||||
// by asset, which is itself a signal), then newest. A flat "newest N" is arbitrary
|
||||
// and drops the true partner on a wide graph; relevance keeps what the question is
|
||||
// about. Falls back to the newest cap when nothing scores, so behaviour without
|
||||
// assets (or on a first finding) is unchanged.
|
||||
func triageRelevant(nodes []*db.Node, in db.RecordFindingInput, cap int) []*db.Node {
|
||||
if cap <= 0 || len(nodes) <= cap {
|
||||
return nodes
|
||||
}
|
||||
candEP := endpointTokens(in.Summary)
|
||||
type scored struct {
|
||||
n *db.Node
|
||||
score int
|
||||
}
|
||||
ranked := make([]scored, 0, len(nodes))
|
||||
for _, n := range nodes {
|
||||
var p map[string]any
|
||||
_ = json.Unmarshal(n.Payload, &p)
|
||||
s := 0
|
||||
if in.VulnClass != "" && strField(p, "vulnclass") == in.VulnClass {
|
||||
s += 2
|
||||
}
|
||||
if len(candEP) > 0 {
|
||||
for ep := range endpointTokens(strField(p, "summary")) {
|
||||
if candEP[ep] {
|
||||
s += 2
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
if n.Inherited {
|
||||
s++ // another task on a shared asset: already a signal, not noise
|
||||
}
|
||||
ranked = append(ranked, scored{n, s})
|
||||
}
|
||||
sort.SliceStable(ranked, func(i, j int) bool {
|
||||
if ranked[i].score != ranked[j].score {
|
||||
return ranked[i].score > ranked[j].score
|
||||
}
|
||||
return ranked[i].n.ID > ranked[j].n.ID
|
||||
})
|
||||
out := make([]*db.Node, 0, cap)
|
||||
for _, r := range ranked {
|
||||
if len(out) >= cap {
|
||||
break
|
||||
}
|
||||
out = append(out, r.n)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
var endpointTokenRe = regexp.MustCompile(`/(?:rest|api|v[0-9])/[a-z0-9_{}./-]+`)
|
||||
|
||||
func endpointTokens(s string) map[string]bool {
|
||||
out := map[string]bool{}
|
||||
for _, m := range endpointTokenRe.FindAllString(strings.ToLower(s), -1) {
|
||||
out[strings.TrimRight(m, ".,;")] = true
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func strField(p map[string]any, k string) string {
|
||||
if p == nil {
|
||||
return ""
|
||||
}
|
||||
if v, ok := p[k].(string); ok {
|
||||
return v
|
||||
}
|
||||
return ""
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,310 @@
|
||||
package agent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/Autumn-27/artex/db"
|
||||
)
|
||||
|
||||
func triageCandidate() TriageCandidate {
|
||||
return TriageCandidate{VulnClass: "sqli", Severity: "high", Name: "SQLi in search",
|
||||
Summary: "GET /rest/products/search?q= is concatenated into SQL; UNION SELECT dumps Users."}
|
||||
}
|
||||
|
||||
func triageExisting() []TriageCandidate {
|
||||
return []TriageCandidate{
|
||||
{FindingID: 98, VulnClass: "sqli", Severity: "high", Name: "SQL injection in search", Summary: "UNION SELECT dumps the Users table."},
|
||||
{FindingID: 102, VulnClass: "xss", Severity: "medium", Name: "DOM XSS", Summary: "q is bound via innerHTML."},
|
||||
}
|
||||
}
|
||||
|
||||
// newTriageServer returns a test server that captures the request body and replies
|
||||
// with the given answers payload.
|
||||
func newTriageServer(t *testing.T, answers map[string]any, status int) (*httptest.Server, *map[string]any) {
|
||||
t.Helper()
|
||||
var got map[string]any
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if !strings.HasSuffix(r.URL.Path, "/systemone") {
|
||||
t.Errorf("unexpected path %s", r.URL.Path)
|
||||
}
|
||||
if h := r.Header.Get("Authorization"); h != "Bearer testkey" {
|
||||
t.Errorf("authorization header = %q", h)
|
||||
}
|
||||
body, _ := io.ReadAll(r.Body)
|
||||
_ = json.Unmarshal(body, &got)
|
||||
if status != http.StatusOK {
|
||||
w.WriteHeader(status)
|
||||
_, _ = w.Write([]byte(`{"error":{"message":"boom"}}`))
|
||||
return
|
||||
}
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{"answers": answers})
|
||||
}))
|
||||
t.Cleanup(srv.Close)
|
||||
return srv, &got
|
||||
}
|
||||
|
||||
func TestSystemOneClient_DuplicateNamesExistingFinding(t *testing.T) {
|
||||
srv, got := newTriageServer(t, map[string]any{
|
||||
"duplicate_of": map[string]any{"type": "choice", "choice": "98", "confidence": 0.91},
|
||||
}, http.StatusOK)
|
||||
c := &SystemOneClient{BaseURL: srv.URL + "/v1", APIKey: "testkey", Model: "decider"}
|
||||
|
||||
ans, err := c.Duplicate(context.Background(), triageCandidate(), triageExisting())
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if ans.DuplicateOf != 98 || ans.Confidence != 0.91 {
|
||||
t.Fatalf("answer = %+v, want duplicate 98 @0.91", ans)
|
||||
}
|
||||
// The question must offer every existing finding plus "none", and carry the
|
||||
// candidate so the model can compare.
|
||||
if (*got)["model"] != "decider" {
|
||||
t.Fatalf("model not sent: %v", (*got)["model"])
|
||||
}
|
||||
state, _ := (*got)["state"].(string)
|
||||
if !strings.Contains(state, "CANDIDATE FINDING") || !strings.Contains(state, "[98]") {
|
||||
t.Fatalf("state does not carry candidate and existing findings:\n%s", state)
|
||||
}
|
||||
q := (*got)["questions"].(map[string]any)["duplicate_of"].(map[string]any)
|
||||
if q["type"] != "choice" {
|
||||
t.Fatalf("question type = %v", q["type"])
|
||||
}
|
||||
crit := q["criteria"].(map[string]any)
|
||||
for _, k := range []string{"none", "98", "102"} {
|
||||
if _, ok := crit[k]; !ok {
|
||||
t.Fatalf("criteria misses %q: %v", k, crit)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSystemOneClient_DistinctFinding(t *testing.T) {
|
||||
srv, _ := newTriageServer(t, map[string]any{
|
||||
"duplicate_of": map[string]any{"type": "choice", "choice": "none", "confidence": 0.88},
|
||||
}, http.StatusOK)
|
||||
c := &SystemOneClient{BaseURL: srv.URL + "/v1", APIKey: "testkey", Model: "decider"}
|
||||
|
||||
ans, err := c.Duplicate(context.Background(), triageCandidate(), triageExisting())
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if ans.DuplicateOf != 0 {
|
||||
t.Fatalf("want no duplicate, got %d", ans.DuplicateOf)
|
||||
}
|
||||
}
|
||||
|
||||
// An id the question never offered must not suppress a finding.
|
||||
func TestSystemOneClient_UnknownChoiceIsNotADuplicate(t *testing.T) {
|
||||
srv, _ := newTriageServer(t, map[string]any{
|
||||
"duplicate_of": map[string]any{"choice": "777", "confidence": 0.99},
|
||||
}, http.StatusOK)
|
||||
c := &SystemOneClient{BaseURL: srv.URL + "/v1", APIKey: "testkey", Model: "decider"}
|
||||
|
||||
ans, err := c.Duplicate(context.Background(), triageCandidate(), triageExisting())
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if ans.DuplicateOf != 0 {
|
||||
t.Fatalf("unknown id must read as distinct, got %d", ans.DuplicateOf)
|
||||
}
|
||||
}
|
||||
|
||||
// Runtimes that fill only probabilities still yield a usable confidence.
|
||||
func TestParseDuplicateAnswer_FallsBackToProbability(t *testing.T) {
|
||||
raw := []byte(`{"answers":{"duplicate_of":{"type":"choice","choice":"98","probabilities":{"none":0.1,"98":0.8,"102":0.1}}}}`)
|
||||
ans, err := parseDuplicateAnswer(raw, map[int64]bool{98: true, 102: true})
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if ans.DuplicateOf != 98 || ans.Confidence != 0.8 {
|
||||
t.Fatalf("answer = %+v, want 98 @0.8", ans)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSystemOneClient_ErrorOnBadStatus(t *testing.T) {
|
||||
srv, _ := newTriageServer(t, nil, http.StatusInternalServerError)
|
||||
c := &SystemOneClient{BaseURL: srv.URL + "/v1", APIKey: "testkey", Model: "decider"}
|
||||
if _, err := c.Duplicate(context.Background(), triageCandidate(), triageExisting()); err == nil {
|
||||
t.Fatal("want an error on 500 so the caller can fail open")
|
||||
}
|
||||
}
|
||||
|
||||
// Nothing to judge: no existing findings or an empty summary must not cost a call.
|
||||
func TestSystemOneClient_NoCallWithoutInput(t *testing.T) {
|
||||
called := 0
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
called++
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{})
|
||||
}))
|
||||
defer srv.Close()
|
||||
c := &SystemOneClient{BaseURL: srv.URL + "/v1", Model: "decider"}
|
||||
|
||||
if _, err := c.Duplicate(context.Background(), triageCandidate(), nil); err != nil {
|
||||
t.Fatalf("no existing findings: %v", err)
|
||||
}
|
||||
empty := triageCandidate()
|
||||
empty.Summary = ""
|
||||
if _, err := c.Duplicate(context.Background(), empty, triageExisting()); err != nil {
|
||||
t.Fatalf("empty summary: %v", err)
|
||||
}
|
||||
if called != 0 {
|
||||
t.Fatalf("expected no HTTP call, got %d", called)
|
||||
}
|
||||
}
|
||||
|
||||
// Regression: FindingID lives in the findings table, not on the node. Building
|
||||
// candidates from nodes as they come out of the store dropped every entry
|
||||
// ("nodes=6, no usable existing findings" on a live run) and triage never fired.
|
||||
func TestTriageCandidates_SkipsNodesWithoutFindingRow(t *testing.T) {
|
||||
payload := func(name string) []byte {
|
||||
b, _ := json.Marshal(map[string]any{"name": name, "vulnclass": "sqli", "severity": "high", "summary": name + " summary"})
|
||||
return b
|
||||
}
|
||||
nodes := []*db.Node{
|
||||
{ID: 10, Kind: db.KindFinding, Payload: payload("no finding row"), FindingID: 0},
|
||||
{ID: 9, Kind: db.KindFinding, Payload: payload("own finding"), FindingID: 98},
|
||||
{ID: 11, Kind: db.KindFinding, Payload: payload("inherited finding"), FindingID: 55, Inherited: true, SourceTaskID: 7},
|
||||
}
|
||||
got := triageCandidates(nodes, db.RecordFindingInput{})
|
||||
if len(got) != 2 {
|
||||
t.Fatalf("want 2 candidates (the row-less node skipped), got %d: %+v", len(got), got)
|
||||
}
|
||||
if got[0].FindingID != 55 || got[0].RelatedTask != 7 {
|
||||
t.Fatalf("newest first with its related task: %+v", got[0])
|
||||
}
|
||||
if got[1].FindingID != 98 || got[1].RelatedTask != 0 {
|
||||
t.Fatalf("own finding must carry no related task: %+v", got[1])
|
||||
}
|
||||
st := buildDuplicateState(TriageCandidate{Summary: "cand"}, got)
|
||||
if !strings.Contains(st, "(related task 7)") {
|
||||
t.Fatalf("state must mark an inherited finding:\n%s", st)
|
||||
}
|
||||
}
|
||||
|
||||
// The cap must be a SELECTION: with more candidates than fit, the ones matching the
|
||||
// candidate's class or endpoint come first, newest only breaking ties.
|
||||
func TestTriageRelevant_PrefersRelevanceOverRecency(t *testing.T) {
|
||||
mk := func(id, findingID int64, class, summary string) *db.Node {
|
||||
b, _ := json.Marshal(map[string]any{"vulnclass": class, "summary": summary})
|
||||
return &db.Node{ID: id, Kind: db.KindFinding, Payload: b, FindingID: findingID}
|
||||
}
|
||||
// The relevant finding is OLDER than the noise, so a newest-first cap would drop
|
||||
// it — that is exactly the live defect this ranking fixes.
|
||||
nodes := []*db.Node{mk(50, 50, "sqli", "GET /rest/user/login is injectable")}
|
||||
for i := int64(100); i < 115; i++ {
|
||||
nodes = append(nodes, mk(i, i, "xss", "GET /other/thing"+strconv.FormatInt(i, 10)))
|
||||
}
|
||||
got := triageCandidates(nodes, db.RecordFindingInput{VulnClass: "sqli", Summary: "POST /rest/user/login injectable"})
|
||||
if len(got) != triageMaxExisting {
|
||||
t.Fatalf("cap = %d, want %d", len(got), triageMaxExisting)
|
||||
}
|
||||
if got[0].FindingID != 50 {
|
||||
t.Fatalf("the relevant OLD finding must rank first, got %d (%+v)", got[0].FindingID, got[0])
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildDuplicateState_CapsPerEntry(t *testing.T) {
|
||||
long := strings.Repeat("y", 500)
|
||||
st := buildDuplicateState(
|
||||
TriageCandidate{Summary: long},
|
||||
[]TriageCandidate{{FindingID: 1, Summary: long}, {FindingID: 2, Summary: long}})
|
||||
// every offered finding stays present and its line is capped, not the whole state
|
||||
for _, id := range []string{"[1]", "[2]"} {
|
||||
if !strings.Contains(st, id) {
|
||||
t.Fatalf("entry %s was cut out of the state:\n%s", id, st)
|
||||
}
|
||||
}
|
||||
if strings.Count(st, "…") < 3 {
|
||||
t.Fatalf("expected every summary to be capped, got %d caps", strings.Count(st, "…"))
|
||||
}
|
||||
if len(st) > triageMaxStateChars {
|
||||
t.Fatalf("state over the safety cap: %d", len(st))
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildDuplicateState_Caps(t *testing.T) {
|
||||
var many []TriageCandidate
|
||||
for i := 0; i < 200; i++ {
|
||||
many = append(many, TriageCandidate{FindingID: int64(i), Summary: strings.Repeat("x", 200)})
|
||||
}
|
||||
st := buildDuplicateState(triageCandidate(), many)
|
||||
if len(st) > triageMaxStateChars {
|
||||
t.Fatalf("state not capped: %d", len(st))
|
||||
}
|
||||
if !strings.Contains(st, "CANDIDATE FINDING") {
|
||||
t.Fatal("state lost the candidate")
|
||||
}
|
||||
}
|
||||
|
||||
func TestTriageDuplicateHit_Threshold(t *testing.T) {
|
||||
defer SetTriageMinConfidence(defaultTriageMinConfidence) // restore the default for other tests
|
||||
SetTriageMinConfidence(defaultTriageMinConfidence)
|
||||
cases := []struct {
|
||||
in DuplicateAnswer
|
||||
want bool
|
||||
}{
|
||||
{DuplicateAnswer{DuplicateOf: 5, Confidence: 0.9}, true},
|
||||
{DuplicateAnswer{DuplicateOf: 5, Confidence: defaultTriageMinConfidence}, true},
|
||||
{DuplicateAnswer{DuplicateOf: 5, Confidence: 0.4}, false}, // below the threshold: register as before
|
||||
{DuplicateAnswer{DuplicateOf: 0, Confidence: 0.99}, false},
|
||||
}
|
||||
for _, c := range cases {
|
||||
if got := triageDuplicateHit(c.in); got != c.want {
|
||||
t.Fatalf("hit(%+v) = %v, want %v", c.in, got, c.want)
|
||||
}
|
||||
}
|
||||
// The live run produced true duplicates at 0.30 with the right partner named, so
|
||||
// a lowered threshold must flip them to a hit — that is the point of the knob.
|
||||
SetTriageMinConfidence(0.25)
|
||||
if !triageDuplicateHit(DuplicateAnswer{DuplicateOf: 5, Confidence: 0.30}) {
|
||||
t.Fatal("0.30 must hit at threshold 0.25")
|
||||
}
|
||||
SetTriageMinConfidence(0.9)
|
||||
if triageDuplicateHit(DuplicateAnswer{DuplicateOf: 5, Confidence: 0.30}) {
|
||||
t.Fatal("0.30 must miss at threshold 0.9")
|
||||
}
|
||||
}
|
||||
|
||||
// The settings path writes the threshold from an HTTP goroutine while report_finding
|
||||
// reads it on a worker. Run under -race: a plain float global fails here.
|
||||
func TestTriageThresholdConcurrentSetAndRead(t *testing.T) {
|
||||
defer SetTriageMinConfidence(0.5)
|
||||
var wg sync.WaitGroup
|
||||
wg.Add(2)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
for i := 0; i < 2000; i++ {
|
||||
SetTriageMinConfidence(0.3 + 0.4*float64(i%2))
|
||||
}
|
||||
}()
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
for i := 0; i < 2000; i++ {
|
||||
_ = triageDuplicateHit(DuplicateAnswer{DuplicateOf: 5, Confidence: 0.6})
|
||||
}
|
||||
}()
|
||||
wg.Wait()
|
||||
}
|
||||
|
||||
func TestSetTriageMinConfidenceZeroRestoresDefault(t *testing.T) {
|
||||
defer SetTriageMinConfidence(defaultTriageMinConfidence)
|
||||
SetTriageMinConfidence(0.9)
|
||||
SetTriageMinConfidence(0)
|
||||
if got := triageDupThreshold(); got != defaultTriageMinConfidence {
|
||||
t.Fatalf("threshold after Set(0) = %v, want %v", got, defaultTriageMinConfidence)
|
||||
}
|
||||
SetTriageMinConfidence(-1)
|
||||
if got := triageDupThreshold(); got != defaultTriageMinConfidence {
|
||||
t.Fatalf("threshold after Set(-1) = %v, want %v", got, defaultTriageMinConfidence)
|
||||
}
|
||||
if !triageDuplicateHit(DuplicateAnswer{DuplicateOf: 5, Confidence: 0.5}) {
|
||||
t.Fatal("0.5 must hit at the restored default")
|
||||
}
|
||||
}
|
||||
+15
-11
@@ -62,17 +62,20 @@ type WebSearchOpts struct {
|
||||
|
||||
type Worker struct {
|
||||
findingRecorder FindingRecorder
|
||||
prov llm.Provider
|
||||
model string
|
||||
workDir string
|
||||
proxyAddr string
|
||||
proxyCACert string // recording proxy's CA cert path (for WebFetch HTTPS verify)
|
||||
factTraffic FactTrafficLookup // proxy captures for fact provenance (nil = activity-only)
|
||||
webSearch WebSearchOpts // web_search tool backend selection (off by default)
|
||||
tx *transcript.Store // raw LLM conversation persistence (nil = off)
|
||||
window int // context window in tokens (for compaction)
|
||||
windowFn func() int // optional dynamic task-chain minimum
|
||||
maxTurns int // max agent turns per run (0 = unlimited)
|
||||
// triage is the advisory decision-model client for closed-list judgements,
|
||||
// handed to the per-run ToolSet (see agent/triage.go). nil = off.
|
||||
triage TriageClient
|
||||
prov llm.Provider
|
||||
model string
|
||||
workDir string
|
||||
proxyAddr string
|
||||
proxyCACert string // recording proxy's CA cert path (for WebFetch HTTPS verify)
|
||||
factTraffic FactTrafficLookup // proxy captures for fact provenance (nil = activity-only)
|
||||
webSearch WebSearchOpts // web_search tool backend selection (off by default)
|
||||
tx *transcript.Store // raw LLM conversation persistence (nil = off)
|
||||
window int // context window in tokens (for compaction)
|
||||
windowFn func() int // optional dynamic task-chain minimum
|
||||
maxTurns int // max agent turns per run (0 = unlimited)
|
||||
// runTimeout is the wall-clock budget for the main exploration of one intent
|
||||
// (0 = unlimited). When it fires, the run is cut and a settlement round is
|
||||
// forced so already-identified facts get written back instead of being lost.
|
||||
@@ -532,6 +535,7 @@ func (w *Worker) ExecuteWithMessage(ctx context.Context, name string, taskID int
|
||||
func (w *Worker) execute(ctx context.Context, name string, taskID int64, as *db.AssetStore, ts *db.ExplorationStore, intent *db.Node, hooks harness.HookRunner, emit func(db.Activity), enr EnrichTrigger, notifyFinding func(int64, string), requestID, message string) (harness.TerminalReason, WriteCounts, error) {
|
||||
tsx := NewToolSet(ts, name)
|
||||
tsx.SetFindingRecorder(w.findingRecorder)
|
||||
tsx.SetTriageClient(w.triage)
|
||||
tsx.SetFactTraffic(w.factTraffic)
|
||||
tsx.SetTaskID(taskID)
|
||||
coverageEnabled := coverageOn(as, taskID)
|
||||
|
||||
+25
-13
@@ -165,10 +165,10 @@ func ParseAutoScopeLine(line string) (ParsedScope, error) {
|
||||
return ParseScopeInput(ScopeInput{Kind: "keyword", Value: raw})
|
||||
}
|
||||
|
||||
func scopeHostname(raw string) (string, error) {
|
||||
func scopeHostname(raw string) (host string, wildcard bool, err error) {
|
||||
candidate := strings.TrimSpace(raw)
|
||||
if candidate == "" {
|
||||
return "", fmt.Errorf("hostname is empty")
|
||||
return "", false, fmt.Errorf("hostname is empty")
|
||||
}
|
||||
if strings.HasPrefix(candidate, "//") {
|
||||
candidate = "http:" + candidate
|
||||
@@ -180,38 +180,42 @@ func scopeHostname(raw string) (string, error) {
|
||||
if err == nil {
|
||||
err = fmt.Errorf("missing hostname")
|
||||
}
|
||||
return "", err
|
||||
return "", false, err
|
||||
}
|
||||
host := strings.TrimSuffix(strings.TrimSpace(parsed.Hostname()), ".")
|
||||
host = strings.TrimSuffix(strings.TrimSpace(parsed.Hostname()), ".")
|
||||
host, wildcard = strings.CutPrefix(host, "*.")
|
||||
if host == "" {
|
||||
return "", fmt.Errorf("hostname is empty")
|
||||
return "", false, fmt.Errorf("hostname is empty")
|
||||
}
|
||||
if ip := net.ParseIP(host); ip != nil {
|
||||
return ip.String(), nil
|
||||
if wildcard {
|
||||
return "", false, fmt.Errorf("a wildcard needs a domain, not an IP")
|
||||
}
|
||||
return ip.String(), false, nil
|
||||
}
|
||||
host, err = idna.Lookup.ToASCII(host)
|
||||
if err != nil {
|
||||
return "", err
|
||||
return "", false, err
|
||||
}
|
||||
host = strings.ToLower(host)
|
||||
if len(host) > 253 {
|
||||
return "", fmt.Errorf("domain exceeds 253 characters")
|
||||
return "", false, fmt.Errorf("domain exceeds 253 characters")
|
||||
}
|
||||
labels := strings.Split(host, ".")
|
||||
if len(labels) < 2 {
|
||||
return "", fmt.Errorf("domain needs at least two labels")
|
||||
return "", false, fmt.Errorf("domain needs at least two labels")
|
||||
}
|
||||
for _, label := range labels {
|
||||
if label == "" || len(label) > 63 || label[0] == '-' || label[len(label)-1] == '-' {
|
||||
return "", fmt.Errorf("invalid domain label")
|
||||
return "", false, fmt.Errorf("invalid domain label")
|
||||
}
|
||||
for _, r := range label {
|
||||
if !((r >= 'a' && r <= 'z') || (r >= '0' && r <= '9') || r == '-') {
|
||||
return "", fmt.Errorf("domain contains invalid characters")
|
||||
return "", false, fmt.Errorf("domain contains invalid characters")
|
||||
}
|
||||
}
|
||||
}
|
||||
return host, nil
|
||||
return host, wildcard, nil
|
||||
}
|
||||
|
||||
// ParseScopeLine classifies and validates one scope line (root domain / IP /
|
||||
@@ -245,10 +249,18 @@ func ParseScopeLine(line string) (ParsedScope, error) {
|
||||
}
|
||||
return r, nil
|
||||
}
|
||||
host, err := scopeHostname(raw)
|
||||
host, wildcard, err := scopeHostname(raw)
|
||||
if err != nil {
|
||||
return r, fmt.Errorf("not recognizable as a valid domain/IP/CIDR: %s", raw)
|
||||
}
|
||||
// "*.example.com" is how bug bounty programs write a domain and its
|
||||
// subdomains, which is what a domain rule on example.com covers (assets match
|
||||
// on their registrable domain). A deeper wildcard has no such rule yet.
|
||||
if wildcard {
|
||||
if root, err := publicsuffix.EffectiveTLDPlusOne(host); err != nil || root != host {
|
||||
return r, fmt.Errorf("a wildcard is only supported on a registrable domain such as *.example.com: %s", raw)
|
||||
}
|
||||
}
|
||||
if ip := net.ParseIP(host); ip != nil {
|
||||
r.Kind = "ip"
|
||||
if ip.To4() != nil {
|
||||
|
||||
@@ -22,6 +22,14 @@ func TestParseScopeLine(t *testing.T) {
|
||||
{"co.uk", "", true}, // bare public suffix
|
||||
{"not a host", "", true},
|
||||
{"1.2.3.1-1.2.3.9", "", true}, // ranges must be CIDR
|
||||
{"*.example.com", "domain", false},
|
||||
{"https://*.example.co.uk/path", "domain", false},
|
||||
{"*.api.example.com", "", true}, // no rule covers only a subdomain's subdomains
|
||||
{"*.co.uk", "", true},
|
||||
{"*.com", "", true},
|
||||
{"*.1.2.3.4", "", true},
|
||||
{"api.*.example.com", "", true},
|
||||
{"*example.com", "", true},
|
||||
}
|
||||
for _, c := range cases {
|
||||
r, err := ParseScopeLine(c.in)
|
||||
@@ -77,6 +85,11 @@ func TestParseAutoScopeLine(t *testing.T) {
|
||||
{name: "overbroad cidr", input: "10.0.0.0/8", wantErr: true},
|
||||
{name: "bare suffix", input: "co.uk", wantErr: true},
|
||||
{name: "empty domain label", input: "foo..example.com", wantErr: true},
|
||||
{name: "wildcard domain", input: "*.example.com", kind: "domain", normalized: "example.com"},
|
||||
{name: "wildcard url", input: "https://*.Example.com:8443/", kind: "domain", normalized: "example.com"},
|
||||
{name: "wildcard idn", input: "*.bücher.de", kind: "domain", normalized: "xn--bcher-kva.de"},
|
||||
{name: "wildcard subdomain", input: "*.api.example.com", wantErr: true},
|
||||
{name: "wildcard suffix", input: "*.co.uk", wantErr: true},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
@@ -426,3 +439,58 @@ func TestCompanyScopeAttribution(t *testing.T) {
|
||||
}
|
||||
mustNil(ipOutID, "out-of-CIDR ip")
|
||||
}
|
||||
|
||||
// A "*.example.com" line is stored as the example.com domain rule, so it
|
||||
// attributes the subdomains just as a plain example.com line does.
|
||||
func TestCompanyScopeWildcardAttribution(t *testing.T) {
|
||||
d, err := Open(testDSN(t))
|
||||
if err != nil {
|
||||
SkipPGUnavailable(t, err)
|
||||
}
|
||||
as := d.Assets()
|
||||
cs := d.Companies()
|
||||
|
||||
var startMax int64
|
||||
if err := d.QueryRow(`SELECT COALESCE(MAX(id),0) FROM assets`).Scan(&startMax); err != nil {
|
||||
d.Close()
|
||||
t.Fatalf("startMax: %v", err)
|
||||
}
|
||||
var cid int64
|
||||
t.Cleanup(func() {
|
||||
defer d.Close()
|
||||
if _, err := d.Exec(`DELETE FROM assets WHERE id > $1`, startMax); err != nil {
|
||||
t.Errorf("cleanup assets: %v", err)
|
||||
}
|
||||
if cid != 0 {
|
||||
if _, err := d.Exec(`DELETE FROM companies WHERE id = $1`, cid); err != nil {
|
||||
t.Errorf("cleanup company %d: %v", cid, err)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
uniq := fmt.Sprintf("%d%d", time.Now().UnixNano(), rand.Uint32())
|
||||
root := fmt.Sprintf("wildcardtest%s.com", uniq)
|
||||
cid, _, err = cs.UpsertCompany(fmt.Sprintf("WildcardCo %s", uniq), "")
|
||||
if err != nil {
|
||||
t.Fatalf("UpsertCompany: %v", err)
|
||||
}
|
||||
cs.AddScope(cid, []string{"*." + root}, "unit test")
|
||||
|
||||
var domain string
|
||||
if err := d.QueryRow(`SELECT domain FROM company_scope WHERE company_id = $1 AND kind = 'domain'`, cid).Scan(&domain); err != nil {
|
||||
t.Fatalf("read scope: %v", err)
|
||||
}
|
||||
if domain != root {
|
||||
t.Fatalf("stored domain = %q, want %q", domain, root)
|
||||
}
|
||||
|
||||
id, err := as.UpsertSubdomain(UpsertSubdomainReq{Domain: "api." + root})
|
||||
if err != nil {
|
||||
t.Fatalf("UpsertSubdomain: %v", err)
|
||||
}
|
||||
var got *int64
|
||||
d.QueryRow(`SELECT company_id FROM assets WHERE id = $1`, id).Scan(&got)
|
||||
if got == nil || *got != cid {
|
||||
t.Fatalf("api.%s company_id = %v, want %d", root, got, cid)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1211,6 +1211,60 @@ WHERE e.exploration_id=$1 AND e.rel=$2 AND n.kind='finding'`, s.expID, RelYields
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// FactOnlyIntent is one intent that yielded facts and no finding — the measurable
|
||||
// form of «proved but not registered».
|
||||
type FactOnlyIntent struct {
|
||||
IntentID int64
|
||||
Summary string
|
||||
Facts int
|
||||
}
|
||||
|
||||
// FactOnlyIntents returns the intents of this exploration that yielded at least one
|
||||
// fact node and zero finding nodes, newest first, capped at limit.
|
||||
//
|
||||
// Why it exists: on the run record, three runs out of twelve had EVERY
|
||||
// fact-producing intent register nothing (3/3, 3/3, 2/2 — llm/agent logs of the
|
||||
// 2026-11-22 stand). Facts were proven, findings never reached the registry, and
|
||||
// nothing in the graph connected the two, so the planner could not notice.
|
||||
// The counter is deliberately about the intent, not the fact: a fact carries no
|
||||
// "this is a defect" flag, while an intent that produced facts has finished work
|
||||
// whose result the planner can judge.
|
||||
//
|
||||
// limit<=0 falls back to 10: a planner round acts on a handful, and the whole
|
||||
// point is a nudge, not an inventory.
|
||||
func (s *ExplorationStore) FactOnlyIntents(limit int) ([]FactOnlyIntent, error) {
|
||||
if limit <= 0 {
|
||||
limit = 10
|
||||
}
|
||||
rows, err := s.db.Query(`SELECT i.id, COALESCE(i.payload->>'summary',''), count(*)
|
||||
FROM exploration_edges e
|
||||
JOIN exploration_nodes i ON i.id=e.src_id AND i.exploration_id=e.exploration_id
|
||||
JOIN exploration_nodes d ON d.id=e.dst_id AND d.exploration_id=e.exploration_id
|
||||
WHERE e.exploration_id=$1 AND e.rel=$2 AND d.kind=$3
|
||||
AND i.state IN ('done','blocked','exhausted','stopped')
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM exploration_edges e2
|
||||
JOIN exploration_nodes f ON f.id=e2.dst_id AND f.exploration_id=e2.exploration_id
|
||||
WHERE e2.exploration_id=e.exploration_id AND e2.src_id=e.src_id
|
||||
AND e2.rel=$2 AND f.kind='finding')
|
||||
GROUP BY i.id, 2
|
||||
ORDER BY i.id DESC
|
||||
LIMIT $4`, s.expID, RelYields, KindFact, limit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var out []FactOnlyIntent
|
||||
for rows.Next() {
|
||||
var r FactOnlyIntent
|
||||
if err := rows.Scan(&r.IntentID, &r.Summary, &r.Facts); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, r)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// FindingIntentsTerminal is the inherited-history variant: it returns finding
|
||||
// lineage only when the producing intent has reached an immutable terminal
|
||||
// state. This keeps a source task's live worker topology private.
|
||||
|
||||
@@ -0,0 +1,140 @@
|
||||
package db
|
||||
|
||||
import "testing"
|
||||
|
||||
// "Proved but not registered", in measurable form: an intent that yielded facts and
|
||||
// no finding. The test holds both cases at once, otherwise the gate is green on an
|
||||
// empty set: intent A (fact, no finding) must be returned, intent B (fact + finding)
|
||||
// must not.
|
||||
func TestFactOnlyIntents(t *testing.T) {
|
||||
d, err := Open(testDSN(t))
|
||||
if err != nil {
|
||||
SkipPGUnavailable(t, err)
|
||||
}
|
||||
t.Cleanup(func() { d.Close() })
|
||||
|
||||
expID, err := d.CreateExploration("fact only intents", "fact only intents")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { cleanupExec(t, d, `DELETE FROM explorations WHERE id=$1`, expID) })
|
||||
store := d.Exploration(expID)
|
||||
|
||||
// A: fact present, no finding — "proved, not registered".
|
||||
intentA, err := store.AddIntent(map[string]any{"summary": "proved X, never registered"}, 1, nil, "planner")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// Only finished intents count: the state filter keeps A (done) and drops open ones.
|
||||
if err := store.SetIntentState(intentA, "done"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
factA, err := store.AddNode(KindFact, map[string]any{"summary": "X is injectable"}, 1, "confirmed", "worker", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := store.Link(intentA, RelYields, factA); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// B: fact and finding — must not be returned.
|
||||
intentB, err := store.AddIntent(map[string]any{"summary": "proved Y and registered"}, 1, nil, "planner")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
factB, err := store.AddNode(KindFact, map[string]any{"summary": "Y is injectable"}, 1, "confirmed", "worker", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
findingB, err := store.AddNode(KindFinding, map[string]any{"summary": "Y finding"}, 1, "confirmed", "worker", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := store.Link(intentB, RelYields, factB); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := store.Link(intentB, RelYields, findingB); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// C: intent with no facts at all — must not be returned either.
|
||||
intentC, err := store.AddIntent(map[string]any{"summary": "nothing yet"}, 1, nil, "planner")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_ = intentC
|
||||
|
||||
got, err := store.FactOnlyIntents(10)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(got) != 1 {
|
||||
t.Fatalf("FactOnlyIntents returned %d intents, want 1 (only the fact-without-finding one): %+v", len(got), got)
|
||||
}
|
||||
if got[0].IntentID != intentA {
|
||||
t.Fatalf("FactOnlyIntents picked intent %d, want %d", got[0].IntentID, intentA)
|
||||
}
|
||||
if got[0].Facts != 1 {
|
||||
t.Fatalf("FactOnlyIntents facts = %d, want 1", got[0].Facts)
|
||||
}
|
||||
if got[0].Summary == "" {
|
||||
t.Fatal("FactOnlyIntents lost the intent summary — the planner cannot act on an id alone")
|
||||
}
|
||||
|
||||
// Default cap: limit<=0 must not return nothing.
|
||||
if many, err := store.FactOnlyIntents(0); err != nil || len(many) != 1 {
|
||||
t.Fatalf("FactOnlyIntents(0) = (%d, %v), want 1 row via the default cap", len(many), err)
|
||||
}
|
||||
}
|
||||
|
||||
// Only finished intents (done, blocked, exhausted, stopped) count. An intent that is
|
||||
// still open or running with a fact and no finding must not be reported as finished.
|
||||
func TestFactOnlyIntentsStates(t *testing.T) {
|
||||
d, err := Open(testDSN(t))
|
||||
if err != nil {
|
||||
SkipPGUnavailable(t, err)
|
||||
}
|
||||
t.Cleanup(func() { d.Close() })
|
||||
|
||||
expID, err := d.CreateExploration("fact only states", "fact only states")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { cleanupExec(t, d, `DELETE FROM explorations WHERE id=$1`, expID) })
|
||||
store := d.Exploration(expID)
|
||||
|
||||
states := []string{"open", "running", "done", "blocked", "exhausted", "stopped"}
|
||||
want := map[int64]bool{}
|
||||
for _, st := range states {
|
||||
id, err := store.AddIntent(map[string]any{"summary": "state " + st}, 1, nil, "planner")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := store.SetIntentState(id, st); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
fact, err := store.AddNode(KindFact, map[string]any{"summary": "fact for " + st}, 1, "confirmed", "worker", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := store.Link(id, RelYields, fact); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if st == "done" || st == "blocked" || st == "exhausted" || st == "stopped" {
|
||||
want[id] = true
|
||||
}
|
||||
}
|
||||
|
||||
got, err := store.FactOnlyIntents(0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(got) != len(want) {
|
||||
t.Fatalf("FactOnlyIntents returned %d intents, want %d (terminal states only): %+v", len(got), len(want), got)
|
||||
}
|
||||
for _, g := range got {
|
||||
if !want[g.IntentID] {
|
||||
t.Fatalf("FactOnlyIntents returned intent %d in a non-terminal state", g.IntentID)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"strings"
|
||||
)
|
||||
|
||||
// prefixedNodeCols mirrors nodeCols with an alias, for queries that join
|
||||
// exploration_nodes with another table carrying an `id` of its own.
|
||||
const prefixedNodeCols = `n.id, n.kind, n.payload, n.priority, n.state, ` +
|
||||
`COALESCE(n.origin,''), COALESCE(n.owner,''), COALESCE(n.blocked_reason,''), ` +
|
||||
`COALESCE(n.delete_reason,''), n.created_at`
|
||||
|
||||
// FindingsSharingAssets returns finding nodes from OTHER tasks that are anchored to
|
||||
// at least one of assetIDs.
|
||||
//
|
||||
// ListByKindWithSources covers the task's own findings plus its directly related
|
||||
// tasks (task_relations). Two tasks run independently against the same target are
|
||||
// NOT related, so a defect registered in one and re-registered in the other is
|
||||
// invisible to a dedup check built only on that pool — measured live: three such
|
||||
// duplicates across two tasks, all answered "distinct" because the question never
|
||||
// offered them. Assets are the join that catches them.
|
||||
//
|
||||
// Returned nodes carry Inherited=true and SourceTaskID so callers can mark them as
|
||||
// belonging to another task (read-only for extension).
|
||||
func (s *ExplorationStore) FindingsSharingAssets(assetIDs []int64, excludeTask int64, limit int) ([]*Node, error) {
|
||||
if len(assetIDs) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
if limit <= 0 {
|
||||
// 50: самый широкий наблюдённый пул по ассету — 31 находка на ассете [1]
|
||||
// (53 находки в графе, 2026-11-22), запас 1.6x; вызывающий всё равно отбирает
|
||||
// из результата не больше triageMaxExisting, так что 50 — верхняя граница запроса.
|
||||
// при превышении: хвост по f.id DESC отбрасывается, вопрос всё равно ограничен.
|
||||
limit = 50
|
||||
}
|
||||
// One containment per asset, OR-joined: asset_ids is a jsonb array and the GIN
|
||||
// index (jsonb_path_ops) serves @>, not a list-membership operator.
|
||||
ors := make([]string, 0, len(assetIDs))
|
||||
args := []any{excludeTask}
|
||||
for _, id := range assetIDs {
|
||||
args = append(args, "["+itoa(id)+"]")
|
||||
ors = append(ors, "f.asset_ids @> $"+itoa(int64(len(args)))+"::jsonb")
|
||||
}
|
||||
args = append(args, limit)
|
||||
q := `SELECT ` + prefixedNodeCols + `, f.id, f.task_id
|
||||
FROM findings f
|
||||
JOIN exploration_nodes n ON n.id = f.node_id
|
||||
WHERE f.task_id <> $1 AND (` + strings.Join(ors, " OR ") + `)
|
||||
ORDER BY f.id DESC LIMIT $` + itoa(int64(len(args)))
|
||||
rows, err := s.db.Query(q, args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var out []*Node
|
||||
for rows.Next() {
|
||||
var n Node
|
||||
var payload []byte
|
||||
var findingID, taskID int64
|
||||
if err := rows.Scan(&n.ID, &n.Kind, &payload, &n.Priority, &n.State, &n.Origin, &n.Owner,
|
||||
&n.BlockedReason, &n.DeleteReason, &n.CreatedAt, &findingID, &taskID); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
n.Payload = payload
|
||||
n.FindingID = findingID
|
||||
n.SourceTaskID = taskID
|
||||
n.Inherited = true
|
||||
out = append(out, &n)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
+3
-2
@@ -5,8 +5,9 @@ import (
|
||||
"strings"
|
||||
)
|
||||
|
||||
// LLMContext is one opt-in context-size telemetry row written when
|
||||
// ARTEX_CONTEXT_TELEMETRY=1. It records only byte sizes, counts, token usage,
|
||||
// LLMContext is one context-size telemetry row, written on every model call while
|
||||
// telemetry is on (the default; ARTEX_CONTEXT_TELEMETRY=0|false|off|no turns it off).
|
||||
// It records only byte sizes, counts, token usage,
|
||||
// and call metadata — never any prompt, tool, or message content.
|
||||
type LLMContext struct {
|
||||
TaskID string `json:"task_id"`
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# LLM Context Size Telemetry (P3.5 Phase A)
|
||||
|
||||
`ARTEX_CONTEXT_TELEMETRY=1` enables opt-in, size-only per-call telemetry for every `llmrec` `Stream` and `Complete` call. It is **disabled by default**: when off, no request sizing runs and no rows are written to PostgreSQL.
|
||||
Size-only per-call telemetry runs for every `llmrec` `Stream` and `Complete` call. It is **on by default**; `ARTEX_CONTEXT_TELEMETRY=0|false|off|no` disables it explicitly, and then no request sizing runs and no rows are written to PostgreSQL.
|
||||
|
||||
This phase measures context composition without changing any prompt, compaction policy, or model behavior, so Phases B (`ARTEX_BOUNDED_CONTEXT`) and C (`ARTEX_CACHE_PREFIX` / `ARTEX_COMPACTION_MEMO`) can be evaluated against real numbers first.
|
||||
|
||||
@@ -10,13 +10,13 @@ This phase measures context composition without changing any prompt, compaction
|
||||
|
||||
| Environment variable | Values | Default |
|
||||
|---|---|---|
|
||||
| `ARTEX_CONTEXT_TELEMETRY` | `1`, `true`, `on`, `yes` (case-insensitive) | off |
|
||||
| `ARTEX_CONTEXT_TELEMETRY` | `0`, `false`, `off`, `no` disable it (case-insensitive); anything else, or unset, keeps it on | on |
|
||||
|
||||
Telemetry runs independently of `llm_record` (`recordBodies`): enabling `ARTEX_CONTEXT_TELEMETRY=1` works even when full request/response body recording is disabled, and stores **no prompt, tool, or message content** — only byte lengths, counts, token usage, and metadata.
|
||||
Telemetry runs independently of `llm_record` (`recordBodies`): it stays on even when full request/response body recording is disabled, and stores **no prompt, tool, or message content** — only byte lengths, counts, token usage, and metadata.
|
||||
|
||||
### Stopping, retention, and write cost
|
||||
|
||||
When `ARTEX_CONTEXT_TELEMETRY=1` is active, each LLM call incurs one lightweight `INSERT` into `llm_context` (~200 bytes/row plus index entries, no bodies), so the table grows by one row per completion call. Unset `ARTEX_CONTEXT_TELEMETRY` (and restart) once the measurement campaign is finished to stop all writes and sizing work, or purge old rows periodically:
|
||||
While telemetry is on (the default), each LLM call incurs one lightweight `INSERT` into `llm_context` (~200 bytes/row plus index entries, no bodies), so the table grows by one row per completion call. Set `ARTEX_CONTEXT_TELEMETRY=0` (and restart) once the measurement campaign is finished to stop all writes and sizing work, or purge old rows periodically:
|
||||
|
||||
```sql
|
||||
DELETE FROM llm_context WHERE ts < now() - interval '30 days';
|
||||
|
||||
+6
-6
@@ -13,7 +13,7 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"log/slog"
|
||||
"math/rand/v2"
|
||||
"net"
|
||||
"net/http"
|
||||
@@ -68,7 +68,7 @@ func ProfileByName(name string) (p Profile, ok bool) {
|
||||
return Profile{Name: "off"}, false
|
||||
}
|
||||
if ua := strings.TrimSpace(os.Getenv("ARTEX_TARGET_USER_AGENT")); strings.ContainsFunc(ua, unicode.IsControl) {
|
||||
log.Printf("[egress] ARTEX_TARGET_USER_AGENT contains a control character; ignored")
|
||||
slog.Warn("[egress] ARTEX_TARGET_USER_AGENT contains a control character, ignored")
|
||||
} else {
|
||||
p.UserAgent = ua
|
||||
}
|
||||
@@ -81,7 +81,7 @@ func ProfileFromEnv() Profile {
|
||||
name := strings.TrimSpace(os.Getenv("ARTEX_NOISE_PROFILE"))
|
||||
p, ok := ProfileByName(name)
|
||||
if !ok && name != "" {
|
||||
log.Printf("[egress] ARTEX_NOISE_PROFILE=%q is not off, quiet, balanced or aggressive; using off", name)
|
||||
slog.Warn("[egress] unknown noise profile, using off", "ARTEX_NOISE_PROFILE", name)
|
||||
}
|
||||
return p
|
||||
}
|
||||
@@ -105,7 +105,7 @@ func Current() *Governor {
|
||||
initCurrent.Do(func() {
|
||||
g := New(ProfileFromEnv())
|
||||
if current.CompareAndSwap(nil, g) {
|
||||
log.Printf("[egress] noise profile: %s", g.p.Name)
|
||||
slog.Info("[egress] noise profile active", "profile", g.p.Name)
|
||||
}
|
||||
startReporter()
|
||||
})
|
||||
@@ -120,7 +120,7 @@ func CurrentProfile() Profile { return Current().p }
|
||||
func SetProfile(p Profile) *Governor {
|
||||
g := New(p)
|
||||
current.Store(g)
|
||||
log.Printf("[egress] noise profile: %s", g.p.Name)
|
||||
slog.Info("[egress] noise profile active", "profile", g.p.Name)
|
||||
startReporter()
|
||||
return g
|
||||
}
|
||||
@@ -135,7 +135,7 @@ func startReporter() {
|
||||
defer t.Stop()
|
||||
for range t.C {
|
||||
for _, l := range Current().report() {
|
||||
log.Print(l)
|
||||
slog.Info(l)
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
+3
-3
@@ -11,7 +11,7 @@ import (
|
||||
"crypto/tls"
|
||||
"html"
|
||||
"io"
|
||||
"log"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"regexp"
|
||||
@@ -75,7 +75,7 @@ func New(as *db.AssetStore, proxy func() string, workers int) *Engine {
|
||||
Timeout: 4 * time.Second,
|
||||
})
|
||||
if err != nil {
|
||||
log.Printf("[enrich] dnsx init failed, DNS resolution disabled: %v", err)
|
||||
slog.Warn("[enrich] dnsx init failed, DNS resolution disabled", "err", err)
|
||||
resolv = nil
|
||||
}
|
||||
e := &Engine{
|
||||
@@ -146,7 +146,7 @@ func (e *Engine) enqueue(j job) {
|
||||
select {
|
||||
case e.jobs <- j:
|
||||
default: // queue full → drop (best-effort enrichment)
|
||||
log.Printf("[enrich] queue full, dropping job kind=%d id=%d", j.kind, j.id)
|
||||
slog.Warn("[enrich] enrich queue full, dropping job", "kind", j.kind, "id", j.id)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+2
-2
@@ -10,7 +10,7 @@ import (
|
||||
"fmt"
|
||||
"io"
|
||||
"io/fs"
|
||||
"log"
|
||||
"log/slog"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
@@ -443,7 +443,7 @@ func (s *Store) RunGC(ctx context.Context) {
|
||||
return
|
||||
case now := <-timer.C:
|
||||
if err := s.Collect(ctx, now); err != nil && !errors.Is(err, context.Canceled) {
|
||||
log.Printf("[evidence] cleanup failed: %v", err)
|
||||
slog.Error("[evidence] evidence cleanup failed", "err", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+18
@@ -82,15 +82,33 @@ install_docker_linux(){
|
||||
sudo apt-get install -y "$p" && break
|
||||
fi
|
||||
done
|
||||
# docker.io only suggests buildx on some releases, and the image build needs it.
|
||||
for p in docker-buildx-plugin docker-buildx; do
|
||||
if apt-cache madison "$p" 2>/dev/null | grep -q .; then
|
||||
sudo apt-get install -y "$p" && break
|
||||
fi
|
||||
done
|
||||
# Kali (and some others) don't start services on package install.
|
||||
if command -v systemctl >/dev/null 2>&1; then
|
||||
sudo systemctl enable --now docker || true
|
||||
fi
|
||||
}
|
||||
|
||||
# The Dockerfile uses --platform=$BUILDPLATFORM, which needs BuildKit. Without the
|
||||
# buildx plugin Compose only warns, falls back to the legacy builder and fails on
|
||||
# the first FROM with 'failed to parse platform'.
|
||||
ensure_buildx(){
|
||||
docker buildx version >/dev/null 2>&1 && return
|
||||
case "$(uname -s)" in
|
||||
Darwin) die "docker buildx not detected; the image build needs it. Docker Desktop includes it; with Homebrew's docker CLI (e.g. Colima) run 'brew install docker-buildx' and register the plugin as its caveats describe" ;;
|
||||
*) die "docker buildx not detected; the image build needs it. Install docker-buildx-plugin (Docker's repo) or docker-buildx (distro repo) and retry" ;;
|
||||
esac
|
||||
}
|
||||
|
||||
# ── 1) All-Docker ───────────────────────────────
|
||||
install_docker(){
|
||||
ensure_docker
|
||||
ensure_buildx
|
||||
if [ ! -f .env ]; then
|
||||
cp .env.example .env 2>/dev/null || true
|
||||
local pw key
|
||||
|
||||
@@ -10,19 +10,24 @@ import (
|
||||
"github.com/Autumn-27/norma/llm"
|
||||
)
|
||||
|
||||
// ContextTelemetryEnv is the opt-in environment flag enabling per-call context
|
||||
// size telemetry into llm_context. Off by default: when unset/false, no sizing
|
||||
// work runs and no rows are written.
|
||||
// ContextTelemetryEnv switches per-call context size telemetry into llm_context.
|
||||
//
|
||||
// ON by default. Measurement: on the test bench, 15 runs left llm_context EMPTY
|
||||
// (0 rows) because the flag was off by default, so the worker's context size was
|
||||
// discussed from the task's total tokens, not from a breakdown (2026-11-22).
|
||||
// Cost: one row per model call plus length counts; no content is stored (up to about
|
||||
// 300 calls per run in the bench logs, so up to about 300 rows).
|
||||
// Explicit off switch: ARTEX_CONTEXT_TELEMETRY=0|false|off|no.
|
||||
const ContextTelemetryEnv = "ARTEX_CONTEXT_TELEMETRY"
|
||||
|
||||
// ContextTelemetryEnabled reports whether ARTEX_CONTEXT_TELEMETRY is enabled
|
||||
// (1, true, on, yes; case-insensitive). Default is false.
|
||||
// ContextTelemetryEnabled reports whether context telemetry is on. Default true;
|
||||
// only an explicit falsy value (0, false, off, no; case-insensitive) turns it off.
|
||||
func ContextTelemetryEnabled() bool {
|
||||
switch strings.ToLower(strings.TrimSpace(os.Getenv(ContextTelemetryEnv))) {
|
||||
case "1", "true", "on", "yes":
|
||||
return true
|
||||
case "0", "false", "off", "no":
|
||||
return false
|
||||
}
|
||||
return false
|
||||
return true
|
||||
}
|
||||
|
||||
// ContextMetrics holds size-only measurements of an assembled CompletionRequest
|
||||
|
||||
@@ -233,11 +233,21 @@ func TestContextTelemetryFlagOffAndOnPostgres(t *testing.T) {
|
||||
wantMetrics := MeasureContext(req)
|
||||
wantUsage := llm.Usage{InputTokens: 1200, OutputTokens: 150, CacheReadTokens: 800, CacheWriteTokens: 100}
|
||||
|
||||
// 1. Flag OFF (default): zero rows in llm_context on both Stream and Complete,
|
||||
// identical behavior regardless of recordBodies.
|
||||
// 0. Default is ON: unset means enabled, only an explicit falsy value disables.
|
||||
t.Setenv(ContextTelemetryEnv, "")
|
||||
if !ContextTelemetryEnabled() {
|
||||
t.Fatal("expected telemetry enabled by default when env unset")
|
||||
}
|
||||
t.Setenv(ContextTelemetryEnv, "off")
|
||||
if ContextTelemetryEnabled() {
|
||||
t.Fatal("expected telemetry disabled when env unset")
|
||||
t.Fatal("expected telemetry disabled when ARTEX_CONTEXT_TELEMETRY=off")
|
||||
}
|
||||
|
||||
// 1. Flag OFF explicitly: zero rows in llm_context on both Stream and Complete,
|
||||
// identical behavior regardless of recordBodies.
|
||||
t.Setenv(ContextTelemetryEnv, "0")
|
||||
if ContextTelemetryEnabled() {
|
||||
t.Fatal("expected telemetry disabled when ARTEX_CONTEXT_TELEMETRY=0")
|
||||
}
|
||||
recOff := Wrap(syntheticTelemetryProvider{usage: wantUsage}, pg, "claude-test", "prof-a", "", "", func() bool { return false })
|
||||
ctxOff := transcript.WithSessionID(WithTaskID(context.Background(), taskOff), "exp1-worker-i1")
|
||||
|
||||
+1
-1
@@ -211,7 +211,7 @@ func (r *Recorder) Stream(ctx context.Context, req llm.CompletionRequest) iter.S
|
||||
}
|
||||
// Lightweight metering row — always written.
|
||||
r.recordUsage(ctx, taskID, expID, worker, usage, int(time.Since(start).Milliseconds()), status)
|
||||
// Opt-in context size telemetry — independent of recordBodies.
|
||||
// Context size telemetry (on by default) — independent of recordBodies.
|
||||
if collectContext {
|
||||
r.recordContext(taskID, worker, ctxMetrics, usage, status)
|
||||
}
|
||||
|
||||
+62
-2
@@ -2,12 +2,14 @@ package notify
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"crypto/tls"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"fmt"
|
||||
"mime"
|
||||
"net"
|
||||
"net/mail"
|
||||
"net/smtp"
|
||||
"strconv"
|
||||
"strings"
|
||||
@@ -57,6 +59,14 @@ func (emailChannel) Validate(cfg map[string]any) error {
|
||||
if len(cfgStrings(cfg, "to")) == 0 {
|
||||
return errors.New("at least one recipient address is required")
|
||||
}
|
||||
for _, rcpt := range cfgStrings(cfg, "to") {
|
||||
if hasLineBreak(rcpt) {
|
||||
return errors.New("recipient address must not contain line breaks")
|
||||
}
|
||||
}
|
||||
if _, err := senderAddress(cfgString(cfg, "from")); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -72,6 +82,10 @@ func (c emailChannel) Send(ctx context.Context, cfg map[string]any, m Message) (
|
||||
password := cfgString(cfg, "password")
|
||||
implicitTLS := cfgBool(cfg, "tls")
|
||||
|
||||
sender, err := senderAddress(from)
|
||||
if err != nil {
|
||||
return 0, Permanent(err)
|
||||
}
|
||||
msg, err := buildEmailMessage(from, to, m)
|
||||
if err != nil {
|
||||
return 0, Permanent(err)
|
||||
@@ -106,8 +120,9 @@ func (c emailChannel) Send(ctx context.Context, cfg map[string]any, m Message) (
|
||||
return 0, Permanent(fmt.Errorf("SMTP authentication failed: %w", err))
|
||||
}
|
||||
}
|
||||
if err := client.Mail(from); err != nil {
|
||||
return 0, smtpStageError(fmt.Sprintf("sender %s rejected", from), err)
|
||||
// The envelope sender is the bare address; the display name stays in the header.
|
||||
if err := client.Mail(sender.Address); err != nil {
|
||||
return 0, smtpStageError(fmt.Sprintf("sender %s rejected", sender.Address), err)
|
||||
}
|
||||
for _, rcpt := range to {
|
||||
if err := client.Rcpt(rcpt); err != nil {
|
||||
@@ -217,9 +232,22 @@ func smtpReplyCode(text string) int {
|
||||
// over-long lines; second, base64 never produces a line starting with ".",
|
||||
// avoiding SMTP dot-stuffing entirely.
|
||||
func buildEmailMessage(from string, to []string, m Message) (string, error) {
|
||||
// From and To go into header lines: a CR or LF would start a new header.
|
||||
if hasLineBreak(from) {
|
||||
return "", errors.New("sender address must not contain line breaks")
|
||||
}
|
||||
for _, rcpt := range to {
|
||||
if hasLineBreak(rcpt) {
|
||||
return "", errors.New("recipient address must not contain line breaks")
|
||||
}
|
||||
}
|
||||
var b strings.Builder
|
||||
fmt.Fprintf(&b, "From: %s\r\n", from)
|
||||
fmt.Fprintf(&b, "To: %s\r\n", strings.Join(to, ", "))
|
||||
// RFC 5322 requires Date and recommends Message-ID. Not every submission
|
||||
// server adds them, and spam filters penalize mail without them.
|
||||
fmt.Fprintf(&b, "Date: %s\r\n", time.Now().Format(time.RFC1123Z))
|
||||
fmt.Fprintf(&b, "Message-ID: <%s@%s>\r\n", rand.Text(), messageIDDomain(from))
|
||||
// A non-ASCII subject must be RFC 2047 encoded, otherwise clients display it
|
||||
// as mojibake.
|
||||
fmt.Fprintf(&b, "Subject: %s\r\n", mime.QEncoding.Encode("utf-8", htmlTitle(m)))
|
||||
@@ -237,3 +265,35 @@ func buildEmailMessage(from string, to []string, m Message) (string, error) {
|
||||
b.WriteString(encoded + "\r\n")
|
||||
return b.String(), nil
|
||||
}
|
||||
|
||||
// senderAddress parses the configured sender with net/mail, so a display name and
|
||||
// comments are accepted and the bare address is what gets used. A line break is
|
||||
// refused before parsing: the value lands in header lines.
|
||||
func senderAddress(from string) (*mail.Address, error) {
|
||||
if hasLineBreak(from) {
|
||||
return nil, errors.New("sender address must not contain line breaks")
|
||||
}
|
||||
addr, err := mail.ParseAddress(from)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("invalid sender address: %w", err)
|
||||
}
|
||||
return addr, nil
|
||||
}
|
||||
|
||||
// hasLineBreak reports whether s contains CR or LF.
|
||||
func hasLineBreak(s string) bool {
|
||||
return strings.ContainsAny(s, "\r\n")
|
||||
}
|
||||
|
||||
// messageIDDomain is the right-hand side of a Message-ID: the domain of the parsed
|
||||
// sender address, or "localhost" when there is none (or the sender does not parse).
|
||||
func messageIDDomain(from string) string {
|
||||
addr, err := senderAddress(from)
|
||||
if err != nil {
|
||||
return "localhost"
|
||||
}
|
||||
if i := strings.LastIndex(addr.Address, "@"); i >= 0 && i+1 < len(addr.Address) {
|
||||
return addr.Address[i+1:]
|
||||
}
|
||||
return "localhost"
|
||||
}
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
package notify
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestMessageIDDomainFromCommentedAddress(t *testing.T) {
|
||||
if got := messageIDDomain("Name <a@example.com> (comment)"); got != "example.com" {
|
||||
t.Fatalf("domain = %q, want example.com", got)
|
||||
}
|
||||
if got := messageIDDomain("ops@example.org"); got != "example.org" {
|
||||
t.Fatalf("domain = %q, want example.org", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMessageIDDomainFallsBackToLocalhost(t *testing.T) {
|
||||
for _, from := range []string{"no-at-sign", "a@", "Name <a@>", ""} {
|
||||
if got := messageIDDomain(from); got != "localhost" {
|
||||
t.Fatalf("messageIDDomain(%q) = %q, want localhost", from, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildEmailMessageRefusesLineBreaksInHeaders(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
from string
|
||||
to []string
|
||||
}{
|
||||
{"CRLF in sender", "a@example.com\r\nBcc: victim@example.net", []string{"b@example.org"}},
|
||||
{"LF in sender", "a@example.com\nBcc: victim@example.net", []string{"b@example.org"}},
|
||||
{"CRLF in recipient", "a@example.com", []string{"b@example.org\r\nBcc: victim@example.net"}},
|
||||
}
|
||||
for _, c := range cases {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
msg, err := buildEmailMessage(c.from, c.to, Message{})
|
||||
if err == nil {
|
||||
t.Fatalf("expected an error, got message:\n%s", msg)
|
||||
}
|
||||
if strings.Contains(msg, "Bcc:") {
|
||||
t.Fatal("no header may be produced from an injected value")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSenderAddressValidation(t *testing.T) {
|
||||
if _, err := senderAddress("a@example.com\r\nX: y"); err == nil {
|
||||
t.Fatal("CRLF sender must be refused")
|
||||
}
|
||||
if _, err := senderAddress("not an address"); err == nil {
|
||||
t.Fatal("unparseable sender must be refused")
|
||||
}
|
||||
addr, err := senderAddress("Name <a@example.com> (comment)")
|
||||
if err != nil {
|
||||
t.Fatalf("commented sender refused: %v", err)
|
||||
}
|
||||
if addr.Address != "a@example.com" {
|
||||
t.Fatalf("envelope address = %q, want a@example.com", addr.Address)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEmailValidateRejectsBadSenderAndRecipients(t *testing.T) {
|
||||
base := map[string]any{"host": "smtp.example.com", "port": 587, "to": []any{"b@example.org"}}
|
||||
ok := map[string]any{"host": "smtp.example.com", "port": 587, "from": "a@example.com", "to": []any{"b@example.org"}}
|
||||
if err := (emailChannel{}).Validate(ok); err != nil {
|
||||
t.Fatalf("valid config refused: %v", err)
|
||||
}
|
||||
if err := (emailChannel{}).Validate(base); err == nil {
|
||||
t.Fatal("empty sender must be refused")
|
||||
}
|
||||
bad := map[string]any{"host": "smtp.example.com", "port": 587, "from": "not an address", "to": []any{"b@example.org"}}
|
||||
if err := (emailChannel{}).Validate(bad); err == nil {
|
||||
t.Fatal("invalid sender must be refused")
|
||||
}
|
||||
crlf := map[string]any{"host": "smtp.example.com", "port": 587, "from": "a@example.com", "to": []any{"b@example.org\r\nX: y"}}
|
||||
if err := (emailChannel{}).Validate(crlf); err == nil {
|
||||
t.Fatal("CRLF recipient must be refused")
|
||||
}
|
||||
}
|
||||
@@ -5,9 +5,11 @@ import (
|
||||
"context"
|
||||
|
||||
"net"
|
||||
"net/mail"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// This file adds the protocol-level tests for the email channel. Before it,
|
||||
@@ -187,6 +189,38 @@ func TestEmailSendDeliversFullMessage(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// RFC 5322 section 3.6 requires a Date header, and every message should carry
|
||||
// a Message-ID. Not every submission server adds them, and spam filters
|
||||
// penalize mail without them.
|
||||
func TestEmailMessageHasDateAndMessageID(t *testing.T) {
|
||||
ids := map[string]bool{}
|
||||
for range 2 {
|
||||
raw, err := buildEmailMessage("artex@example.com", []string{"a@example.com"}, singleMsg())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
msg, err := mail.ReadMessage(strings.NewReader(raw))
|
||||
if err != nil {
|
||||
t.Fatalf("message does not parse: %v\n%s", err, raw)
|
||||
}
|
||||
date, err := msg.Header.Date()
|
||||
if err != nil {
|
||||
t.Fatalf("missing or invalid Date header: %v\n%s", err, raw)
|
||||
}
|
||||
if d := time.Since(date); d < -time.Minute || d > time.Minute {
|
||||
t.Errorf("Date %v is not the send time", date)
|
||||
}
|
||||
id := msg.Header.Get("Message-ID")
|
||||
if !strings.HasPrefix(id, "<") || !strings.HasSuffix(id, "@example.com>") {
|
||||
t.Errorf("Message-ID %q, want <...@example.com>", id)
|
||||
}
|
||||
ids[id] = true
|
||||
}
|
||||
if len(ids) != 2 {
|
||||
t.Errorf("two messages share a Message-ID: %v", ids)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEmailSendWithoutAuth(t *testing.T) {
|
||||
// AUTH must not be sent when no account is configured — some relays reject
|
||||
// because of it.
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
//go:build linux
|
||||
|
||||
package server
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"syscall"
|
||||
)
|
||||
|
||||
// prSetNoNewPrivs is PR_SET_NO_NEW_PRIVS from linux/prctl.h. With the flag set, execve
|
||||
// cannot grant privileges (setuid bits, file capabilities), so a process that dropped
|
||||
// to the executor identity cannot regain root through a setuid binary.
|
||||
const prSetNoNewPrivs = 38
|
||||
|
||||
// setNoNewPrivileges sets PR_SET_NO_NEW_PRIVS on the calling thread. The flag is per
|
||||
// thread and is inherited by what that thread forks or execs.
|
||||
func setNoNewPrivileges() error {
|
||||
if _, _, errno := syscall.RawSyscall6(syscall.SYS_PRCTL, prSetNoNewPrivs, 1, 0, 0, 0, 0); errno != 0 {
|
||||
return fmt.Errorf("no_new_privs: prctl(PR_SET_NO_NEW_PRIVS): %w", errno)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// setNoNewPrivsFn is the step the executor shims run before they drop identity. A
|
||||
// variable so a test can make it fail.
|
||||
var setNoNewPrivsFn = setNoNewPrivileges
|
||||
@@ -0,0 +1,51 @@
|
||||
//go:build linux
|
||||
|
||||
package server
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"os"
|
||||
"runtime"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// noNewPrivsOfThread reads the NoNewPrivs flag of the calling thread from /proc.
|
||||
func noNewPrivsOfThread(t *testing.T) string {
|
||||
t.Helper()
|
||||
b, err := os.ReadFile("/proc/thread-self/status")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, line := range strings.Split(string(b), "\n") {
|
||||
if v, ok := strings.CutPrefix(line, "NoNewPrivs:"); ok {
|
||||
return strings.TrimSpace(v)
|
||||
}
|
||||
}
|
||||
t.Fatal("no NoNewPrivs line in /proc/thread-self/status")
|
||||
return ""
|
||||
}
|
||||
|
||||
// PR_SET_NO_NEW_PRIVS is per thread: the check reads the thread that set it.
|
||||
func TestSetNoNewPrivilegesSetsTheFlag(t *testing.T) {
|
||||
runtime.LockOSThread()
|
||||
defer runtime.UnlockOSThread()
|
||||
if err := setNoNewPrivileges(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := noNewPrivsOfThread(t); got != "1" {
|
||||
t.Fatalf("NoNewPrivs = %s, want 1", got)
|
||||
}
|
||||
}
|
||||
|
||||
// The executor shims fail closed: no identity change and no exec when the flag cannot
|
||||
// be set. The error names the step so the operator can see why the start stopped.
|
||||
func TestEnterExecutorFailsClosedWithoutNoNewPrivs(t *testing.T) {
|
||||
old := setNoNewPrivsFn
|
||||
setNoNewPrivsFn = func() error { return errors.New("prctl refused") }
|
||||
t.Cleanup(func() { setNoNewPrivsFn = old })
|
||||
err := enterExecutor(DefaultExecUID, DefaultExecGID)
|
||||
if err == nil || !strings.Contains(err.Error(), "no_new_privs") {
|
||||
t.Fatalf("enterExecutor = %v, want a no_new_privs failure", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
//go:build unix && !linux
|
||||
|
||||
package server
|
||||
|
||||
import "errors"
|
||||
|
||||
// PR_SET_NO_NEW_PRIVS is Linux only. The privilege drop is never enabled elsewhere
|
||||
// (execPrivilegeSupported is false), so this only keeps the unix code compiling and
|
||||
// fails closed if reached.
|
||||
|
||||
var errNoNewPrivsUnsupported = errors.New("no_new_privs: PR_SET_NO_NEW_PRIVS is not supported on this platform")
|
||||
|
||||
func setNoNewPrivileges() error { return errNoNewPrivsUnsupported }
|
||||
|
||||
var setNoNewPrivsFn = setNoNewPrivileges
|
||||
@@ -0,0 +1,74 @@
|
||||
//go:build linux
|
||||
|
||||
package server
|
||||
|
||||
import (
|
||||
"os"
|
||||
"os/exec"
|
||||
"runtime"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
const nnpShimHelperEnv = "ARTEX_NNP_SHIM_HELPER"
|
||||
|
||||
// PR_SET_NO_NEW_PRIVS is per thread: the thread that sets it must be the one that
|
||||
// execs. This runs the real drop shim as root with GOMAXPROCS=1 and wraps
|
||||
// setNoNewPrivsFn so that right after the prctl on thread M1 a helper goroutine
|
||||
// steals and locks M1. If runDropShim did not call runtime.LockOSThread(), the shim
|
||||
// resumes on a new thread M2 where NoNewPrivs is 0 and the exec'd program reports 0;
|
||||
// with the lock it stays on M1 and reports 1. A plain "run the shim and read the
|
||||
// flag" test passes without the lock, so it does not guard this regression.
|
||||
func TestExecDropShimInheritsNoNewPrivs(t *testing.T) {
|
||||
if os.Geteuid() != 0 {
|
||||
t.Skip("needs root: the shim drops to the executor identity before it execs")
|
||||
}
|
||||
cmd := exec.Command(os.Args[0], "-test.run=^TestExecDropShimNoNewPrivsHelper$")
|
||||
cmd.Env = append(os.Environ(), nnpShimHelperEnv+"=1", "GOMAXPROCS=1")
|
||||
out, err := cmd.CombinedOutput()
|
||||
if err != nil {
|
||||
t.Fatalf("shim helper failed: %v\n%s", err, out)
|
||||
}
|
||||
for _, line := range strings.Split(string(out), "\n") {
|
||||
if v, ok := strings.CutPrefix(line, "NoNewPrivs:"); ok {
|
||||
if got := strings.TrimSpace(v); got != "1" {
|
||||
t.Fatalf("exec'd program NoNewPrivs = %q, want 1 (thread migrated after prctl)\n%s", got, out)
|
||||
}
|
||||
return
|
||||
}
|
||||
}
|
||||
t.Fatalf("no NoNewPrivs line from the exec'd program\n%s", out)
|
||||
}
|
||||
|
||||
// TestExecDropShimNoNewPrivsHelper is the child side: it wraps the flag setter and
|
||||
// runs the drop shim. On success the shim execs /bin/sh, which prints its own status.
|
||||
func TestExecDropShimNoNewPrivsHelper(t *testing.T) {
|
||||
if os.Getenv(nnpShimHelperEnv) != "1" {
|
||||
t.Skip("helper process only")
|
||||
}
|
||||
orig := setNoNewPrivsFn
|
||||
setNoNewPrivsFn = func() error {
|
||||
if err := orig(); err != nil {
|
||||
return err
|
||||
}
|
||||
// With GOMAXPROCS=1, blocking on <-locked lets this goroutine run on M1
|
||||
// (when the shim is not locked) and lock it, forcing the shim onto M2.
|
||||
// When the shim is locked to M1, the helper takes M2 and the shim resumes
|
||||
// on M1 with the flag set.
|
||||
locked := make(chan struct{})
|
||||
hold := make(chan struct{})
|
||||
go func() {
|
||||
runtime.LockOSThread()
|
||||
close(locked)
|
||||
<-hold
|
||||
}()
|
||||
<-locked
|
||||
return nil
|
||||
}
|
||||
RunExecShimIfRequested([]string{
|
||||
"artex", execDropArg, strconv.Itoa(DefaultExecUID), strconv.Itoa(DefaultExecGID), "--",
|
||||
"/bin/sh", "-c", "grep NoNewPrivs /proc/self/status",
|
||||
})
|
||||
t.Fatal("the drop shim returned instead of exec-ing the target")
|
||||
}
|
||||
@@ -10,6 +10,7 @@ import (
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strconv"
|
||||
"strings"
|
||||
"syscall"
|
||||
@@ -678,6 +679,9 @@ func RunExecShimIfRequested(argv []string) {
|
||||
}
|
||||
|
||||
func runBashShim(argv []string) {
|
||||
// PR_SET_NO_NEW_PRIVS is per thread, so the thread that sets it must be the one
|
||||
// that execs. The lock is never released: the process is replaced by exec.
|
||||
runtime.LockOSThread()
|
||||
uid, gid, err := execIDsFromEnv()
|
||||
if err != nil {
|
||||
shimFail(err)
|
||||
@@ -692,7 +696,15 @@ func runBashShim(argv []string) {
|
||||
// nested shell already running as the executor, whose environment the agent may
|
||||
// have set), the environment is first rebuilt from the allowlist (execenv_unix.go)
|
||||
// and HOME and XDG_CACHE_HOME move to the executor's home.
|
||||
// PR_SET_NO_NEW_PRIVS is set first, before the identity changes, on the calling
|
||||
// thread. The shims call this with their thread locked (runBashShim, runDropShim),
|
||||
// so the same thread goes on to exec the target and the flag is inherited by it and
|
||||
// everything it forks. Custom tools take SysProcAttr.Credential in the server and do
|
||||
// not pass through this shim, so the flag is a known gap there.
|
||||
func enterExecutor(uid, gid int) error {
|
||||
if err := setNoNewPrivsFn(); err != nil {
|
||||
return fmt.Errorf("no_new_privs must be set before the executor identity is applied: %w", err)
|
||||
}
|
||||
if os.Getuid() != uid || os.Getgid() != gid {
|
||||
if err := sealExecutorEnv(); err != nil {
|
||||
return err
|
||||
@@ -709,6 +721,7 @@ func enterExecutor(uid, gid int) error {
|
||||
|
||||
// runDropShim handles: <uid> <gid> -- <command> <args...>.
|
||||
func runDropShim(args []string) {
|
||||
runtime.LockOSThread() // same reason as runBashShim: the flag is per thread
|
||||
if len(args) < 3 || args[2] != "--" {
|
||||
shimFail(errors.New("drop shim needs <uid> <gid> -- <command> [args]"))
|
||||
}
|
||||
|
||||
+32
-5
@@ -209,22 +209,49 @@ func (s *logSinkT) subscribe() (<-chan LogLine, func()) {
|
||||
}
|
||||
|
||||
// parseLog pulls a level + [tag] out of a standard-logger line; the timestamp is
|
||||
// the capture time (RFC3339).
|
||||
// the capture time (RFC3339). Lines written by the slog text handler carry the level
|
||||
// word right after the LstdFlags timestamp ("WARN [traffic] ..."): that word is the
|
||||
// level, and the tag after it is the tag. Lines without a level word keep the
|
||||
// keyword guess and the leading-tag rule.
|
||||
func parseLog(line string) LogLine {
|
||||
msg := line
|
||||
// strip the "2006/01/02 15:04:05" LstdFlags prefix if present
|
||||
if len(msg) >= 20 && msg[4] == '/' && msg[7] == '/' && msg[10] == ' ' {
|
||||
msg = strings.TrimSpace(msg[19:])
|
||||
}
|
||||
tag := ""
|
||||
if strings.HasPrefix(msg, "[") {
|
||||
if i := strings.IndexByte(msg, ']'); i > 1 {
|
||||
tag = msg[1:i]
|
||||
if word, rest, ok := strings.Cut(msg, " "); ok {
|
||||
if level := slogLevel(word); level != "" {
|
||||
tag, text := splitTag(rest)
|
||||
return LogLine{TS: time.Now().Format(time.RFC3339), Level: level, Tag: tag, Text: text}
|
||||
}
|
||||
}
|
||||
tag, _ := splitTag(msg)
|
||||
return LogLine{TS: time.Now().Format(time.RFC3339), Level: levelOf(msg), Tag: tag, Text: msg}
|
||||
}
|
||||
|
||||
// slogLevel maps the slog level word to the sink's level, "" when word is not one.
|
||||
func slogLevel(word string) string {
|
||||
switch word {
|
||||
case "DEBUG", "INFO":
|
||||
return "info"
|
||||
case "WARN":
|
||||
return "warn"
|
||||
case "ERROR":
|
||||
return "error"
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// splitTag returns the leading [tag] of msg and the text after it.
|
||||
func splitTag(msg string) (tag, text string) {
|
||||
if strings.HasPrefix(msg, "[") {
|
||||
if i := strings.IndexByte(msg, ']'); i > 1 {
|
||||
return msg[1:i], strings.TrimSpace(msg[i+1:])
|
||||
}
|
||||
}
|
||||
return "", msg
|
||||
}
|
||||
|
||||
func levelOf(msg string) string {
|
||||
low := strings.ToLower(msg)
|
||||
for _, k := range []string{"fatal", "panic", "error", "err:", "failed", "dropped", "refused", "✕", "unreachable"} {
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
package server
|
||||
|
||||
import "testing"
|
||||
|
||||
// The line as the default slog handler writes it through the standard logger.
|
||||
func TestParseLogSlogWarnLineKeepsTagAndLevel(t *testing.T) {
|
||||
line := "2026/11/23 13:48:50 WARN [traffic] MITM failed, falling back to passthrough host=example.com ttl=1m0s err=boom"
|
||||
got := parseLog(line)
|
||||
if got.Tag != "traffic" {
|
||||
t.Fatalf("tag = %q, want traffic", got.Tag)
|
||||
}
|
||||
if got.Level != "warn" {
|
||||
t.Fatalf("level = %q, want warn", got.Level)
|
||||
}
|
||||
want := "MITM failed, falling back to passthrough host=example.com ttl=1m0s err=boom"
|
||||
if got.Text != want {
|
||||
t.Fatalf("text = %q, want %q", got.Text, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseLogSlogLevelWords(t *testing.T) {
|
||||
cases := map[string]string{
|
||||
"2026/11/23 13:48:50 INFO [egress] noise profile active profile=balanced": "info",
|
||||
"2026/11/23 13:48:50 DEBUG [enrich] probe": "info",
|
||||
"2026/11/23 13:48:50 ERROR [evidence] cleanup failed err=disk": "error",
|
||||
}
|
||||
for line, level := range cases {
|
||||
if got := parseLog(line); got.Level != level {
|
||||
t.Fatalf("%q: level = %q, want %q", line, got.Level, level)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Lines without a level word keep the keyword guess and the leading-tag rule.
|
||||
func TestParseLogWithoutLevelWordKeepsRules(t *testing.T) {
|
||||
got := parseLog("2026/11/23 13:48:50 [pg] connection refused")
|
||||
if got.Tag != "pg" || got.Level != "error" {
|
||||
t.Fatalf("tag/level = %q/%q, want pg/error", got.Tag, got.Level)
|
||||
}
|
||||
if got.Text != "[pg] connection refused" {
|
||||
t.Fatalf("text = %q, want the line with its tag", got.Text)
|
||||
}
|
||||
}
|
||||
@@ -334,6 +334,15 @@ const (
|
||||
// Target noise profile (off|quiet|balanced|aggressive). When stored it wins over
|
||||
// ARTEX_NOISE_PROFILE, which stays the fallback; applied at startup and on PUT.
|
||||
settingNoiseProfile = "noise_profile"
|
||||
// settingTriageProfile names an llm_profiles row that serves the decision-model
|
||||
// (/v1/systemone) contract: the triage client for closed-list judgements such as
|
||||
// the duplicate check in report_finding. Empty or 0 = triage off (main model
|
||||
// decides, exactly as before). See server/triage.go.
|
||||
settingTriageProfile = "triage_profile_id"
|
||||
// settingTriageMinConfidence is the suppression threshold for a duplicate answer
|
||||
// (0..1, empty = 0.5). Confidence on true duplicates moves with the question's
|
||||
// width, so this is a knob rather than a constant.
|
||||
settingTriageMinConfidence = "triage_min_confidence"
|
||||
// defaultWebSearchBackend is used when web search is on but no backend was picked.
|
||||
defaultWebSearchBackend = "ddgs"
|
||||
// deepSeekWebSearchBackend borrows the active LLM profile instead of its own
|
||||
|
||||
@@ -3920,6 +3920,8 @@ func (s *Server) settingsPayload() map[string]any {
|
||||
return map[string]any{
|
||||
"traffic_capture": s.m.TrafficEnabled(),
|
||||
"agent_traffic_binding": s.m.pg.GetBool(settingAgentTrafficBinding, false),
|
||||
"triage_profile_id": s.triageProfileID(),
|
||||
"triage_min_confidence": s.triageMinConfidence(),
|
||||
"llm_record": s.m.LLMRecordEnabled(),
|
||||
"web_search_enabled": on,
|
||||
"web_search_backend": backend,
|
||||
@@ -4021,6 +4023,14 @@ func (s *Server) putSettings(w http.ResponseWriter, r *http.Request) {
|
||||
// operation-constraint injection scope switches (default both on); take effect immediately (planner/worker read them every round), no agent rebuild needed.
|
||||
ConstraintsInjectPlanner *bool `json:"constraints_inject_planner"`
|
||||
ConstraintsInjectWorker *bool `json:"constraints_inject_worker"`
|
||||
// Triage profile: an llm_profiles row serving the decision-model (/v1/systemone)
|
||||
// contract, used for closed-list judgements (report_finding dedup). 0/null-safe:
|
||||
// omit = keep, 0 = off. Read per agent run, so it applies to runs started afterwards.
|
||||
TriageProfileID *int64 `json:"triage_profile_id"`
|
||||
// Suppression threshold for a duplicate answer (0..1). Lower catches more real
|
||||
// duplicates and risks suppressing a distinct one; the caller is told to
|
||||
// re-register in that case, which is what makes the low end affordable.
|
||||
TriageMinConfidence *float64 `json:"triage_min_confidence"`
|
||||
// Experimental: noa context compaction switch (default off); read per run, applies to runs started afterwards, no agent rebuild needed.
|
||||
NoaCompaction *bool `json:"noa_compaction"`
|
||||
// Vulnerability IM push global settings. The delivery engine re-reads all three every round, so changes
|
||||
@@ -4052,6 +4062,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)
|
||||
@@ -4067,6 +4097,19 @@ func (s *Server) putSettings(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
}
|
||||
if req.TriageMinConfidence != nil {
|
||||
if err := s.m.pg.SetSetting(settingTriageMinConfidence, strconv.FormatFloat(*req.TriageMinConfidence, 'f', 3, 64)); err != nil {
|
||||
writeErr(w, 500, err.Error())
|
||||
return
|
||||
}
|
||||
s.applyTriageThreshold()
|
||||
}
|
||||
if req.TriageProfileID != nil {
|
||||
if err := s.m.pg.SetSetting(settingTriageProfile, strconv.FormatInt(*req.TriageProfileID, 10)); err != nil {
|
||||
writeErr(w, 500, err.Error())
|
||||
return
|
||||
}
|
||||
}
|
||||
if req.NoaCompaction != nil {
|
||||
// The resolver is read per run; toggling takes effect immediately for runs started afterwards, no applyLLM rebuild needed.
|
||||
if err := s.m.SetNoaCompaction(*req.NoaCompaction); err != nil {
|
||||
|
||||
@@ -801,6 +801,8 @@ func (s *Server) agentsForTask(t *Task) *taskAgentBundle {
|
||||
window := workerRuntime.CompactionWindow()
|
||||
wk := agent.NewWorker(workerRuntime, "task-router", s.m.dir, tx, window, s.agentMaxTurns("worker"))
|
||||
wk.SetFindingRecorder(s.evidenceStore())
|
||||
wk.SetTriageClient(s.triageClient()) // advisory dedup on report_finding (nil = off)
|
||||
s.applyTriageThreshold() // stored suppression threshold (cheap, idempotent)
|
||||
wk.SetCompactionWindowResolver(workerRuntime.CompactionWindow)
|
||||
wk.SetNonStreaming(workerRuntime.nonStreaming) // per the task's currently active profile streaming switch (read every turn)
|
||||
wk.SetMaxTokens(workerRuntime.maxTokens) // as above, the output cap also follows the currently active profile
|
||||
@@ -812,6 +814,7 @@ func (s *Server) agentsForTask(t *Task) *taskAgentBundle {
|
||||
wk.SetConstraintInject(s.constraintInjectWorker) // operation-constraint injection into the worker (configurable, on by default)
|
||||
pl := agent.NewPlanner(plannerRuntime, "task-router", s.m.dir, tx, plannerRuntime.CompactionWindow(), s.agentMaxTurns("planner"))
|
||||
pl.SetFindingRecorder(s.evidenceStore())
|
||||
pl.SetTriageClient(s.triageClient()) // the planner registers findings too (wrap-up paths)
|
||||
pl.SetCompactionWindowResolver(plannerRuntime.CompactionWindow)
|
||||
pl.SetNonStreaming(plannerRuntime.nonStreaming)
|
||||
pl.SetMaxTokens(plannerRuntime.maxTokens)
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log"
|
||||
"net"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/Autumn-27/artex/agent"
|
||||
)
|
||||
|
||||
// triageClient builds the advisory triage client from the configured profile, or
|
||||
// nil when triage is off. The profile's base_url must serve the decision-model
|
||||
// contract at <base_url>/systemone; the model is the profile's model. Built per
|
||||
// agent run (cheap: one settings read + one profile read), so toggling the setting
|
||||
// takes effect on the next run without an agent rebuild.
|
||||
//
|
||||
// Fail-open by design: an unreadable setting, a missing profile or a profile with
|
||||
// no base_url/model returns nil, and report_finding behaves exactly as before.
|
||||
func (s *Server) triageClient() agent.TriageClient {
|
||||
id := s.triageProfileID()
|
||||
log.Printf("[triage] triageClient: profile_id=%d", id)
|
||||
if id <= 0 {
|
||||
return nil
|
||||
}
|
||||
p, err := s.m.pg.ProfileByID(id)
|
||||
if err != nil || p == nil {
|
||||
return nil
|
||||
}
|
||||
if strings.TrimSpace(p.BaseURL) == "" || strings.TrimSpace(p.Model) == "" {
|
||||
return nil
|
||||
}
|
||||
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
|
||||
// boot and on a settings change; an unreadable or out-of-range value keeps the current
|
||||
// threshold. 0 is in range and means "back to the default" (SetTriageMinConfidence).
|
||||
func (s *Server) applyTriageThreshold() {
|
||||
if s.m.pg == nil {
|
||||
return
|
||||
}
|
||||
raw, ok, err := s.m.pg.GetSetting(settingTriageMinConfidence)
|
||||
if err != nil || !ok {
|
||||
return
|
||||
}
|
||||
if v, err := strconv.ParseFloat(strings.TrimSpace(raw), 64); err == nil && v >= 0 && v <= 1 {
|
||||
agent.SetTriageMinConfidence(v)
|
||||
}
|
||||
}
|
||||
|
||||
// triageMinConfidence reports the stored threshold for the settings API (0 = default).
|
||||
func (s *Server) triageMinConfidence() float64 {
|
||||
if s.m.pg == nil {
|
||||
return 0
|
||||
}
|
||||
raw, ok, err := s.m.pg.GetSetting(settingTriageMinConfidence)
|
||||
if err != nil || !ok {
|
||||
return 0
|
||||
}
|
||||
v, err := strconv.ParseFloat(strings.TrimSpace(raw), 64)
|
||||
if err != nil {
|
||||
return 0
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
// triageProfileID returns the configured triage profile id, 0 when off or unreadable.
|
||||
func (s *Server) triageProfileID() int64 {
|
||||
if s.m.pg == nil {
|
||||
return 0
|
||||
}
|
||||
raw, ok, err := s.m.pg.GetSetting(settingTriageProfile)
|
||||
if err != nil || !ok {
|
||||
return 0
|
||||
}
|
||||
id, err := strconv.ParseInt(strings.TrimSpace(raw), 10, 64)
|
||||
if err != nil || id < 0 {
|
||||
return 0
|
||||
}
|
||||
return id
|
||||
}
|
||||
@@ -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"])
|
||||
}
|
||||
}
|
||||
+2
-2
@@ -2,7 +2,7 @@ package traffic
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
"log/slog"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
@@ -69,7 +69,7 @@ func (t *Traffic) RecordExternal(e ExternalExchange) error {
|
||||
id := fmt.Sprintf("%d-%04d", now.Unix(), n%10000)
|
||||
|
||||
if err := t.insertExchange(id, now.Unix(), host, method, db.TemplatePath(u.EscapedPath()), u.String(), status, respCT, len(e.RequestBody), len(e.ResponseBody), reqHead, reqB, respHead, respB); err != nil {
|
||||
log.Printf("[traffic] failed to ingest %s: %v", u.String(), err)
|
||||
slog.Error("[traffic] failed to ingest external exchange", "url", u.String(), "err", err)
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
|
||||
+2
-2
@@ -2,7 +2,7 @@ package traffic
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
@@ -62,6 +62,6 @@ func pace(f *mproxy.Flow) {
|
||||
defer cancel()
|
||||
host := egress.HostKey(f.Request.URL)
|
||||
if err := egress.Wait(ctx, host); err != nil {
|
||||
log.Printf("[traffic] pacing a Bash request to %s stopped waiting (%v); sending it unpaced", host, err)
|
||||
slog.Warn("[traffic] pacing request stopped waiting, sending unpaced", "host", host, "err", err)
|
||||
}
|
||||
}
|
||||
|
||||
+3
-3
@@ -5,7 +5,7 @@ import (
|
||||
"database/sql"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"log"
|
||||
"log/slog"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
@@ -64,13 +64,13 @@ func (t *Traffic) spillRawDir(data []byte, previewCap int) (preview []byte, blob
|
||||
h := hex.EncodeToString(sum[:])
|
||||
blobDir := filepath.Join(t.dir, "_blobs", "sha256", h[:2])
|
||||
if err := os.MkdirAll(blobDir, 0o700); err != nil {
|
||||
log.Printf("[traffic/socks5] failed to create blob directory: %v", err)
|
||||
slog.Error("[traffic/socks5] failed to create blob directory", "err", err)
|
||||
return append([]byte(nil), data[:previewCap]...), ""
|
||||
}
|
||||
blobPath := filepath.Join(blobDir, h+".bin")
|
||||
if _, err := os.Stat(blobPath); os.IsNotExist(err) {
|
||||
if err := writeBlobAtomic(blobDir, blobPath, h, data); err != nil {
|
||||
log.Printf("[traffic/socks5] failed to write blob %s: %v", h, err)
|
||||
slog.Error("[traffic/socks5] failed to write blob", "hash", h, "err", err)
|
||||
return append([]byte(nil), data[:previewCap]...), ""
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@ package traffic
|
||||
import (
|
||||
"database/sql"
|
||||
"io"
|
||||
"log"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
@@ -219,7 +219,7 @@ func (t *snapTable) convertLocked(cost int64) bool {
|
||||
t.tombs++
|
||||
*victim = reqSnap{done: victim.done, rules: victim.rules, host: victim.host, tomb: true, reason: reasonOriginalUnavailable, ruleIDs: ids}
|
||||
t.conversions.Add(1)
|
||||
log.Printf("[traffic] rewrite snapshot of a request to %s (rules %v) released under pressure: its exchange will be recorded as original request unavailable", victim.host, ids)
|
||||
slog.Warn("[traffic] rewrite snapshot released under pressure, exchange recorded as original request unavailable", "host", victim.host, "rules", ids)
|
||||
return true
|
||||
}
|
||||
|
||||
@@ -239,7 +239,7 @@ func (t *snapTable) refuseLocked(k flowKey, e *reqSnap) {
|
||||
}
|
||||
if now := t.now(); now.Sub(t.lastFullLog) >= time.Minute {
|
||||
t.lastFullLog = now
|
||||
log.Printf("[traffic] rewrite snapshot table full: requests are sent without rewriting (%d refused, %d without a trace so far)", t.capacity.Load(), t.tombDrops.Load())
|
||||
slog.Warn("[traffic] rewrite snapshot table full, requests sent without rewriting", "refused", t.capacity.Load(), "without_trace", t.tombDrops.Load())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -469,7 +469,7 @@ func (s *sink) Request(f *mproxy.Flow) {
|
||||
host := f.Request.URL.Hostname()
|
||||
defer func() {
|
||||
if recover() != nil {
|
||||
log.Printf("[traffic] rewrite rules stopped on a request to %s (class %s): it is sent as the client sent it", host, rewrite.ErrClassPanic)
|
||||
slog.Error("[traffic] rewrite rules panicked on request, sent as-is", "host", host, "class", rewrite.ErrClassPanic)
|
||||
}
|
||||
}()
|
||||
in := rewrite.Input{Request: engineRequest(f.Request), IsBinary: rulesIsBinary}
|
||||
@@ -541,7 +541,7 @@ func (s *sink) applyResponse(f *mproxy.Flow, set *rewrite.Set, hooks *HookSet, i
|
||||
defer func() {
|
||||
if recover() != nil {
|
||||
res = rewrite.Result{}
|
||||
log.Printf("[traffic] rewrite rules stopped on a response from %s (class %s): it is sent as the target sent it", f.Request.URL.Hostname(), rewrite.ErrClassPanic)
|
||||
slog.Error("[traffic] rewrite rules panicked on response, sent as-is", "host", f.Request.URL.Hostname(), "class", rewrite.ErrClassPanic)
|
||||
}
|
||||
}()
|
||||
r := set.Apply(rewrite.PhaseResponse, in)
|
||||
@@ -614,7 +614,7 @@ func (s *sink) applyRequestTrace(f *mproxy.Flow, set *rewrite.Set, hooks *HookSe
|
||||
defer func() {
|
||||
if recover() != nil {
|
||||
lines = nil
|
||||
log.Printf("[traffic] rewrite rules stopped on a request to %s (class %s)", f.Request.URL.Hostname(), rewrite.ErrClassPanic)
|
||||
slog.Error("[traffic] rewrite rules panicked on request", "host", f.Request.URL.Hostname(), "class", rewrite.ErrClassPanic)
|
||||
}
|
||||
}()
|
||||
in := rewrite.Input{Request: req, IsBinary: rulesIsBinary}
|
||||
@@ -649,7 +649,7 @@ func (s *sink) RequestError(f *mproxy.Flow, err error) {
|
||||
for _, id := range ids {
|
||||
snap.rules.NoteError(id, rewrite.ErrClassTransport)
|
||||
}
|
||||
log.Printf("[traffic] a request to %s rewritten by rules %v failed (class %s); the host stays intercepted", snap.host, ids, rewrite.ErrClassTransport)
|
||||
slog.Warn("[traffic] rewritten request failed, host stays intercepted", "host", snap.host, "rules", ids, "class", rewrite.ErrClassTransport)
|
||||
return
|
||||
}
|
||||
}
|
||||
@@ -675,7 +675,7 @@ func (s *sink) StreamResponseModifier(f *mproxy.Flow, in io.Reader) (out io.Read
|
||||
return in
|
||||
}
|
||||
s.t.snaps.largeResponses.Add(1)
|
||||
log.Printf("[traffic] the response to a request to %s with rewrite rules %v reached %d MiB: passed through, not recorded", snap.host, snap.appliedRuleIDs(), libraryStreamBody>>20)
|
||||
slog.Warn("[traffic] large response passed through, not recorded", "host", snap.host, "rules", snap.appliedRuleIDs(), "size_mib", libraryStreamBody>>20)
|
||||
return in
|
||||
}
|
||||
|
||||
|
||||
@@ -445,7 +445,7 @@ func TestRewriteTraceFailureRollsBack(t *testing.T) {
|
||||
}
|
||||
}
|
||||
out := logs.String()
|
||||
if !strings.Contains(out, "failed to record a rewritten exchange of 127.0.0.1 (writing rewrite trace; rules [7])") {
|
||||
if !strings.Contains(out, "failed to record rewritten exchange") || !strings.Contains(out, "host=127.0.0.1") || !strings.Contains(out, "rules=[7]") {
|
||||
t.Fatalf("log: %q", out)
|
||||
}
|
||||
for _, leak := range []string{"secret-path", "XYZ123", "client-path", "forced"} {
|
||||
@@ -474,7 +474,7 @@ func TestRewriteRequestErrorRedactedAndCleared(t *testing.T) {
|
||||
}
|
||||
waitFor(t, "empty snapshot table", func() bool { e, tb := tr.snaps.counts(); return e == 0 && tb == 0 })
|
||||
out := logs.String()
|
||||
if !strings.Contains(out, "a request to 127.0.0.1 rewritten by rules [3] failed (class transport_error)") {
|
||||
if !strings.Contains(out, "rewritten request failed") || !strings.Contains(out, "host=127.0.0.1") || !strings.Contains(out, "rules=[3]") || !strings.Contains(out, "class=transport_error") {
|
||||
t.Fatalf("log: %q", out)
|
||||
}
|
||||
for _, leak := range []string{"XYZ123", "client-path", dead, "refused"} {
|
||||
@@ -935,7 +935,7 @@ func TestRewriteSinkRecoverKeepsFlow(t *testing.T) {
|
||||
if n := countRows(t, tr, "exchanges"); n != 1 {
|
||||
t.Fatalf("%d exchanges", n)
|
||||
}
|
||||
if out := logs.String(); !strings.Contains(out, "class panic") || strings.Contains(out, "/p") {
|
||||
if out := logs.String(); !strings.Contains(out, "class=panic") || strings.Contains(out, "/p") {
|
||||
t.Fatalf("log %q", out)
|
||||
}
|
||||
}
|
||||
|
||||
+5
-5
@@ -6,7 +6,7 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"log/slog"
|
||||
"net"
|
||||
"net/url"
|
||||
"os"
|
||||
@@ -157,7 +157,7 @@ func SOCKS5ConfigFromEnv() (SOCKS5Config, bool) {
|
||||
case "1", "true", "on", "yes":
|
||||
enableUDP = true
|
||||
default:
|
||||
log.Printf("[traffic] %s=%q is not a boolean; leaving SOCKS5 UDP disabled", SOCKS5UDPEnabledEnv, rawUDP)
|
||||
slog.Warn("[traffic] non-boolean SOCKS5 UDP env value, leaving disabled", "env", SOCKS5UDPEnabledEnv, "value", rawUDP)
|
||||
}
|
||||
|
||||
switch rawEnabled {
|
||||
@@ -179,7 +179,7 @@ func SOCKS5ConfigFromEnv() (SOCKS5Config, bool) {
|
||||
}
|
||||
return SOCKS5Config{Addr: addr, EnableUDP: enableUDP}, true
|
||||
default:
|
||||
log.Printf("[traffic] %s=%q is not a boolean; leaving SOCKS5 disabled", SOCKS5EnabledEnv, rawEnabled)
|
||||
slog.Warn("[traffic] non-boolean SOCKS5 env value, leaving disabled", "env", SOCKS5EnabledEnv, "value", rawEnabled)
|
||||
return SOCKS5Config{}, false
|
||||
}
|
||||
}
|
||||
@@ -343,7 +343,7 @@ func (s *socks5Server) serve() {
|
||||
if errors.As(err, &ne) && ne.Timeout() {
|
||||
continue
|
||||
}
|
||||
log.Printf("[traffic/socks5] accept error: %v", err)
|
||||
slog.Error("[traffic/socks5] socks5 accept error", "err", err)
|
||||
return
|
||||
}
|
||||
if !s.trackConn(conn) {
|
||||
@@ -447,7 +447,7 @@ func (s *socks5Server) handleConn(client net.Conn) {
|
||||
func (s *socks5Server) recordCapture(rec RawTCPCapture) {
|
||||
if s.t != nil && s.t.db != nil {
|
||||
if _, err := s.t.RecordRawTCPStream(rec, s.cfg.PreviewBytes); err != nil {
|
||||
log.Printf("[traffic/socks5] failed to record raw tcp stream %s:%d: %v", rec.Host, rec.Port, err)
|
||||
slog.Error("[traffic/socks5] failed to record raw tcp stream", "host", rec.Host, "port", rec.Port, "err", err)
|
||||
}
|
||||
}
|
||||
if s.cfg.OnRecord != nil {
|
||||
|
||||
@@ -5,7 +5,7 @@ import (
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"log/slog"
|
||||
"net"
|
||||
"net/url"
|
||||
"strconv"
|
||||
@@ -438,8 +438,7 @@ func (s *socks5Server) recordUDPCapture(rec RawUDPCapture) {
|
||||
}
|
||||
if s.t != nil && s.t.db != nil {
|
||||
if _, err := s.t.RecordRawUDPDatagram(rec, s.cfg.UDPPreviewBytes); err != nil {
|
||||
log.Printf("[traffic/socks5-udp] failed to record datagram assoc=%s dst=%s:%d: %v",
|
||||
rec.AssociationID, rec.Host, rec.Port, err)
|
||||
slog.Error("[traffic/socks5-udp] failed to record UDP datagram", "assoc", rec.AssociationID, "dst_host", rec.Host, "dst_port", rec.Port, "err", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+11
-11
@@ -6,7 +6,7 @@ import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"log/slog"
|
||||
"net/url"
|
||||
"reflect"
|
||||
"strings"
|
||||
@@ -152,10 +152,10 @@ func (s *sink) startStream(f *mproxy.Flow, kind string) {
|
||||
if rewritten, ruleIDs := appliedRules(lines); rewritten {
|
||||
var re *recordError
|
||||
errors.As(err, &re)
|
||||
log.Printf("[traffic] failed to record a rewritten %s stream of %s (%s; rules %v)", kind, f.Request.URL.Hostname(), re.step, ruleIDs)
|
||||
slog.Error("[traffic] failed to record rewritten stream", "kind", kind, "host", f.Request.URL.Hostname(), "step", re.step, "rules", ruleIDs)
|
||||
return
|
||||
}
|
||||
log.Printf("[traffic] failed to record %s stream %s: %v", kind, f.Request.URL, err)
|
||||
slog.Error("[traffic] failed to record stream", "kind", kind, "url", f.Request.URL.String(), "err", err)
|
||||
return
|
||||
}
|
||||
st.id = id
|
||||
@@ -200,7 +200,7 @@ func lockLib(v any) (unlock func(), ok bool) {
|
||||
mu := libMutex(v)
|
||||
if mu == nil {
|
||||
libMutexMissing.Do(func() {
|
||||
log.Printf("[traffic] go-mitmproxy stream data has no mu field; stream messages are not recorded")
|
||||
slog.Warn("[traffic] go-mitmproxy stream data has no mu field; stream messages are not recorded")
|
||||
})
|
||||
return nil, false
|
||||
}
|
||||
@@ -424,7 +424,7 @@ func (t *Traffic) persistStream(st *streamState, rows []streamRow) {
|
||||
|
||||
tx, err := t.db.Begin()
|
||||
if err != nil {
|
||||
log.Printf("[traffic] failed to record stream messages of %s (beginning transaction): %v", st.id, err)
|
||||
slog.Error("[traffic] failed to record stream messages", "exchange_id", st.id, "step", "begin tx", "err", err)
|
||||
return
|
||||
}
|
||||
defer tx.Rollback() //nolint:errcheck // no-op once committed
|
||||
@@ -436,12 +436,12 @@ func (t *Traffic) persistStream(st *streamState, rows []streamRow) {
|
||||
if _, err := tx.Exec(`INSERT INTO stream_messages(exchange_id,seq,ts,direction,kind,event,event_id,retry,size,payload,payload_blob,truncated)
|
||||
VALUES(?,?,?,?,?,?,?,?,?,?,?,?)`, st.id, p.seq, p.ts, p.direction, p.kind, p.event, p.eventID, p.retry, p.size,
|
||||
inline, nullIfEmpty(p.body.hash), boolInt(p.truncated)); err != nil {
|
||||
log.Printf("[traffic] failed to record stream message %d of %s: %v", p.seq, st.id, err)
|
||||
slog.Error("[traffic] failed to record stream message", "seq", p.seq, "exchange_id", st.id, "err", err)
|
||||
return
|
||||
}
|
||||
if p.body.hash != "" {
|
||||
if _, err := tx.Exec(`INSERT OR IGNORE INTO blob_refs(hash,exchange_id) VALUES(?,?)`, p.body.hash, st.id); err != nil {
|
||||
log.Printf("[traffic] failed to record stream message %d of %s (registering blob reference): %v", p.seq, st.id, err)
|
||||
slog.Error("[traffic] failed to register stream message blob ref", "seq", p.seq, "exchange_id", st.id, "err", err)
|
||||
return
|
||||
}
|
||||
}
|
||||
@@ -449,12 +449,12 @@ VALUES(?,?,?,?,?,?,?,?,?,?,?,?)`, st.id, p.seq, p.ts, p.direction, p.kind, p.eve
|
||||
if meta != nil {
|
||||
if _, err := tx.Exec(`INSERT INTO stream_messages(exchange_id,seq,ts,direction,kind,size,payload)
|
||||
VALUES(?,?,?,'meta',0,?,?)`, st.id, metaSeq, time.Now().Unix(), len(meta), meta); err != nil {
|
||||
log.Printf("[traffic] failed to record stream limit marker of %s: %v", st.id, err)
|
||||
slog.Error("[traffic] failed to record stream limit marker", "exchange_id", st.id, "err", err)
|
||||
return
|
||||
}
|
||||
}
|
||||
if err := tx.Commit(); err != nil {
|
||||
log.Printf("[traffic] failed to record stream messages of %s (committing): %v", st.id, err)
|
||||
slog.Error("[traffic] failed to record stream messages", "exchange_id", st.id, "step", "commit", "err", err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -493,12 +493,12 @@ func (t *Traffic) finishStream(st *streamState) {
|
||||
t.wmu.Lock()
|
||||
defer t.wmu.Unlock()
|
||||
if _, err := t.db.Exec(`UPDATE exchanges SET req_len=?, resp_len=? WHERE id=?`, st.reqBytes, st.respBytes, st.id); err != nil {
|
||||
log.Printf("[traffic] failed to record stream sizes of %s: %v", st.id, err)
|
||||
slog.Error("[traffic] failed to record stream sizes", "exchange_id", st.id, "err", err)
|
||||
}
|
||||
if st.dropped {
|
||||
meta := streamMetaPayload(st)
|
||||
if _, err := t.db.Exec(`UPDATE stream_messages SET payload=?, size=? WHERE exchange_id=? AND direction='meta'`, meta, len(meta), st.id); err != nil {
|
||||
log.Printf("[traffic] failed to update stream limit marker of %s: %v", st.id, err)
|
||||
slog.Error("[traffic] failed to update stream limit marker", "exchange_id", st.id, "err", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+19
-19
@@ -15,7 +15,7 @@ import (
|
||||
"fmt"
|
||||
"io"
|
||||
"io/fs"
|
||||
"log"
|
||||
"log/slog"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
@@ -412,7 +412,7 @@ func (t *Traffic) initIndex() error {
|
||||
}
|
||||
t.incrementalVacuum = mode == autoVacuumIncremental
|
||||
if !t.incrementalVacuum {
|
||||
log.Printf("[traffic] index database does not have incremental vacuum enabled (auto_vacuum=%d): deleting traffic will not shrink index.sqlite; run one storage compaction to convert it", mode)
|
||||
slog.Warn("[traffic] index database does not have incremental vacuum enabled: deleting traffic will not shrink index.sqlite; run one storage compaction to convert it", "auto_vacuum", mode)
|
||||
}
|
||||
if _, err := conn.ExecContext(ctx, indexSchema); err != nil {
|
||||
return err
|
||||
@@ -421,7 +421,7 @@ func (t *Traffic) initIndex() error {
|
||||
return err
|
||||
}
|
||||
if _, err := conn.ExecContext(ctx, ftsSchema); err != nil {
|
||||
log.Printf("[traffic] full-text index unavailable; body search will be disabled (metadata search is unaffected): %v", err)
|
||||
slog.Warn("[traffic] full-text index unavailable; body search will be disabled", "err", err)
|
||||
return nil
|
||||
}
|
||||
t.fts = true
|
||||
@@ -623,7 +623,7 @@ func (t *Traffic) maybePassthrough(f *mproxy.Flow, err error) {
|
||||
}
|
||||
until := time.Now().Add(passthroughTTL)
|
||||
if _, loaded := t.pass.LoadOrStore(host, until); !loaded {
|
||||
log.Printf("[traffic] MITM with %s failed, falling back to passthrough for %s (this request failed; the host connects straight to the target and is not recorded until then; the first request after the window fails again if interception still cannot handle it): %v", host, passthroughTTL, err)
|
||||
slog.Warn("[traffic] MITM failed, falling back to passthrough", "host", host, "ttl", passthroughTTL, "err", err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -740,10 +740,10 @@ func (t *Traffic) recordViews(rq requestView, rs responseView, lines []rewrite.T
|
||||
rewritten, ruleIDs := appliedRules(lines)
|
||||
fail := func(step string, err error) {
|
||||
if rewritten {
|
||||
log.Printf("[traffic] failed to record a rewritten exchange of %s (%s; rules %v)", host, step, ruleIDs)
|
||||
slog.Error("[traffic] failed to record rewritten exchange", "host", host, "step", step, "rules", ruleIDs)
|
||||
return
|
||||
}
|
||||
log.Printf("[traffic] failed to record %s (%s): %v", url, step, err)
|
||||
slog.Error("[traffic] failed to record exchange", "url", url, "step", step, "err", err)
|
||||
}
|
||||
|
||||
tx, err := t.db.Begin()
|
||||
@@ -870,14 +870,14 @@ func tightenBlobPerms(root string) {
|
||||
if d.IsDir() {
|
||||
if info.Mode().Perm() != 0o700 {
|
||||
if err := os.Chmod(path, 0o700); err != nil {
|
||||
log.Printf("[traffic] failed to restrict blob directory %s: %v", path, err)
|
||||
slog.Error("[traffic] failed to restrict blob directory", "path", path, "err", err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if info.Mode().IsRegular() && info.Mode().Perm() != 0o600 {
|
||||
if err := os.Chmod(path, 0o600); err != nil {
|
||||
log.Printf("[traffic] failed to restrict blob %s: %v", path, err)
|
||||
slog.Error("[traffic] failed to restrict blob", "path", path, "err", err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
@@ -911,20 +911,20 @@ func (t *Traffic) spillAt(body []byte, contentType string, maxInline int) stored
|
||||
// the store only ever holds bodies above maxInlineBody, deduplicated by hash.
|
||||
blobDir := filepath.Join(t.dir, "_blobs", "sha256", h[:2])
|
||||
if err := os.MkdirAll(blobDir, 0o700); err != nil {
|
||||
log.Printf("[traffic] failed to create blob directory: %v", err)
|
||||
slog.Error("[traffic] failed to create blob directory", "err", err)
|
||||
return storedBody{inline: clipBytes(body, blobPreview), index: indexText()}
|
||||
}
|
||||
if err := os.Chmod(blobDir, 0o700); err != nil {
|
||||
log.Printf("[traffic] failed to restrict blob directory: %v", err)
|
||||
slog.Error("[traffic] failed to restrict blob directory", "err", err)
|
||||
}
|
||||
blobPath := filepath.Join(blobDir, h+".bin")
|
||||
if _, err := os.Stat(blobPath); os.IsNotExist(err) {
|
||||
if err := os.WriteFile(blobPath, body, 0o600); err != nil {
|
||||
log.Printf("[traffic] failed to write blob %s: %v", h, err)
|
||||
slog.Error("[traffic] failed to write blob", "hash", h, "err", err)
|
||||
return storedBody{inline: clipBytes(body, blobPreview), index: indexText()}
|
||||
}
|
||||
} else if err := os.Chmod(blobPath, 0o600); err != nil {
|
||||
log.Printf("[traffic] failed to restrict blob %s: %v", h, err)
|
||||
slog.Error("[traffic] failed to restrict blob", "hash", h, "err", err)
|
||||
}
|
||||
sb := storedBody{hash: h, index: indexText()}
|
||||
if text {
|
||||
@@ -1607,7 +1607,7 @@ func (t *Traffic) DeleteAll() (deleted int64, reclaimed int64, err error) {
|
||||
if err := t.compactIndex(); err != nil {
|
||||
// The deletion is already durable; compaction is disk space, not
|
||||
// correctness, so it must not turn a completed purge into a failed one.
|
||||
log.Printf("[traffic] failed to compact index: %v", err)
|
||||
slog.Error("[traffic] failed to compact index", "err", err)
|
||||
return deleted, 0, nil
|
||||
}
|
||||
return deleted, before - t.indexBytes(), nil
|
||||
@@ -1861,7 +1861,7 @@ func (t *Traffic) reapStage(stageDir string) {
|
||||
}
|
||||
t.reaping.Go(func() {
|
||||
if err := os.RemoveAll(stageDir); err != nil {
|
||||
log.Printf("[traffic] failed to clean up legacy traffic directory %s: %v", stageDir, err)
|
||||
slog.Error("[traffic] failed to clean up legacy traffic directory", "dir", stageDir, "err", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -2215,7 +2215,7 @@ func (t *Traffic) reclaim() {
|
||||
ctx := context.Background()
|
||||
conn, err := t.db.Conn(ctx)
|
||||
if err != nil {
|
||||
log.Printf("[traffic] failed to reclaim index space (getting a connection): %v", err)
|
||||
slog.Error("[traffic] failed to reclaim index space", "step", "get connection", "err", err)
|
||||
return
|
||||
}
|
||||
defer conn.Close()
|
||||
@@ -2226,7 +2226,7 @@ func (t *Traffic) reclaim() {
|
||||
progressed, err := t.reclaimChunk(ctx, conn, &merges)
|
||||
t.wmu.Unlock()
|
||||
if err != nil {
|
||||
log.Printf("[traffic] failed to reclaim index space: %v", err)
|
||||
slog.Error("[traffic] failed to reclaim index space", "err", err)
|
||||
return
|
||||
}
|
||||
if !progressed {
|
||||
@@ -2236,11 +2236,11 @@ func (t *Traffic) reclaim() {
|
||||
return // shutdown must not wait out the remaining budget
|
||||
}
|
||||
if step+1 >= reclaimMaxSteps {
|
||||
log.Printf("[traffic] index space reclamation unfinished (used up the %d-step limit); will continue on the next deletion", reclaimMaxSteps)
|
||||
slog.Info("[traffic] index space reclamation unfinished, will continue on the next deletion", "reason", "step limit", "max_steps", reclaimMaxSteps)
|
||||
return
|
||||
}
|
||||
if time.Now().After(deadline) {
|
||||
log.Printf("[traffic] index space reclamation unfinished (used up the %s budget); will continue on the next deletion", reclaimBudget)
|
||||
slog.Info("[traffic] index space reclamation unfinished, will continue on the next deletion", "reason", "time budget", "budget", reclaimBudget)
|
||||
return
|
||||
}
|
||||
}
|
||||
@@ -2250,7 +2250,7 @@ func (t *Traffic) reclaim() {
|
||||
t.wmu.Lock()
|
||||
defer t.wmu.Unlock()
|
||||
if _, err := conn.ExecContext(ctx, `PRAGMA wal_checkpoint(TRUNCATE)`); err != nil {
|
||||
log.Printf("[traffic] failed to truncate WAL: %v", err)
|
||||
slog.Error("[traffic] failed to truncate WAL", "err", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@@ -5,7 +5,7 @@ import (
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"log/slog"
|
||||
"net"
|
||||
"net/url"
|
||||
"os"
|
||||
@@ -96,7 +96,7 @@ func TransparentTCPConfigFromEnv() (TransparentTCPConfig, bool) {
|
||||
}
|
||||
return TransparentTCPConfig{Addr: rawAddr}, true
|
||||
default:
|
||||
log.Printf("[traffic] %s=%q is not a boolean; leaving transparent TCP disabled", TransparentTCPEnabledEnv, rawEnabled)
|
||||
slog.Warn("[traffic] transparent TCP env var is not a boolean, leaving disabled", "env", TransparentTCPEnabledEnv, "value", rawEnabled)
|
||||
return TransparentTCPConfig{}, false
|
||||
}
|
||||
}
|
||||
@@ -302,7 +302,7 @@ func (s *transparentServer) serve() {
|
||||
if errors.As(err, &ne) && ne.Timeout() {
|
||||
continue
|
||||
}
|
||||
log.Printf("[traffic/transparent] accept error: %v", err)
|
||||
slog.Error("[traffic/transparent] transparent proxy accept error", "err", err)
|
||||
return
|
||||
}
|
||||
if !s.trackConn(conn) {
|
||||
@@ -389,7 +389,7 @@ func (s *transparentServer) handleConn(client net.Conn) {
|
||||
C2SData: c2sCap.buf,
|
||||
S2CData: s2cCap.buf,
|
||||
}, s.cfg.PreviewBytes); err != nil {
|
||||
log.Printf("[traffic/transparent] failed to record raw TCP stream %s: %v", targetAddr, err)
|
||||
slog.Error("[traffic/transparent] failed to record raw TCP stream", "target", targetAddr, "err", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -34,6 +34,8 @@ RECOVER
|
||||
update_docker(){
|
||||
command -v docker >/dev/null 2>&1 && docker compose version >/dev/null 2>&1 \
|
||||
|| die "docker / docker compose not detected; install and deploy with ./install.sh first"
|
||||
docker buildx version >/dev/null 2>&1 \
|
||||
|| die "docker buildx not detected; the image build needs it (see the Docker section of the README)"
|
||||
[ -f .env ] || die ".env not found; run ./install.sh first to complete the initial deployment"
|
||||
|
||||
# Touch only artex: postgres is pinned to 16-alpine and does not need upgrading along
|
||||
|
||||
@@ -84,12 +84,16 @@ function domainHostname(value: string): string | null {
|
||||
if (value.startsWith("//")) candidate = `http:${value}`;
|
||||
else if (!value.includes("://")) candidate = `http://${value}`;
|
||||
const url = new URL(candidate);
|
||||
return (
|
||||
url.hostname
|
||||
.replace(/^\[|\]$/g, "")
|
||||
.replace(/\.$/, "")
|
||||
.toLowerCase() || null
|
||||
);
|
||||
const hostname = url.hostname
|
||||
.replace(/^\[|\]$/g, "")
|
||||
.replace(/\.$/, "")
|
||||
.toLowerCase();
|
||||
// "*.example.com" scopes a domain and its subdomains; the server accepts it on a registrable domain.
|
||||
if (hostname.startsWith("*.")) {
|
||||
const domain = hostname.slice(2);
|
||||
return ipVersion(domain) === null ? domain : null;
|
||||
}
|
||||
return hostname || null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user