Compare commits

..
Author SHA1 Message Date
dependabot[bot] bf2343e0bc deps(docker): bump python from 935c3c5 to 44cf179
Bumps python from `935c3c5` to `44cf179`.

---
updated-dependencies:
- dependency-name: python
  dependency-version: 3.12-slim-bookworm
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-11-28 18:25:16 +00:00
12 changed files with 3 additions and 313 deletions
-3
View File
@@ -19,10 +19,7 @@ All notable changes to this project are documented in this file. The format is b
- **Go vulnerability scanning in CI**: every push and pull request runs the official `govulncheck` action against packages reachable from `./...`, using the Go version declared by `go.mod`. Run the same check locally with `./scripts/verify.sh --security`.
### Fixed
- **LLM failover charges the response budget against the context window**: the window filter sized only the prompt, so a profile whose window held the prompt but not `max_tokens` was still tried. The provider rejects that call with a 400, and a 400 never fails over (a malformed request fails identically everywhere), so the call failed outright instead of moving to a profile that can hold prompt and response. The estimate now adds the request's `max_tokens`, and a member that cannot hold both is skipped; when every member is skipped the chain head is still tried, as before.
- **Inserted assets trigger the async enrichment again**: `ToolSet.enrich` was assigned by `SetEnrich` and passed all the way from the manager, but no tool ever read it, so the enrichment engine started, was paced by the noise profile, was covered by tests, and never received a job: an inserted domain was never resolved and an inserted HTTP service was never probed. `insert_assets` now hands each written asset to the engine (domain → DNS resolve, HTTP service → probe), after the intercept gate and only for a row that was actually written. Both ingest tools call `insert_assets`, so scanned assets are covered too.
- **`GET /api/traffic/exchange` reports which capture it returned**: the response carried only the raw `req`/`resp` text and stream counters, so a caller holding an exchange id could not tell which exchange the bodies came from or when it was captured. It now also returns `id` and `ts` (Unix seconds) from the exchange's metadata row. The bench-v2 R2 check needs that timestamp to credit a finding's `traffic_ref`, and without it every referenced capture was rejected as `traffic_ref_missing_timestamp`, leaving detection rate and precision at zero for any run with traffic verification on (the default; `--skip-traffic-verify` opts out).
- **Ollama accepts the Main Agent's tools**: the `summary` pattern in the `record_fact` schema was unanchored, and Ollama refuses the whole request with HTTP 400 ("Pattern must start with '^' and end with '$'") when it turns a schema into a grammar, so the first turn failed. The pattern is now anchored and still means "contains a non-whitespace character", multi-line summaries included. A test fails on any unanchored pattern in the schema. Based on the approach in #599 by @Layfate (#595).
- **`traffic_search` host matching**: a port search such as `host:8443` matched any capture of that host whose URL quoted `host:8443` in its query string (`?next=http://host:8443/`, typical of open-redirect and SSRF probes), because the authority prefix was not anchored to the scheme. It is now anchored to `http`, `https`, `ws` and `wss`. The recorded host keeps the client's case while the search is lowercased, so a capture of `https://Mixed.Example.com/` was not found by any host search; the comparison now ignores case. A compressed body with a bad checksum or trailing garbage now keeps the text decoded before the error instead of dropping out of the index, and the store directory guard on host delete ignores case for case-insensitive filesystems.
- **Browser capture keeps a bounded request map**: unfinished debugger requests are capped at 500, and a request that fails to load is dropped instead of waiting for eviction. A stored body longer than 256K JavaScript characters is cut and marked `[truncated by extension]`. That count is UTF-16 code units, not bytes; the server still enforces its byte cap on ingest.
+1 -1
View File
@@ -160,7 +160,7 @@ RUN set -eux; \
test "$count" -gt 10000
# ---------------------------------------------------------------- runtime ---
FROM python:3.12-slim-bookworm@sha256:935c3c5b12357a7e10caa9c1e6ca5692344d97cf229832ef584be2cec9fc03df
FROM python:3.12-slim-bookworm@sha256:44cf1793efa7c7a476bb0f2cff81443f4a072c90c1cb127e2924933daa3e8c64
ARG TARGETARCH
ARG ARTEX_VERSION=dev
ARG ARTEX_REVISION=
-96
View File
@@ -1,96 +0,0 @@
package agent
import (
"context"
"testing"
)
// fakeEnrich records the triggers the tool layer hands to the enrichment engine.
// Before insert_assets called the engine, the ToolSet field was assigned but
// never read, so no asset was ever resolved or probed (see triggerEnrichment).
type fakeEnrich struct {
resolved []string
probed []string
probeCtx []context.Context
}
func (f *fakeEnrich) ResolveDomain(id int64, host string) {
f.resolved = append(f.resolved, host)
}
func (f *fakeEnrich) ProbeSite(ctx context.Context, id int64, url string) {
f.probed = append(f.probed, url)
f.probeCtx = append(f.probeCtx, ctx)
}
// TestInsertAssetsTriggersEnrichment pins which inserted asset types start an
// async auto-completion job: a domain resolves, an HTTP service is probed, and
// everything the engine cannot act on is left alone.
func TestInsertAssetsTriggersEnrichment(t *testing.T) {
cases := []struct {
name string
typ string
item assetInputItem
wantDomain string
wantProbe string
}{
{name: "root_domain resolves", typ: "root_domain", item: assetInputItem{Domain: "example.com"}, wantDomain: "example.com"},
{name: "subdomain resolves", typ: "subdomain", item: assetInputItem{Domain: "api.example.com"}, wantDomain: "api.example.com"},
{name: "domain is trimmed", typ: "subdomain", item: assetInputItem{Domain: " api.example.com "}, wantDomain: "api.example.com"},
{name: "http service is probed", typ: "service", item: assetInputItem{URL: "https://example.com:8443/login"}, wantProbe: "https://example.com:8443/login"},
{name: "url is trimmed", typ: "service", item: assetInputItem{URL: " https://example.com/ "}, wantProbe: "https://example.com/"},
// A non-HTTP service has no url: nothing to probe.
{name: "non-http service is skipped", typ: "service", item: assetInputItem{ServiceName: "ssh", Port: 22}},
{name: "ip is skipped", typ: "ip", item: assetInputItem{IP: "203.0.113.7"}},
{name: "app is skipped", typ: "app", item: assetInputItem{AppName: "portal"}},
{name: "endpoint is skipped", typ: "endpoint", item: assetInputItem{URL: "https://example.com/api", Method: "GET"}},
{name: "blank domain is skipped", typ: "subdomain", item: assetInputItem{Domain: " "}},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
enr := &fakeEnrich{}
ts := NewToolSet(nil, "worker")
ts.SetEnrich(enr)
ctx := context.Background()
ts.triggerEnrichment(ctx, tc.typ, 7, tc.item)
if tc.wantDomain != "" {
if len(enr.resolved) != 1 || enr.resolved[0] != tc.wantDomain {
t.Fatalf("resolved %v, want [%s]", enr.resolved, tc.wantDomain)
}
} else if len(enr.resolved) != 0 {
t.Fatalf("resolved %v, want no DNS job", enr.resolved)
}
if tc.wantProbe != "" {
if len(enr.probed) != 1 || enr.probed[0] != tc.wantProbe {
t.Fatalf("probed %v, want [%s]", enr.probed, tc.wantProbe)
}
// The probe must keep the caller's context: it carries the target
// scope the engine gates the dial on, so a replaced or background
// context would make the probe refuse to dial.
if len(enr.probeCtx) != 1 || enr.probeCtx[0] != ctx {
t.Fatalf("probe did not receive the caller context")
}
} else if len(enr.probed) != 0 {
t.Fatalf("probed %v, want no HTTP probe", enr.probed)
}
})
}
}
// TestEnrichmentTriggerWithoutEngineIsNoop pins that the trigger is optional:
// tool sets built outside a worker run carry no engine, and that must not panic.
func TestEnrichmentTriggerWithoutEngineIsNoop(t *testing.T) {
ts := NewToolSet(nil, "worker")
ts.triggerEnrichment(context.Background(), "root_domain", 1, assetInputItem{Domain: "example.com"})
ts.triggerEnrichment(context.Background(), "service", 2, assetInputItem{URL: "https://example.com/"})
// A write that produced no id (a no-op upsert path) must not be triggered either.
enr := &fakeEnrich{}
ts.SetEnrich(enr)
ts.triggerEnrichment(context.Background(), "root_domain", 0, assetInputItem{Domain: "example.com"})
ts.triggerEnrichment(context.Background(), "service", -1, assetInputItem{URL: "https://example.com/"})
if len(enr.resolved) != 0 || len(enr.probed) != 0 {
t.Fatalf("triggered without a persisted asset id: resolved %v probed %v", enr.resolved, enr.probed)
}
}
+1 -31
View File
@@ -133,33 +133,6 @@ func insertAssetsRuleLoadFailure(err error) (actool.Result, bool) {
return actool.Errorf("asset intercept rules are unavailable; insertion refused"), true
}
// triggerEnrichment hands one freshly inserted asset to the async enrichment
// engine: a domain gets a DNS resolve, an HTTP service gets a probe. Only the
// types the engine can act on are triggered — an IP, app, endpoint or non-HTTP
// service has nothing to resolve or probe on its own.
//
// The trigger is best-effort by design: the engine dedups by cooldown, drops the
// job when its queue is full, resolves DNS ungated and gates the HTTP probe on
// the target scope carried by ctx (a probe without a scope dials nothing). A nil
// engine — no manager, or a tool set built outside a worker run — is a no-op.
func (t *ToolSet) triggerEnrichment(ctx context.Context, typ string, id int64, item assetInputItem) {
if t.enrich == nil || id <= 0 {
return
}
switch typ {
case "root_domain", "subdomain":
if host := strings.TrimSpace(item.Domain); host != "" {
t.enrich.ResolveDomain(id, host)
}
case "service":
// Only the HTTP branch (url set) has something to probe; a non-HTTP
// service carries no URL, so the empty check covers both.
if raw := strings.TrimSpace(item.URL); raw != "" {
t.enrich.ProbeSite(ctx, id, raw)
}
}
}
// insertAssets is the unified insert_assets agent tool.
func (t *ToolSet) insertAssets() actool.CoreTool {
return writeTool(
@@ -243,7 +216,7 @@ func (t *ToolSet) insertAssets() actool.CoreTool {
}, "type"),
},
}, "assets"),
func(ctx context.Context, in json.RawMessage) (actool.Result, error) {
func(_ context.Context, in json.RawMessage) (actool.Result, error) {
if t.as == nil {
return actool.Errorf("insert_assets is not enabled: AssetStore is not initialized"), nil
}
@@ -391,9 +364,6 @@ func (t *ToolSet) insertAssets() actool.CoreTool {
results = append(results, result{Index: i, ID: id, Type: typ})
t.writes.Assets++
t.anchorOwner(id)
// Auto-completion is triggered only for an asset that was actually
// written: a gated or failed item must not be resolved or probed.
t.triggerEnrichment(ctx, typ, id, item)
if taskID > 0 {
var sourceNodeID *int64
if t.ownerNode > 0 {
-8
View File
@@ -275,11 +275,6 @@ func trimErr(err error) string {
// estimateTokens roughly sizes a request so members whose context window clearly
// can't hold it are skipped. Deliberately crude (~3.5 chars/token) and biased to
// over-estimate slightly; it only needs to tell "fits" from "nowhere near".
//
// The response budget counts as part of the request: a provider rejects a call
// whose prompt plus max_tokens exceeds the window, and shouldFailover never
// retries a 400, so a member that can hold only the prompt is a member that
// fails the whole call.
func estimateTokens(req llm.CompletionRequest) int {
n := 0
for _, s := range req.System {
@@ -293,9 +288,6 @@ func estimateTokens(req llm.CompletionRequest) int {
// cheaply — charge a flat ~120 chars per top-level property instead.
n += len(t.Name) + len(t.Description) + len(t.InputSchema)*120
}
if req.MaxTokens > 0 {
n += req.MaxTokens * 7 / 2 // max_tokens is in tokens; n accumulates chars
}
return n * 2 / 7 // ≈ len/3.5
}
-30
View File
@@ -382,33 +382,3 @@ func TestTrimErrKeepsValidUTF8(t *testing.T) {
t.Fatalf("trimErr = %q (%d bytes), want at most 300 bytes plus …", got, len(got))
}
}
// The window filter must charge the response budget as well as the prompt. A
// profile whose window cannot hold prompt + max_tokens rejects the call with a
// 400, and shouldFailover never retries a 400, so the request would fail
// outright instead of moving to the profile that can hold it.
func TestWindowFilterChargesMaxTokens(t *testing.T) {
small, big := okProv("small", "s"), okProv("big", "b")
ms := member(1, "small", 10, small)
ms.WindowTokens = 20_000
mb := member(2, "big", 5, big)
mb.WindowTokens = 1_000_000
p := New([]*Member{ms, mb}, NewRegistry(nil, nil))
// ~16K prompt tokens (56K chars at the estimator's ~3.5 chars/token) plus an
// 8K response cap is 24K, which no 20K window can hold.
req := llm.CompletionRequest{
Messages: []llm.Message{llm.UserText(strings.Repeat("x", 56_000))},
MaxTokens: 8192,
}
got, err := drain(p.Stream(context.Background(), req))
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if got != "b" {
t.Fatalf("text=%q, want the large-window member to serve it", got)
}
if small.calls != 0 {
t.Fatalf("sent a request whose prompt+max_tokens cannot fit the window (calls=%d)", small.calls)
}
}
-23
View File
@@ -401,29 +401,6 @@ class BenchV2R2AndR5Tests(unittest.TestCase):
self.assertEqual(len(scores["detection_rate_wilson95"]), 2)
self.assertEqual(len(scores["precision_wilson95"]), 2)
def test_r2_reads_real_traffic_exchange_payload(self):
"""The verifier must work on what GET /api/traffic/exchange actually
returns: the raw bodies plus the exchange id and capture time. A payload
without them (the endpoint before it reported identity) is unusable, so
the producer and this consumer have to stay in sync."""
def exchange(ts=None):
body = {"req": "GET /rest/user/login HTTP/1.1\n", "resp": "HTTP/1.1 200 OK\n",
"stream_count": 0, "stream_kind": ""}
if ts is not None:
body["id"] = "1700001200-0001"
body["ts"] = ts
return body
findings = [
{"id": 1, "name": "Payload names its capture", "traffic_refs": ["1700001200-0001"]},
{"id": 2, "name": "Bodies only", "traffic_refs": ["1700001200-0002"]},
]
store = {"1700001200-0001": exchange(1700001200), "1700001200-0002": exchange()}
tv = run_bench.verify_finding_traffic_refs(findings, store.get, self.window_start, self.window_end)
self.assertEqual(tv["verified_keys"], {(int, 1)})
self.assertEqual(tv["verified_refs"][1]["timestamp"], 1700001200)
self.assertEqual(tv["rejected"][2], "traffic_ref_missing_timestamp")
def test_r2_parses_iso8601_and_millisecond_timestamps(self):
findings = [
{"id": "f-iso", "name": "ISO ts", "traffic_refs": [{"traffic_id": "ex-iso"}]},
+1 -10
View File
@@ -3808,16 +3808,7 @@ func (s *Server) getTrafficExchange(w http.ResponseWriter, r *http.Request) {
if err != nil {
log.Printf("[traffic] stream info for %s: %v", id, err)
}
// The bodies alone do not say which exchange they belong to or when it was
// captured; the benchmark's R2 check needs both to credit a finding that
// references this exchange.
out := map[string]any{"req": req, "resp": resp, "stream_count": count, "stream_kind": kind}
if meta, merr := tr.Meta(id); merr == nil {
out["id"], out["ts"] = meta.ID, meta.TS
} else {
log.Printf("[traffic] metadata for %s: %v", id, merr)
}
writeJSON(w, 200, out)
writeJSON(w, 200, map[string]any{"req": req, "resp": resp, "stream_count": count, "stream_kind": kind})
}
// getTrafficStream returns one page of a WebSocket/SSE exchange's messages in
-58
View File
@@ -1,58 +0,0 @@
package server
import (
"encoding/json"
"testing"
)
// TestTrafficExchangeCarriesIdentity pins the contract the bench-v2 R2 check
// reads: GET /api/traffic/exchange must name the exchange it returned and when
// it was captured. scripts/benchmark/run_bench.py credits a finding only when a
// referenced traffic_ref exists in the capture store with a timestamp inside the
// run window; with the bodies alone the timestamp lookup finds nothing and every
// verified finding is rejected as "traffic_ref_missing_timestamp".
func TestTrafficExchangeCarriesIdentity(t *testing.T) {
s, request := ingestServer(t)
db := s.m.Traffic().DB()
const ts = 1700001200
if _, err := db.Exec(`INSERT INTO exchanges(id,ts,host,method,url_template,url,status,content_type,req_len,resp_len,path)
VALUES('1700001200-0001',?,'api.example.com','GET','/login','http://api.example.com/login',200,'text/html',0,0,'')`, ts); err != nil {
t.Fatal(err)
}
if _, err := db.Exec(`INSERT INTO exchange_bodies(id,req_head,resp_head) VALUES('1700001200-0001','GET /login HTTP/1.1\n','HTTP/1.1 200 OK\n')`); err != nil {
t.Fatal(err)
}
w := request("GET", "/api/traffic/exchange?id=1700001200-0001", "")
if w.Code != 200 {
t.Fatalf("GET exchange = %d %s", w.Code, w.Body)
}
var got struct {
ID string `json:"id"`
TS int64 `json:"ts"`
Req string `json:"req"`
Resp string `json:"resp"`
}
if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil {
t.Fatalf("decode %s: %v", w.Body, err)
}
if got.ID != "1700001200-0001" {
t.Fatalf("id = %q, want the requested exchange id (body %s)", got.ID, w.Body)
}
if got.TS != ts {
t.Fatalf("ts = %d, want the capture time %d (body %s)", got.TS, ts, w.Body)
}
// The bodies stay exactly as before; the identity fields are additive.
if got.Req == "" || got.Resp == "" {
t.Fatalf("bodies missing: req %q resp %q", got.Req, got.Resp)
}
}
// TestTrafficExchangeUnknownID checks the 404 path still reports a missing
// exchange rather than an empty record.
func TestTrafficExchangeUnknownID(t *testing.T) {
_, request := ingestServer(t)
if w := request("GET", "/api/traffic/exchange?id=does-not-exist", ""); w.Code != 404 {
t.Fatalf("unknown exchange = %d %s, want 404", w.Code, w.Body)
}
}
-34
View File
@@ -1,34 +0,0 @@
package traffic
import "testing"
// TestMetaReturnsExchangeIdentity checks Meta reports the same id and capture
// time the exchange was stored under, so callers that only have the bodies can
// still identify the row.
func TestMetaReturnsExchangeIdentity(t *testing.T) {
tr, _ := openTraffic(t)
tr.record(newFlow("api.example.com", "GET", "/login", nil, []byte("ok")))
id := onlyExchangeID(t, tr)
m, err := tr.Meta(id)
if err != nil {
t.Fatalf("Meta(%q): %v", id, err)
}
if m.ID != id {
t.Fatalf("id = %q, want %q", m.ID, id)
}
if m.TS <= 0 {
t.Fatalf("ts = %d, want a positive capture time", m.TS)
}
if m.Host != "api.example.com" || m.Method != "GET" || m.Status != 200 {
t.Fatalf("meta = %+v, want host/method/status of the recorded flow", m)
}
}
// TestMetaUnknownID checks a missing exchange is an error rather than a zero row.
func TestMetaUnknownID(t *testing.T) {
tr, _ := openTraffic(t)
if m, err := tr.Meta("1700000000-9999"); err == nil {
t.Fatalf("Meta of unknown id = %+v, want error", m)
}
}
-14
View File
@@ -1533,20 +1533,6 @@ func (t *Traffic) Page(f PageQuery, page, size int) (rows []ExchangeMeta, total
return rows, total, rs.Err()
}
// Meta returns the metadata row of one exchange — its id, capture time, request
// line, status and sizes — without the bodies. Consumers that receive the body
// text from Get still need these fields to identify which exchange they got and
// when it was captured.
func (t *Traffic) Meta(id string) (ExchangeMeta, error) {
var m ExchangeMeta
err := t.db.QueryRow(`SELECT id,ts,host,method,url_template,url,status,content_type,resp_len,path,`+rewrittenExistsSQL+` FROM exchanges WHERE id=?`, id).
Scan(&m.ID, &m.TS, &m.Host, &m.Method, &m.URLTemplate, &m.URL, &m.Status, &m.ContentType, &m.RespLen, &m.Path, &m.Rewritten)
if err != nil {
return ExchangeMeta{}, err
}
return m, nil
}
// Get returns the full request/response text of one exchange. Bodies come from
// the database; rows recorded before bodies moved into SQLite carry a non-empty
// path and are read from the legacy on-disk tree instead, so history stays
-5
View File
@@ -951,11 +951,6 @@ export interface TrafficResp {
// Full raw request/response of one exchange (lazy-loaded on row select).
export interface TrafficDetail {
// Which exchange these bodies belong to, and when it was captured (Unix
// seconds). The benchmark's R2 check uses them to prove a finding references a
// capture from the run window.
id?: string;
ts?: number;
req: string;
resp: string;
// WebSocket/SSE exchanges carry their messages separately (trafficStream);