Compare commits

..
Author SHA1 Message Date
BaaRai 99cda59643 fix(agent): keep knowledge_lookup out of the target gate
knowledge_lookup takes a taxonomy id or keyword, never a connection. Add it to
the intercept noTargetTools list so the target gate does not read targets from
its query. TestDomainToolsDeclareNoTarget now covers the new domain tool.

Refs #521.
2026-11-24 01:19:21 +01:00
BaaRai 9cd000dbd0 feat(agent): add versioned knowledge pack and knowledge_lookup tool
Embed MITRE ATT&CK, OWASP WSTG and MITRE CWE ids, names, categories and
capped descriptions generated by scripts/knowledge/build.py. The pack records
the source URL, license, retrieval date and SHA-256; the license texts and
attribution live in knowledge/NOTICE and knowledge/licenses.

Expose a read-only knowledge_lookup tool to the planner and the workers so an
agent can resolve an entry by id or keyword and cite the id in findings and
facts. The data files keep their own licenses; the repository's AGPL-3.0
covers the code.

Refs #521.
2026-11-24 01:13:15 +01:00
BaaRai 0c64c3958c Merge pull request #520 from Phantom-IN/feat/scope-wildcard-domains
feat(scope): accept *.example.com in asset scope
2026-11-23 23:54:03 +01:00
BaaRai 1094e9697f Merge pull request #517 from Phantom-IN/fix/install-buildx-preflight
fix(install): check for docker buildx before building the image
2026-11-23 23:53:57 +01:00
BaaRai 6ebb2b3d0a Merge pull request #510 from kalt2212/feat/issue-423-fail-closed-privdrop
fix(server): fail-closed privilege drop and set PR_SET_NO_NEW_PRIVS on linux (#423)
2026-11-23 23:39:58 +01:00
BaaRai e17ab07a8a Merge pull request #499 from NikolayGusev-astra/fix/telemetry-on-and-registration-gap
fix: context telemetry ON by default + counter for proved-but-unregistered intents
2026-11-23 23:39:08 +01:00
BaaRai b1d2d776f8 Merge pull request #508 from thejesh23/fix/email-date-message-id
fix(notify): add Date and Message-ID headers to notification emails
2026-11-23 23:38:38 +01:00
Adrian Martinez Garcia b6748f8ec0 fix(server): lock OS thread and set PR_SET_NO_NEW_PRIVS in shims before exec
PR_SET_NO_NEW_PRIVS is per thread. PrepareExecPrivilege set it on a server thread that never execs, so the flag was not inherited by agent processes. The shims set it in enterExecutor, but runBashShim and runDropShim did not lock their goroutine, so it could migrate between prctl and exec.

Move the prctl out of PrepareExecPrivilege. Lock the thread at the top of runBashShim and runDropShim; the lock is never released because exec replaces the process.

Replace the test with a deterministic one: the drop shim runs as root with GOMAXPROCS=1, and a wrapped setNoNewPrivsFn forces the goroutine off its thread. Without the lock the exec'd program reports NoNewPrivs 0; with it, 1.
2026-11-23 22:28:50 +00:00
BaaRai a37403d1e7 Merge pull request #488 from sresarehumantoo/chore/slog-migration-v2
chore: migrate log.Printf to log/slog in traffic, egress, enrich and evidence
2026-11-23 23:18:08 +01:00
BaaRai deba1d1c7a fix(agent,db): finish the fact-only counter
FactOnlyIntents now returns only terminal intents (done, blocked, exhausted,
stopped), so an open, running or deleted intent is no longer reported as
finished. The summaries go into the planner block inside env.wrap, and the
telemetry docs, the llmrec comment and the db comment match the on-by-default
flag with 0|false|off|no to disable it.
2026-11-23 23:12:41 +01:00
BaaRai fca37610a2 Merge remote-tracking branch 'origin/main' into HEAD 2026-11-23 23:12:37 +01:00
BaaRai a2d011a390 Merge pull request #470 from NikolayGusev-astra/feat/systemone-profile-format
agent: advisory duplicate check on report_finding via a decision model
2026-11-23 23:12:21 +01:00
BaaRai 5ce4e1eae9 Merge branch 'main' into chore/slog-migration-v2 2026-11-23 22:58:53 +01:00
BaaRai 2d39964bac Merge branch 'main' into fix/email-date-message-id 2026-11-23 22:58:51 +01:00
BaaRai d2ccabff98 Merge branch 'main' into feat/systemone-profile-format 2026-11-23 22:58:48 +01:00
Phantom-IN 9d615bb1ec feat(scope): accept *.example.com in asset scope
Bug bounty programs write a domain and its subdomains as *.example.com.
ParseScopeLine rejected that line ("not recognizable as a valid
domain/IP/CIDR"), and the web scope editor rejected it before it reached
the server, so every wildcard line had to be rewritten by hand.

Drop a leading "*." label and store the line as the example.com domain
rule. Company and task scope match assets on their registrable domain, so
that rule already covers the subdomains. The wildcard is accepted only on
a registrable domain: *.api.example.com would store a rule that matches
nothing, so it is rejected along with *.co.uk and *.<IP>.

Step 1 of #519.
2026-11-24 03:28:46 +05:30
BaaRai f3b00d204e Merge pull request #518 from BaaRai/fix/gorilla-websocket-go-2026-6278
fix(deps): bump gorilla/websocket past GO-2026-6278
2026-11-23 22:58:42 +01:00
BaaRai 375b4913ef fix(deps): bump gorilla/websocket past GO-2026-6278
govulncheck reports GO-2026-6278: gorilla/websocket v1.5.3 uses a
cryptographically weak PRNG for the WebSocket mask key. The fix is the
upstream commit d67f41855da4, available as
v1.5.4-0.20240701034025-d67f41855da4, and it is reachable from the capture
proxy through go-mitmproxy and from the log sink path.

Bumps the module and go.sum. govulncheck ./... reports no vulnerabilities,
go build ./... and go test ./traffic pass.
2026-11-23 22:38:54 +01:00
BaaRai 3112fef438 chore(logs): keep the tags and read the slog level
The slog migration dropped the [traffic], [egress], [enrich] and [evidence]
tags, so the logs view lost the badge and the level was guessed from the
message text. Put the tag back in each message and teach parseLog to read the
slog level word (2026/11/23 13:48:50 WARN [traffic] ...) before the tag.

Adds parseLog tests for the real slog line, the level words and the legacy
no-level shape.
2026-11-23 22:25:32 +01:00
BaaRai f58365c83e fix(notify): parse the sender and reject header line breaks
messageIDDomain broke Name <a@example.com> (comment), and a CR or LF in the
from value could start a new header line. Parse the sender with net/mail,
refuse line breaks in From and To, take the Message-ID domain from the parsed
address with a localhost fallback, and use the bare address as the SMTP
envelope sender.

Adds the sender parsing and header tests.
2026-11-23 22:25:14 +01:00
BaaRai c8c6df423c fix(agent): make the triage threshold atomic
The threshold is written by the settings path and read by the report_finding
worker, so a plain float global is a data race. Store the bits in an
atomic.Uint64, restore the default on 0 or negative, and accept 0 in
applyTriageThreshold so a reset takes effect.

Adds a two-goroutine -race test and the Set(0) reset test.
2026-11-23 22:24:53 +01:00
Phantom-IN 0b4a0d135e fix(install): check for docker buildx before building the image
The Dockerfile builds its first stages with FROM --platform=$BUILDPLATFORM,
which only BuildKit understands. When the buildx plugin is missing, Compose
prints "Docker Compose requires buildx plugin to be installed", falls back
to the legacy builder and fails on step 1:

  failed to parse platform : "" is an invalid OS component of ""

Docker Desktop and get.docker.com ship buildx, but Homebrew's docker CLI
(Colima) and some distro docker.io packages do not, so install.sh and
update.sh got all the way to the build before failing with that message.

Check docker buildx version before the build in both scripts and stop with
an install hint. The apt fallback in install_docker_linux also installs the
buildx package now, and the README Docker section names the requirement.
2026-11-24 02:07:28 +05:30
BaaRai 81eafd0856 Merge pull request #516 from gaurav7902/main
ci: add govulncheck job and --security flag to verify.sh
2026-11-23 21:16:42 +01:00
BaaRai 167cf72b09 Merge pull request #481 from Phantom-IN/fix/seed-target-trailing-punctuation
fix(server): seed a goal URL that is followed by punctuation
2026-11-23 21:16:35 +01:00
Adrian Martinez Garcia 528e5230cd fix(server): fail-closed privilege drop and set PR_SET_NO_NEW_PRIVS on linux (#423) 2026-11-23 19:27:26 +00:00
Gaurav Patidar 52a2a6ac87 Added govulncheck to CI and local verification 2026-11-23 20:24:16 +05:30
Phantom-IN 2efc2aca68 fix(server): seed a goal URL that is followed by punctuation
parseTarget pulls the first URL out of the goal with https?://[^\s'"]+,
which keeps any punctuation that follows it. "Assess http://juiceshop:3000."
matches "http://juiceshop:3000.", url.Parse rejects the port, and the seed
logs "could not parse a target host/IP" even though goalGateCheck accepted
the same goal. A dotted host only survived through the domain fallback,
which takes the scheme from the port, and a sentence-final period stayed
in the host.

Trim trailing punctuation before parsing the URL, including full-width
punctuation from pasted text. A closing bracket is trimmed only when the
URL has no matching opener, so a bracketed IPv6 host like http://[::1]
still parses.
2026-11-23 20:09:03 +05:30
BaaRai d235be850e Merge pull request #507 from thejesh23/fix/scheduler-timeout-order
fix(scheduler): fire on_task_timeout for tasks that time out out of id order
2026-11-23 15:26:50 +01:00
Николай Гусев 8e1c88e803 fix(agent,db): counter for intents that proved facts and registered no finding
«Доказал — не зарегистрировал» was measurable all along and nobody measured it:
on the 2026-11-22 run record, 3 runs out of 12 had EVERY fact-producing intent
register nothing (3/3, 3/3, 2/2 intents) — task 8 burned 130 Bash calls in 35
minutes and registered zero findings. Facts carry no "this is a defect" flag, so
the planner is the only place that can turn a fact into a finding; it had no
counter telling it that a finished intent yielded facts and nothing else.

db: FactOnlyIntents(limit) — intents with >=1 fact edge and no finding edge.
agent: the situational block now carries them with the rule (register or say why
not), so the nudge survives seeded agent_prompts (the block is code-owned, not a
template).

limits: FactOnlyIntents limit default 10 - a planner round acts on a handful, the
counter is a nudge and not an inventory
limits: summary truncation 140 chars - one-sentence intent summaries; full text
stays one node_detail away, and the block must not become a second context source

Tests RED first: db test asserts the fact-without-finding intent is picked and the
fact+findings one is not; agent test asserts the block reaches the situational
prompt and does not appear for an empty lookup.
2026-11-23 17:22:35 +03:00
Николай Гусев b708ea6b9a fix(llmrec): context size telemetry ON by default
The llm_context table carries the per-call context breakdown (system, tools,
tool_result, assistant) but was EMPTY on a stand that had already run 15 tasks:
the flag was opt-in and off. Context size was therefore discussed from per-task
token sums, and any fix to it was a guess.

limits: telemetry row 1 per model call - byte counting only, no content kept;
наблюдаемо до ~300 вызовов на прогон, то есть до ~300 строк
limits: disable via explicit falsy value only (0|false|off|no) - the point of the
change is that an unset env means ON

Tests: default-on and explicit-off are both asserted (RED first: the old test
asserted the opposite default).
2026-11-23 17:22:35 +03:00
Николай Гусев a3e44d3f05 agent: close the review blockers on the advisory duplicate check
Fixes the three blockers and three shoulds from the review of #470, rebased
onto current main.

Blocker 1 — no way out of a wrong suppression. The suppression note told the
agent to register a distinct defect again, but report_finding had no override:
the retry hit the same check and was suppressed again. report_finding now takes
force_register, which skips the duplicate check for that call and logs the
override. Covered end to end: suppress, then register with the flag.

Blocker 2 — id mismatch. The suppression answer returned duplicate_of_finding_id
(the findings-table id) while update_finding_report addresses the exploration
NODE. The answer now carries duplicate_of_finding_node_id as well, and the note
names the node id to pass. withNodeID resolves it from the candidates the
question offered, so an id the model was never shown maps to nothing.

Blocker 3 — unguarded HTTP client. SystemOneClient.http() returned a bare client,
so a stored triage profile could point the server at an internal host. The client
is now built by the server under the same endpoint guard as the model-list path:
ARTEX_LLM_PRIVATE_ENDPOINTS allow-list, private and metadata addresses refused,
no proxy, redirects not followed. A refused base_url leaves triage off (fail
open, as every other triage failure). TriageHTTPTimeout is exported so the
injected client uses the same budget instead of a second number.

Should 4 — UTF-8 truncation. capText and buildDuplicateState cut by byte index,
splitting a multi-byte rune on CJK or Cyrillic summaries. Both now cut on a rune
boundary.

Should 5 — settings validation. putSettings accepts and stores any
triage_profile_id and any confidence. Both are validated before anything is
written: a negative or unknown profile id and a threshold outside 0..1 are
rejected with 400; 0 still turns the check off.

Should 6 — the threshold is a setting (triage_min_confidence), read on boot and
on change; the description matches the code.

Verification: go build ./... and go vet clean; gofmt clean. go test ./agent/
./db/ ./llmrec/ ./server/ with ARTEX_PG_DSN on a local PostgreSQL — green except
TestManagerSOCKS5UDPOptInAndAssetBlockRuleDropsDatagram (binds 127.0.0.2) and
TestPauseShiftsTaskDeadlineOnResume, which fail the same way on clean main on
macOS. Red/green: with the force_register branch disabled the override test
fails naming the ignored flag; restored, it passes.
2026-11-23 17:22:16 +03:00
BaaRai 6ec01e007e Merge remote-tracking branch 'origin/main' into pr507b
# Conflicts:
#	CHANGELOG.md
2026-11-23 15:10:58 +01:00
BaaRai 9f0436e272 Merge pull request #503 from Dev-next-gen/fix/archive-skip-fifo
fix(server): skip named pipes and sockets when packing a task archive
2026-11-23 15:10:35 +01:00
Николай Гусев 24cd7da9af agent: advisory duplicate check on report_finding via a decision model
Duplicates are the cheapest way to lose reviewer trust, and the only guard today is
a prompt instruction: the worker is told to check list_findings before registering.
It does not hold — in one run against a deliberately vulnerable app three defect
classes were registered twice each (two SQLi, two IDOR, two admin-endpoint
findings), and one of the pairs differed only in wording.

A decision model answers exactly this kind of closed-list question (same defect as
one of these N findings, or not?) with probabilities and no generated text, so the
judgement costs one small request instead of a main-model turn over a six-figure
context. Measured on our own findings before writing any of this (15 candidates,
hand labels): the correct partner 8/8 on a 27B decider 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. Repeated calls were stable (30/30 identical).

Changes

- agent/triage.go: TriageClient interface, a /v1/systemone HTTP client, and the pure
  pieces (state builder, criteria builder, answer parser, threshold) so the logic is
  testable without a server.
- report_finding: consults the client before registering. On a duplicate above the
  confidence threshold the finding is not registered again; the caller is told which
  finding_id it matched and to extend it with update_finding_report.
- Wiring: agent.SetTriageClient on the worker/planner ToolSets, a triage_profile_id
  setting (any llm_profiles row whose base_url serves the decision contract; 0 = off),
  exposed through the settings API.

Fail-open, by construction

Triage changes an outcome only when it is confident; every other path behaves exactly
as today: no client, no existing findings, empty summary, transport error, non-200,
malformed body, an id the question never offered, or confidence below the threshold
all fall through to normal registration. A wrong suppression loses evidence, a wrong
registration only costs a row — hence the threshold, and hence "advisory".

Verification

- go test ./agent/ passes, including new tests: request shape (model/state/criteria
  carry every candidate), distinct answer, unknown id reads as distinct, probability
  fallback when confidence is absent, error on 500, no HTTP call without input, state
  cap, threshold boundaries.
- red/green on two independent breakages: forcing the threshold false and accepting
  an unoffered id both fail the suite; restored, it passes.
- go test ./server/ shows one failure,
  TestManagerSOCKS5UDPOptInAndAssetBlockRuleDropsDatagram (bind 127.0.0.2 —
  environment), reproduced on clean main in a separate worktree.
- gofmt -l agent/ server/ clean.

Notes

- The profile must serve /v1/systemone. A chat-only decider endpoint (one that refuses
  /v1/chat/completions) needs a thin adapter; a decision endpoint works directly.
- Off by default: with no triage_profile_id the platform behaves as before.

The cap on offered findings is a SELECTION, not "the newest N": with a wide graph
the true partner falls out of a newest-first list, so candidates are ranked by
relevance (same class, overlapping endpoint, another task on a shared asset) with
recency only breaking ties. Per-entry summary capping replaces the whole-state
truncation, which used to cut mid-line and leave criteria ids whose state line had
been dropped.

Threshold is a knob, not a constant (live acceptance): on a run with the wider
cross-task pool the model named the right partner in 8 of 9 questions, but its
confidence moved with the question's width — 0.73-0.79 on a small pool, 0.30-0.53
with twenty candidates. Six duplicates were suppressed, and exactly the two that
slipped were the 0.30 and 0.47 ones, both with the correct partner named. A fixed
0.5 cannot fit both ends, so the threshold is a setting (triage_min_confidence,
default 0.5); the low end is affordable because the suppression result tells the
agent to re-register explicitly when the finding is in fact distinct.

Cross-task pool (found by re-measuring the live miss): task_relations only links
spawned tasks, so two tasks created independently against the same target never see
each other's findings and a defect registered in both is invisible to the dedup
question. FindingsSharingAssets joins on the candidate's own asset ids (jsonb
containment, GIN-served) and adds those findings to the question, marked with their
task. On three real cross-task duplicates the wider question names the right partner
in all three (confidence 0.58-0.73, above the threshold), where the own-task pool
could only answer "none".

Regression note (found on a live run, not in CI): FindingID is filled from the findings table, so building the candidate list straight from the nodes dropped every entry and triage never fired ("nodes=6, no usable existing findings"). Covered by TestTriageCandidates_SkipsNodesWithoutFindingRow; findings inherited from a directly related task are kept and marked in the question.

---

Found while running the platform against a live target.

limits: triageDupMinConfidence 0.5 - калибровка 538 пар одной цели (stage3_calibrate.py, 2026-11-22): recall 1.00 при FP 0.47 на 75 жёстких негативах; на истинных дублях в живом прогоне 0.30-0.79
limits: triageMaxExisting 10 - ширина вопроса на реальном дубле (stage3_width.py, 2026-11-22): уверенность 0.81-0.91 до 11 кандидатов, 0.64 на 19, 0.56 на 29; латентность 0.44->1.29 с
limits: triageMaxSummaryChars 400 - p90 длины сводки 334, максимум 564 по 53 находкам графа (2026-11-22)
limits: triageMaxStateChars 6000 - арифметика при потолке 10 записей: 10*(400+60)+480 ~= 5.1 КБ, запас 1.17x
limits: triageHTTPTimeout 20s - наблюдаемая латентность decider 0.26-1.29 с, 3.83-3.96 с на 27B; запас ~5x к худшему
limits: findings pool query limit 50 - самый широкий пул по ассету 31 находка (53 в графе, 2026-11-22), запас 1.6x
limits: ответ decider 1 MiB - наблюдаемый ответ 0.3-2 КБ, запас ~500x
2026-11-23 16:59:40 +03:00
BaaRai 410d8fa7f2 Merge remote-tracking branch 'origin/main' into pr507b
# Conflicts:
#	CHANGELOG.md
2026-11-23 14:55:14 +01:00
BaaRai 8040e38faf Merge remote-tracking branch 'origin/main' into pr503b
# Conflicts:
#	CHANGELOG.md
2026-11-23 14:54:03 +01:00
thejesh23 ad4c976732 fix(notify): add Date and Message-ID headers to notification emails
buildEmailMessage wrote From, To, Subject and the MIME headers only.
RFC 5322 requires Date and says every message should have a Message-ID.
Not every submission server adds them, and receiving filters penalize
mail without them.

Add the send time and a random Message-ID on the sender's domain.
2026-11-23 01:34:25 -08:00
thejesh23 1aaa7a479b fix(scheduler): fire on_task_timeout for tasks that time out out of id order
The timeout trigger used the task id as a watermark, but tasks time out
in deadline order. When a newer task timed out first, the watermark moved
past every older running task, so their later timeouts were never fired.

Keep fired timeouts in a persisted set, the same way met goals are
tracked. On first start the set is seeded with the tasks already timed
out, so nothing replays.
2026-11-23 01:33:19 -08:00
Leo Camus b7e766ffe4 fix(server): skip named pipes and sockets when packing a task archive
writeTaskArchivePackage opened every entry of the staged workspace that is
not a directory. Opening a FIFO blocks until a writer appears, so a named
pipe left by a command (mkfifo backpipe for an nc relay) stopped the single
archive worker in openat for good, with the task files already moved to
staging and every later archive, restore and delete job queued behind it.
A Unix socket failed the archive instead, and a device file was packed but
refused by extractTaskArchivePackage on restore.

Skip every entry that is neither a directory nor a regular file, as is
already done for symlinks.
2026-11-23 04:34:29 +00:00
SREsAreHumanToo 10afb2e79a chore: migrate log.Printf to slog in traffic/, egress/, enrich/ and evidence/
Replace every log.Printf/log.Print call with structured slog equivalents
and swap the "log" import for "log/slog". Update test assertions that
matched the old format strings.
2026-11-22 18:27:47 -05:00
81 changed files with 23401 additions and 171 deletions
+1 -1
View File
@@ -4,7 +4,7 @@ web/.next
web/out
server/webui/dist
/artex
data
/data
keys
backups
.env
+12
View File
@@ -116,6 +116,18 @@ jobs:
# service, so parallel package runs delete each other's rows.
- run: go test -p 1 ./...
govulncheck:
runs-on: ubuntu-latest
permissions:
contents: read
steps:
# The official action uses the Go version declared by go.mod and reports
# only vulnerabilities reachable from this module's packages.
- uses: golang/govulncheck-action@v1
with:
go-version-file: go.mod
go-package: ./...
shell:
runs-on: ubuntu-latest
steps:
+8 -1
View File
@@ -6,12 +6,19 @@ All notable changes to this project are documented in this file. The format is b
### Added
- **Pentest knowledge pack**: the planner and the workers can call a read-only `knowledge_lookup` tool to resolve a MITRE ATT&CK technique, an OWASP WSTG test or a CWE weakness by id or keyword, and cite the id in findings and facts. The pack is generated from the official sources by `scripts/knowledge/build.py`, with the source URL, license, retrieval date and source SHA-256 recorded, keeps its own licenses in `knowledge/NOTICE` and `knowledge/licenses`, and is embedded in the binary, so no network is needed at runtime. Descriptions are capped and each entry carries the canonical URL (#521).
- **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).
- **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
- **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.
- **Task form does not keep test-account secrets on screen**: after a task is created the credential rows are cleared, and the password field is masked.
- **LLM connection-test logs stay one line**: the response body written by a connection test has CR and LF replaced with spaces before it is logged, so the body cannot start a second log record.
- **Benchmark judge validation**: grading and the judge's falsification battery require one verdict per ground-truth ID, actual boolean decisions and gates, and matches to the supplied scanner findings. Invalid grading responses use the existing three-attempt budget and abort without writing scores, rather than counting duplicate IDs or truthy strings such as `"false"`.
@@ -305,7 +312,7 @@ Ollama support, a setup token for the first-run claim, secret scrubbing for chil
- **The build context includes local secrets**: `.dockerignore` does not exclude `.env`, `config.json` or `jwt.key`, so the build stage's `COPY . .` puts them in a build-stage layer of the local builder cache. They are not copied into the final image.
- **Image supply chain**: the recon tools are downloaded at pinned versions but not checksum-verified, sqlmap tracks its default branch, and the Playwright packages are installed at `@latest`. Draft #127 proposes checksum verification.
- **No Docker image is published for this release**: the release workflow's `docker` job only runs when `DOCKERHUB_ENABLED` is set, and it still downloads prebuilt binaries into `dist/` that the Dockerfile no longer uses. Build the image from the checkout with `docker compose up -d --build`.
- **CI gaps**: `./server` is not run under `-race`; there is no `govulncheck` step and no `docker build` job. Four tests skip themselves (fresh-database or timing failures, see #9).
- **CI gaps**: there is no `docker build` job. Four tests skip themselves (fresh-database or timing failures, see #9).
- **Reported and not fixed in this release**: `list_task_credentials` emits an invalid `"required": [""]` schema that strict LLM providers reject (#130), and the MCP Streamable HTTP client fails against servers that only support protocol version 2025-11-25 (#131; fix proposed in #132).
## [0.4.0] - 2026-10-23
+1 -1
View File
@@ -158,7 +158,7 @@ RUN set -eux; \
test "$count" -gt 10000
# ---------------------------------------------------------------- runtime ---
FROM python:3.15-slim-bookworm@sha256:96599df822d0e1c6bb700014a05c7f3c8cabc6e0f7ff3c4f9f69cee033b4b5d9
FROM python:3.12-slim-bookworm@sha256:935c3c5b12357a7e10caa9c1e6ca5692344d97cf229832ef584be2cec9fc03df
ARG TARGETARCH
# Common tools: ripgrep / curl / vim, plus a set of recon staples (add/remove as needed).
RUN apt-get update && apt-get install -y --no-install-recommends \
+8 -1
View File
@@ -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,
@@ -871,7 +877,8 @@ CGO_ENABLED=0 go build -tags embedui -o artex ./cmd/artex
- Backend: `go run ./cmd/artex` (without `-tags embedui`, the frontend is not embedded)
- Frontend: `cd web && npm run dev` (`/api` is reverse-proxied to the backend, with hot reload)
- Tests: `go test ./...`
- Reproduce all CI checks locally: `./scripts/verify.sh` (add `--full` for `-race` and the static web build)
- Reproduce the fast CI checks locally: `./scripts/verify.sh` (add `--full` for `-race` and the static web build; add `--security` for `govulncheck`)
- Security scan: install `govulncheck` and run `./scripts/verify.sh --security` (CI runs this on every push and pull request)
- Mock preview (no backend): `cd web && NEXT_PUBLIC_MOCK=1 npm run dev`
---
+39
View File
@@ -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)
}
}
+49
View File
@@ -0,0 +1,49 @@
package agent
import (
"context"
"encoding/json"
"strings"
"github.com/Autumn-27/artex/knowledge"
actool "github.com/Autumn-27/norma/tool"
)
// knowledgeLookup is a read-only taxonomy lookup shared by the planner and the
// workers. It has no task store dependency: the pack is embedded in the binary.
func (t *ToolSet) knowledgeLookup() actool.CoreTool {
return readTool("knowledge_lookup",
"Look up a stable security taxonomy entry by id or keyword. Sources: attack (MITRE ATT&CK technique), wstg (OWASP Web Security Testing Guide test), cwe (MITRE Common Weakness Enumeration). Use it to choose a test or technique while planning, or to cite an id when reporting a finding or fact. Returns id, name, category, a capped description and the canonical url; truncated=true means the full text is at the url. Read-only.",
obj(map[string]any{
"source": str("taxonomy to search: attack, wstg or cwe"),
"query": str("entry id (for example T1190, WSTG-ATHN-01, CWE-79) or keywords"),
"limit": intp("maximum matches, default 5, max 20"),
}, "source", "query"),
knowledgeLookupRun)
}
func knowledgeLookupRun(_ context.Context, in json.RawMessage) (actool.Result, error) {
var a struct {
Source string `json:"source"`
Query string `json:"query"`
Limit int `json:"limit"`
}
if err := json.Unmarshal(in, &a); err != nil {
return actool.Errorf("invalid input: " + err.Error()), nil
}
pack, err := knowledge.Default()
if err != nil {
return actool.Errorf(err.Error()), nil
}
source := strings.ToLower(strings.TrimSpace(a.Source))
matches, total, err := pack.Search(source, a.Query, a.Limit)
if err != nil {
return actool.Errorf(err.Error()), nil
}
return jsonResult(map[string]any{
"source": source,
"query": strings.TrimSpace(a.Query),
"matches": matches,
"total": total,
})
}
+90
View File
@@ -0,0 +1,90 @@
package agent
import (
"encoding/json"
"strings"
"testing"
)
func TestKnowledgeLookupRunExactID(t *testing.T) {
res, err := knowledgeLookupRun(t.Context(), json.RawMessage(`{"source":"attack","query":"T1190"}`))
if err != nil {
t.Fatalf("run: %v", err)
}
if res.IsError {
t.Fatalf("unexpected tool error: %s", res.Flatten())
}
out := res.Flatten()
for _, want := range []string{`"T1190"`, "Exploit Public-Facing Application", "attack.mitre.org"} {
if !strings.Contains(out, want) {
t.Errorf("output missing %q: %s", want, out)
}
}
}
func TestKnowledgeLookupRunKeyword(t *testing.T) {
res, err := knowledgeLookupRun(t.Context(), json.RawMessage(`{"source":"wstg","query":"default credentials","limit":3}`))
if err != nil {
t.Fatalf("run: %v", err)
}
if res.IsError {
t.Fatalf("unexpected tool error: %s", res.Flatten())
}
if !strings.Contains(res.Flatten(), "WSTG-ATHN-01") {
t.Errorf("output does not contain WSTG-ATHN-01: %s", res.Flatten())
}
}
func TestKnowledgeLookupRunLimitIsClamped(t *testing.T) {
res, err := knowledgeLookupRun(t.Context(), json.RawMessage(`{"source":"cwe","query":"data","limit":100}`))
if err != nil {
t.Fatalf("run: %v", err)
}
if res.IsError {
t.Fatalf("unexpected tool error: %s", res.Flatten())
}
var out struct {
Matches []map[string]any `json:"matches"`
Total int `json:"total"`
}
if err := json.Unmarshal([]byte(res.Flatten()), &out); err != nil {
t.Fatalf("decode: %v", err)
}
if len(out.Matches) > 20 {
t.Fatalf("matches = %d, want at most 20", len(out.Matches))
}
if out.Total <= len(out.Matches) {
t.Fatalf("total = %d, matches = %d", out.Total, len(out.Matches))
}
}
func TestKnowledgeLookupRunErrors(t *testing.T) {
cases := []struct {
name, in, want string
}{
{"unknown source", `{"source":"nope","query":"x"}`, "unknown knowledge source"},
{"empty query", `{"source":"attack","query":" "}`, "query is required"},
{"invalid json", `{`, "invalid input"},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
res, err := knowledgeLookupRun(t.Context(), json.RawMessage(c.in))
if err != nil {
t.Fatalf("run: %v", err)
}
if !res.IsError || !strings.Contains(res.Flatten(), c.want) {
t.Fatalf("result = %q (isError=%v), want error containing %q", res.Flatten(), res.IsError, c.want)
}
})
}
}
func TestKnowledgeLookupToolIsReadOnly(t *testing.T) {
tool := (&ToolSet{}).knowledgeLookup()
if tool.Name() != "knowledge_lookup" {
t.Fatalf("name = %q", tool.Name())
}
if !tool.IsReadOnly(nil) {
t.Fatal("tool is not read-only")
}
}
+44 -1
View File
@@ -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 {
+34 -1
View File
@@ -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)
@@ -2534,7 +2567,7 @@ func (t *ToolSet) listWorkerTraces() actool.CoreTool {
// PlannerTools is the read + intent-generation + goal-judgement tool set.
func (t *ToolSet) PlannerTools() []actool.CoreTool {
return []actool.CoreTool{
t.graphOverview(), t.listFindings(), t.listFacts(), t.nodeDetail(),
t.graphOverview(), t.listFindings(), t.listFacts(), t.nodeDetail(), t.knowledgeLookup(),
// cold-digest §6.1: restore folded cold nodes (digest body → members → detail).
t.expandDigest(),
t.getWorkerOutput(), t.getWorkerTrace(), t.searchAllWorkerTraces(), t.listGoals(), t.addIntent(), t.proveGoal(), t.goalMet(),
+3
View File
@@ -711,6 +711,9 @@ func (t *ToolSet) WorkerTools() []actool.CoreTool {
// node_detail: once a worker has an intent_id/node id, it can look up that node's
// full detail (pairs with the review above).
t.nodeDetail(),
// knowledge_lookup: cite a stable ATT&CK/WSTG/CWE id when reporting a
// finding or a fact, or look up a test while executing an intent.
t.knowledgeLookup(),
// The following tools are still [not given] to workers, reserved for
// planner/main (reading context, cross-work retrospection are planning duties; a
// worker only executes and writes back its single intent):
+500
View File
@@ -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 ""
}
+113
View File
@@ -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)
}
}
+92
View File
@@ -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)
}
}
+310
View File
@@ -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
View File
@@ -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
View File
@@ -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 {
+68
View File
@@ -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)
}
}
+54
View File
@@ -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.
+140
View File
@@ -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)
}
}
}
+71
View File
@@ -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
View File
@@ -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"`
+7 -6
View File
@@ -189,13 +189,14 @@ ORDER BY n.id`, lastID)
return out, rows.Err()
}
// TimedOutTasksSince returns tasks that reached status='timeout' with id > lastID,
// ordered by id (monotonic watermark → no double-fire across restarts).
func (d *DB) TimedOutTasksSince(lastID int64) ([]TaskEvent, error) {
// TimedOutTasks returns all live tasks in status='timeout', ordered by id. Tasks
// time out in deadline order, not id order, so the scheduler filters out the
// ones it already fired for via its persisted fired-set, not an id watermark.
func (d *DB) TimedOutTasks() ([]TaskEvent, error) {
rows, err := d.Query(`
SELECT id, description, goal FROM tasks
WHERE status='timeout' AND deleted_at IS NULL AND id > $1
ORDER BY id`, lastID)
WHERE status='timeout' AND deleted_at IS NULL
ORDER BY id`)
if err != nil {
return nil, err
}
@@ -206,7 +207,7 @@ ORDER BY id`, lastID)
if err := rows.Scan(&e.NodeID, &e.TaskDesc, &e.TaskGoal); err != nil {
return nil, err
}
e.TaskID = e.NodeID // task id doubles as NodeID for the watermark
e.TaskID = e.NodeID // task id doubles as NodeID for the fired-set
e.Summary = e.TaskGoal
out = append(out, e)
}
+4 -4
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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)
}
}
}
+1 -1
View File
@@ -12,7 +12,7 @@ require (
github.com/aws/aws-sdk-go-v2/service/s3 v1.114.6
github.com/golang-jwt/jwt/v5 v5.3.1
github.com/google/uuid v1.6.0
github.com/gorilla/websocket v1.5.3
github.com/gorilla/websocket v1.5.4-0.20240701034025-d67f41855da4
github.com/jackc/pgx/v5 v5.10.0
github.com/klauspost/compress v1.20.2
github.com/lqqyt2423/go-mitmproxy v1.9.2
+2 -2
View File
@@ -67,8 +67,8 @@ github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/gorilla/css v1.0.1 h1:ntNaBIghp6JmvWnxbZKANoLyuXTPZ4cAMlo6RyhlbO8=
github.com/gorilla/css v1.0.1/go.mod h1:BvnYkspnSzMmwRK+b8/xgNPLiIuNZr6vbZBTPQ2A3b0=
github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=
github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
github.com/gorilla/websocket v1.5.4-0.20240701034025-d67f41855da4 h1:PYKzliEgITjLJoJqbV90S0YRaG8LNAsICH6fp6MApC0=
github.com/gorilla/websocket v1.5.4-0.20240701034025-d67f41855da4/go.mod h1:r4w70xmWCQKmi1ONH4KIaBptdivuRPyosB9RmPlGEwA=
github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k=
github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM=
github.com/hinshun/vt10x v0.0.0-20220301184237-5011da428d02 h1:AgcIVYPa6XJnU3phs104wLj8l5GEththEw6+F79YsIY=
+18
View File
@@ -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
+2
View File
@@ -29,6 +29,8 @@ var noTargetTools = toolSet(
"insert_assets", "add_company_scope", "add_task_scope", "list_assets",
"list_untested_assets", "list_companies", "report_finding", "record_fact",
"save_task_credential", "list_task_credentials", "ingest_bbot", "ingest_scan_output", "record_coverage",
// taxonomy lookup: the input is an id or a keyword, never a connection
"knowledge_lookup",
// cross-task orchestration, findings and retests (server)
"list_tasks", "list_llm_profiles", "spawn_task", "pause_task", "get_task_graph",
"list_task_findings", "add_task_hint", "get_task_worker_trace",
+27
View File
@@ -0,0 +1,27 @@
Knowledge pack attribution
The files under knowledge/data/ are generated from the sources below and are
distributed under their own terms. They are not covered by the repository's
AGPL-3.0 license.
MITRE ATT&CK
Copyright © 2026 The MITRE Corporation. This work is reproduced and
distributed with the permission of The MITRE Corporation.
License: knowledge/licenses/ATTACK-LICENSE.txt
Source: https://github.com/mitre-attack/attack-stix-data
OWASP Web Security Testing Guide
Copyright © OWASP Foundation. Licensed under CC-BY-SA-4.0.
Changes: descriptions are shortened for tool output; ids, names and
references are unchanged.
License: knowledge/licenses/WSTG-LICENSE.txt
Source: https://github.com/OWASP/wstg
MITRE CWE
Copyright © 2006-2026 The MITRE Corporation. This work is reproduced and
distributed with the permission of The MITRE Corporation.
Terms: knowledge/licenses/CWE-TERMS.txt
Source: https://cwe.mitre.org/data/csv/1000.csv
The canonical text and the full license terms are at the URL in each entry and
in knowledge/licenses/.
+63
View File
@@ -0,0 +1,63 @@
# Knowledge pack
Small, versioned security taxonomy pack embedded in the ARTEX binary. It gives
the planner and the workers stable identifiers to plan against and to cite in
findings and facts:
- **attack**: MITRE ATT&CK Enterprise techniques (706 entries).
- **wstg**: OWASP Web Security Testing Guide tests (133 entries).
- **cwe**: MITRE Common Weakness Enumeration weaknesses (956 entries).
Each entry carries an id, a name, a category (tactics, WSTG category or CWE
abstraction), a short description capped by the build script, a `truncated` flag
when the description was cut, and the canonical URL.
## Sources and licenses
The data files are generated from the official sources and keep their own
licenses. They are not covered by the repository's AGPL-3.0 license.
| source | license | source |
|---|---|---|
| attack | MITRE ATT&CK Terms of Use | https://github.com/mitre-attack/attack-stix-data |
| wstg | CC-BY-SA-4.0 | https://github.com/OWASP/wstg |
| cwe | MITRE CWE Terms of Use | https://cwe.mitre.org/data/csv/1000.csv |
See [NOTICE](NOTICE) and [licenses/](licenses/) for the attribution and the
license texts. The WSTG descriptions are shortened; IDs, names and references
are unchanged.
## Files
- `data/attack.json`, `data/wstg.json`, `data/cwe.json`: the embedded entries.
- `data/sources.json`: source URL, license, retrieval date, source SHA-256 and
entry count for each file.
- `licenses/`: the license texts.
- `../scripts/knowledge/build.py`: the generator.
## Rebuilding
```sh
python3 scripts/knowledge/build.py
```
The script downloads the official sources, rewrites the three JSON files and
`sources.json`, and refreshes the license files. The generated data is committed
so the binary needs no network at runtime. Review the diff before committing:
the result is a new pack version.
## How it is used
The read-only `knowledge_lookup` tool is available to the planner and the
workers. It accepts a `source`, a `query` (an id such as `T1190`,
`WSTG-ATHN-01`, `CWE-79`, or keywords) and an optional `limit` (default 5, max
20), and returns the matching entries. It reads the embedded pack, never the
network.
## What it is not
- Not a training corpus, not a fine-tuning dataset, not a RAG dump.
- No exploit code, no scraped lab writeups, no vendor-specific material.
- Not the place for dynamic feeds (CISA KEV, NVD, OSV). Those change daily and
belong to a fetch-at-runtime layer, not to a committed pack.
- Descriptions are capped for tool output; open the entry URL for the full text.
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+38
View File
@@ -0,0 +1,38 @@
{
"generated_at": "2026-11-24",
"sources": [
{
"source": "attack",
"title": "MITRE ATT&CK Enterprise",
"license": "MITRE ATT&CK Terms of Use",
"license_url": "https://raw.githubusercontent.com/mitre-attack/attack-stix-data/master/LICENSE.txt",
"source_url": "https://raw.githubusercontent.com/mitre-attack/attack-stix-data/master/enterprise-attack/enterprise-attack.json",
"retrieved_at": "2026-11-24",
"sha256": "539a843a7b53ed9749740b2123dddae3726b1a4831841c32aca740b011b910b5",
"entries": 706,
"data_file": "data/attack.json"
},
{
"source": "wstg",
"title": "OWASP Web Security Testing Guide",
"license": "CC-BY-SA-4.0",
"license_url": "https://raw.githubusercontent.com/OWASP/wstg/master/LICENSE",
"source_url": "https://raw.githubusercontent.com/OWASP/wstg/master/checklists/checklist.json",
"retrieved_at": "2026-11-24",
"sha256": "c87aaa4566b6dae46e217b2630eb0c4eed9ff8317d094bc9dd2a22e8c19cb21c",
"entries": 133,
"data_file": "data/wstg.json"
},
{
"source": "cwe",
"title": "MITRE Common Weakness Enumeration",
"license": "MITRE CWE Terms of Use",
"license_url": "https://cwe.mitre.org/about/termsofuse.html",
"source_url": "https://cwe.mitre.org/data/csv/1000.csv",
"retrieved_at": "2026-11-24",
"sha256": "b3b8fc1bb6e2398ce4f1a7b0f5f74949f6cd568a26190d203e1103c3aafa6ff5",
"entries": 956,
"data_file": "data/cwe.json"
}
]
}
File diff suppressed because it is too large Load Diff
+242
View File
@@ -0,0 +1,242 @@
// Package knowledge embeds a small, attributed security taxonomy pack used by
// the planner and worker tools. The pack is generated from the official sources
// by scripts/knowledge/build.py; it is not a training corpus and contains no
// scraped lab material.
package knowledge
import (
"embed"
"encoding/json"
"fmt"
"sort"
"strings"
"sync"
)
//go:embed data/attack.json data/wstg.json data/cwe.json
var dataFS embed.FS
// Entry is one taxonomy record. Descriptions are capped by the build script;
// Truncated marks that the full text is at URL.
type Entry struct {
ID string `json:"id"`
Name string `json:"name"`
Category []string `json:"category,omitempty"`
Status string `json:"status,omitempty"`
Description string `json:"description,omitempty"`
Truncated bool `json:"truncated,omitempty"`
URL string `json:"url,omitempty"`
}
// SourceInfo describes one embedded source. The data files keep their own
// licenses; see knowledge/NOTICE and knowledge/licenses.
type SourceInfo struct {
Source string `json:"source"`
Title string `json:"title"`
License string `json:"license"`
LicenseURL string `json:"license_url"`
SourceURL string `json:"source_url"`
RetrievedAt string `json:"retrieved_at"`
Entries int `json:"entries"`
}
type source struct {
info SourceInfo
entries []Entry
byID map[string]int
}
// Pack is the loaded knowledge pack.
type Pack struct {
sources map[string]*source
names []string
}
var (
defaultOnce sync.Once
defaultPack *Pack
defaultErr error
)
// Default returns the embedded pack, loading it once. A malformed embedded pack
// is a build error, not a runtime condition; the error is returned so a caller
// can fail at startup.
func Default() (*Pack, error) {
defaultOnce.Do(func() { defaultPack, defaultErr = Load() })
return defaultPack, defaultErr
}
// Load parses the embedded sources. It is exported for tests and for callers
// that want to fail before the first lookup.
func Load() (*Pack, error) {
p := &Pack{sources: map[string]*source{}}
for _, name := range []string{"attack", "wstg", "cwe"} {
raw, err := dataFS.ReadFile("data/" + name + ".json")
if err != nil {
return nil, fmt.Errorf("knowledge: read %s: %w", name, err)
}
var file struct {
Source string `json:"source"`
Title string `json:"title"`
License string `json:"license"`
LicenseURL string `json:"license_url"`
SourceURL string `json:"source_url"`
RetrievedAt string `json:"retrieved_at"`
Entries []Entry `json:"entries"`
}
if err := json.Unmarshal(raw, &file); err != nil {
return nil, fmt.Errorf("knowledge: parse %s: %w", name, err)
}
if file.Source != name {
return nil, fmt.Errorf("knowledge: %s.json declares source %q", name, file.Source)
}
if len(file.Entries) == 0 {
return nil, fmt.Errorf("knowledge: %s has no entries", name)
}
s := &source{
info: SourceInfo{
Source: file.Source,
Title: file.Title,
License: file.License,
LicenseURL: file.LicenseURL,
SourceURL: file.SourceURL,
RetrievedAt: file.RetrievedAt,
Entries: len(file.Entries),
},
entries: file.Entries,
byID: make(map[string]int, len(file.Entries)),
}
for i, e := range file.Entries {
id := strings.ToUpper(strings.TrimSpace(e.ID))
if id == "" || strings.TrimSpace(e.Name) == "" {
return nil, fmt.Errorf("knowledge: %s has an entry without id or name", name)
}
if _, exists := s.byID[id]; exists {
return nil, fmt.Errorf("knowledge: %s has duplicate id %s", name, id)
}
s.byID[id] = i
}
p.sources[name] = s
p.names = append(p.names, name)
}
sort.Strings(p.names)
return p, nil
}
// SourceNames returns the embedded source names in stable order.
func (p *Pack) SourceNames() []string {
if p == nil {
return nil
}
out := make([]string, len(p.names))
copy(out, p.names)
return out
}
// SourceInfo returns the metadata for one source.
func (p *Pack) SourceInfo(name string) (SourceInfo, bool) {
if p == nil {
return SourceInfo{}, false
}
s, ok := p.sources[strings.ToLower(strings.TrimSpace(name))]
if !ok {
return SourceInfo{}, false
}
return s.info, true
}
// Lookup returns the entry with the exact id in one source.
func (p *Pack) Lookup(source, id string) (Entry, bool) {
if p == nil {
return Entry{}, false
}
s, ok := p.sources[strings.ToLower(strings.TrimSpace(source))]
if !ok {
return Entry{}, false
}
i, ok := s.byID[strings.ToUpper(strings.TrimSpace(id))]
if !ok {
return Entry{}, false
}
return s.entries[i], true
}
// Search returns up to limit matches for query in one source and the total
// number of matches before the limit. An exact id wins and returns one entry.
func (p *Pack) Search(source, query string, limit int) ([]Entry, int, error) {
if p == nil {
return nil, 0, fmt.Errorf("knowledge pack is not loaded")
}
s, ok := p.sources[strings.ToLower(strings.TrimSpace(source))]
if !ok {
return nil, 0, fmt.Errorf("unknown knowledge source %q (valid: %s)", source, strings.Join(p.names, ", "))
}
q := strings.TrimSpace(query)
if q == "" {
return nil, 0, fmt.Errorf("query is required")
}
if i, ok := s.byID[strings.ToUpper(q)]; ok {
return []Entry{s.entries[i]}, 1, nil
}
tokens := strings.Fields(strings.ToLower(q))
if len(tokens) == 0 {
return nil, 0, fmt.Errorf("query is required")
}
type hit struct {
entry Entry
score int
}
hits := make([]hit, 0, 16)
lowerQuery := strings.ToLower(q)
for _, e := range s.entries {
hay := strings.ToLower(strings.Join([]string{
e.ID, e.Name, strings.Join(e.Category, " "), e.Status, e.Description,
}, " "))
if !containsAll(hay, tokens) {
continue
}
score := 1
name := strings.ToLower(e.Name)
id := strings.ToLower(e.ID)
switch {
case strings.HasPrefix(name, lowerQuery):
score += 4
case strings.Contains(name, lowerQuery):
score += 3
}
if strings.HasPrefix(id, strings.ToUpper(q)) {
score += 2
}
hits = append(hits, hit{entry: e, score: score})
}
sort.SliceStable(hits, func(i, j int) bool {
if hits[i].score != hits[j].score {
return hits[i].score > hits[j].score
}
return hits[i].entry.ID < hits[j].entry.ID
})
total := len(hits)
if limit <= 0 {
limit = 5
}
if limit > 20 {
limit = 20
}
if len(hits) > limit {
hits = hits[:limit]
}
out := make([]Entry, len(hits))
for i := range hits {
out[i] = hits[i].entry
}
return out, total, nil
}
func containsAll(hay string, tokens []string) bool {
for _, token := range tokens {
if !strings.Contains(hay, token) {
return false
}
}
return true
}
+138
View File
@@ -0,0 +1,138 @@
package knowledge
import (
"strings"
"testing"
)
func load(t *testing.T) *Pack {
t.Helper()
p, err := Load()
if err != nil {
t.Fatalf("Load: %v", err)
}
return p
}
func TestLoadSources(t *testing.T) {
p := load(t)
names := p.SourceNames()
if len(names) != 3 {
t.Fatalf("sources = %v, want attack, cwe, wstg", names)
}
want := map[string]int{"attack": 600, "wstg": 100, "cwe": 900}
for _, name := range names {
info, ok := p.SourceInfo(name)
if !ok {
t.Fatalf("SourceInfo(%q) missing", name)
}
if info.Entries < want[name] {
t.Errorf("%s entries = %d, want at least %d", name, info.Entries, want[name])
}
if info.License == "" || info.SourceURL == "" || info.RetrievedAt == "" {
t.Errorf("%s metadata incomplete: %+v", name, info)
}
}
}
func TestLookupExact(t *testing.T) {
p := load(t)
cases := []struct {
source, id, name string
}{
{"attack", "T1190", "Exploit Public-Facing Application"},
{"wstg", "WSTG-ATHN-01", "Default Credentials"},
{"cwe", "CWE-79", "Improper Neutralization of Input During Web Page Generation"},
}
for _, c := range cases {
e, ok := p.Lookup(c.source, c.id)
if !ok {
t.Fatalf("%s %s not found", c.source, c.id)
}
if e.Name != c.name {
t.Errorf("%s name = %q, want %q", c.id, e.Name, c.name)
}
if e.URL == "" {
t.Errorf("%s has no url", c.id)
}
}
}
func TestLookupIsCaseInsensitiveAndTrimmed(t *testing.T) {
p := load(t)
for _, id := range []string{"t1190", " T1190 ", "T1190"} {
if _, ok := p.Lookup("ATTACK", id); !ok {
t.Errorf("Lookup(ATTACK, %q) not found", id)
}
}
}
func TestSearchKeyword(t *testing.T) {
p := load(t)
matches, total, err := p.Search("wstg", "default credentials", 5)
if err != nil {
t.Fatalf("Search: %v", err)
}
if total == 0 || len(matches) == 0 {
t.Fatal("no matches for default credentials")
}
if matches[0].ID != "WSTG-ATHN-01" {
t.Errorf("first match = %s, want WSTG-ATHN-01", matches[0].ID)
}
}
func TestSearchExactIDWins(t *testing.T) {
p := load(t)
matches, total, err := p.Search("cwe", "cwe-79", 5)
if err != nil {
t.Fatalf("Search: %v", err)
}
if total != 1 || len(matches) != 1 || matches[0].ID != "CWE-79" {
t.Fatalf("matches=%v total=%d, want one CWE-79", matches, total)
}
}
func TestSearchLimit(t *testing.T) {
p := load(t)
matches, total, err := p.Search("cwe", "data", 2)
if err != nil {
t.Fatalf("Search: %v", err)
}
if len(matches) != 2 {
t.Fatalf("len(matches) = %d, want 2", len(matches))
}
if total <= 2 {
t.Fatalf("total = %d, want more than the limit", total)
}
matches, _, err = p.Search("cwe", "data", 100)
if err != nil {
t.Fatalf("Search: %v", err)
}
if len(matches) > 20 {
t.Fatalf("limit was not clamped: %d", len(matches))
}
}
func TestSearchErrors(t *testing.T) {
p := load(t)
if _, _, err := p.Search("nope", "x", 5); err == nil || !strings.Contains(err.Error(), "unknown knowledge source") {
t.Fatalf("unknown source error = %v", err)
}
if _, _, err := p.Search("attack", " ", 5); err == nil || !strings.Contains(err.Error(), "query is required") {
t.Fatalf("empty query error = %v", err)
}
}
func TestEveryEntryHasNameAndURL(t *testing.T) {
p := load(t)
for _, name := range p.SourceNames() {
for _, e := range p.sources[name].entries {
if strings.TrimSpace(e.ID) == "" || strings.TrimSpace(e.Name) == "" {
t.Fatalf("%s has an entry without id or name: %+v", name, e)
}
if strings.TrimSpace(e.URL) == "" {
t.Fatalf("%s %s has no url", name, e.ID)
}
}
}
}
+20
View File
@@ -0,0 +1,20 @@
License
-------
The MITRE Corporation (MITRE) hereby grants you a non-exclusive, royalty-free license to use ATT&CK® for research,
development, and commercial purposes. Any copy you make for such purposes is authorized provided that you reproduce
MITRE's copyright designation and this license in any such copy.
"© 2026 The MITRE Corporation. This work is reproduced and distributed with the permission of The MITRE Corporation."
Disclaimers
-----------
MITRE does not claim ATT&CK enumerates all possibilities for the types of actions and behaviors documented as part
of its adversary model and framework of techniques. Using the information contained within ATT&CK to address or cover
full categories of techniques will not guarantee full defensive coverage as there may be undisclosed techniques or
variations on existing techniques not documented by ATT&CK.
ALL DOCUMENTS AND THE INFORMATION CONTAINED THEREIN ARE PROVIDED ON AN "AS IS" BASIS AND THE CONTRIBUTOR, THE
ORGANIZATION HE/SHE REPRESENTS OR IS SPONSORED BY (IF ANY), THE MITRE CORPORATION, ITS BOARD OF TRUSTEES, OFFICERS,
AGENTS, AND EMPLOYEES, DISCLAIM ALL WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTY THAT
THE USE OF THE INFORMATION THEREIN WILL NOT INFRINGE ANY RIGHTS OR ANY IMPLIED WARRANTIES OF MERCHANTABILITY OR
FITNESS FOR A PARTICULAR PURPOSE.
+282
View File
@@ -0,0 +1,282 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<?xml version="1.0"?>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<meta name="description" content="Common Weakness Enumeration (CWE) is a list of software and hardware weaknesses." />
<meta http-equiv="X-UA-Compatible" content="IE=Edge">
<link rel="shortcut icon" href="/favicon.ico" />
<link href="/css/main.css?version=5.0.102726" rel="stylesheet" type="text/css" />
<link href="/css/custom.css" rel="stylesheet" type="text/css" />
<!--[if IE]>
<link rel="stylesheet" type="text/css" href="/css/ie.css?version=1.7" />
<![endif]-->
<script src="/includes/custom_filter.js" language="JavaScript" type="text/javascript"></script>
<script src="/includes/browserheight.js" language="JavaScript" type="text/javascript"></script>
<script src="/includes/jquery.js" language="JavaScript" type="text/javascript"></script>
<script src="/includes/cwe_minimizer.js?version=4.12.062923" language="JavaScript" type="text/javascript"></script>
<script src="/includes/cookie.js?version=4.12.062923" language="Javascript" type="text/javascript"></script>
<script src="/includes/includeglossarydef.js" language="JavaScript" type="text/javascript"></script>
<script src="/includes/custom.js" language="JavaScript" type="text/javascript"></script>
<script src=https://cmp.osano.com/AzyhULTdPkqmy4aDN/318aa814-0420-45bb-857d-8fb5fac33ff8/osano.js></script>
<link href="/css/print.css?version=1.11" rel="stylesheet" media="print" type="text/css" />
<link href="/css/mappingonly.css" rel="stylesheet" type="text/css" />
<noscript>
<style type="text/css">
#script { visibility:collapse; visibility:hidden; font-size:0px; height:0px; width:0px }
#noscript { visibility:visible; font-size:inherit; height:inherit; width:inherit}
</style>
</noscript>
<title>CWE -
Terms of Use</title>
</head>
<body onload="onloadCookie()">
<a name="top" id="top"></a>
<div id="MastHead" style="width:100%">
<div style="width:62%;float:left;padding-top:15px;padding-left:10px;padding-bottom:2px;">
<a href="/index.html" style="color:#32498D; text-decoration:none">
<img src="/images/cwe-20years-logo.png" width="203" height="58" style="float:left;border:0;margin-right:6px" alt="CWE" />
<h1 style="color:#314a8d;font-size:1.5em;font-family:'Verdana',sans-serif;#eee;margin: .1em auto">Common Weakness Enumeration</h1>
<p style="color:#314a8d;font-family:'Times New Roman';font-style:italic;font-size:1em;#eee;margin:.1em auto 0 auto">Celebrating 20 years of community-developed cybersecurity weakness knowledge!</p>
</a>
</div>
<div style="float:right;padding-top:0px;text-align:right;padding-left:8px;padding-right:4px;padding-bottom:0px;"><a href="/about/new_to_cwe.html" title="New to CWE click here logo"><img src="/images/new_to_cwe/new_to_cwe_click_here.png" height="90" border="0" alt="New to CWE? click here!" style="text-align:center"/></a></div>
<div style="float:right;padding-top:0px;text-align:right;padding-left:0px;padding-right:4px;padding-bottom:0px;"><a href="/topHW/index.html" title="CWE Most Important Hardware Weaknesses"> <img src="/images/mihw_logo.svg" width="90" border="0" alt="CWE Most Important Hardware Weaknesses" style="vertical-align:bottom"/></a></div>
<div style="float:right;padding-top:0px;text-align:right;padding-left:0px;padding-right:4px;padding-bottom:0px;"><a href="/top25/" title="CWE Top 25"><img src="/images/cwe_top_25_logo_simple.svg" width="90" border="0" alt="CWE Top 25 Most Dangerous Weaknesses" style="vertical-align:bottom"/></a></div>
</div><!--End Masthead div-->
<div id="HeaderBar" class="noprint">
<table width="100%" border="0" cellpadding="0" cellspacing="0">
<tr>
<td width="100%" align="left" style="padding-left:10px; font-size:75%;">
<a href="/" >Home</a> &gt; <a href="/about/index.html" >About CWE</a> &gt;
Terms of Use
&nbsp;
</td>
<td align="right" nowrap="nowrap" style="padding-right:12px">
<!-- Begin /includes/search_cwe_id.html -->
<div class="noprint">
<form action="/cgi-bin/jumpmenu.cgi" align="right" style="padding:0px; margin:0px">
ID <label for="id" style="padding-right:5px">Lookup:</label>
<input id="id" name="id" type="text" style="width:50px; font-size:80%" maxlength="10" />
<input value="Go" style="padding: 0px; font-size:80%" type="submit">
</form>
</div>
<!-- End /includes/search_cwe_id.html -->
</td>
</tr>
</table>
</div> <!--//HeaderBar-->
<div class="yesprint">
<hr width="100%" size="1" style="clear:both" color="#000000" />
</div>
<div class="topnav">
<ul>
<li><a href="/index.html">Home</a></li>
<li>
<div class="dropdown">
<button class="dropbtn">About &#x25BC;</button>
<div class="dropdown-content">
<a href="/about/index.html">Who We Are</a>
<a href="/about/user_stories.html">User Stories</a>
<a href="/about/history.html">History</a>
<a href="/about/documents.html">Documents</a>
<a href="/about/cwe_videos.html">Videos</a>
</div>
</div>
</li>
<li>
<div class="dropdown">
<button class="dropbtn">Learn &#x25BC;</button>
<div class="dropdown-content">
<a href="/about/new_to_cwe.html">Basics</a>
<div class="dropdown-sub-group">
<a href="/documents/cwe_usage/guidance.html">Root Cause Mapping &nbsp; &#x25BA;</a>
<div class="dropdown-content-submenu">
<a href="/documents/cwe_usage/guidance.html">Guidance</a>
<a href="/documents/cwe_usage/quick_tips.html">Quick Tips</a>
<a href="/documents/cwe_usage/mapping_examples.html">Examples</a>
</div>
</div>
<a href="/community/submissions/overview.html">How to Contribute Weakness Content</a>
<a href="/about/faq.html">FAQs</a>
<a href="/documents/glossary/index.html">Glossary</a>
</div>
</div>
</li>
<li>
<div class="dropdown">
<button class="dropbtn">Access Content &#x25BC;</button>
<div class="dropdown-content">
<div class="dropdown-sub-group">
<a href="/scoring/index.html#top_n_lists">Top-N Lists &nbsp; &#x25BA;</a>
<div class="dropdown-content-submenu">
<a href="/top25/">Top 25 Software</a>
<a href="/topHW/index.html">Top Hardware</a>
<a href="/top25/archive/2025/2025_kev_list.html">Top 10 KEV Weaknesses</a>
</div>
</div>
<div class="dropdown-sub-group">
<a href="/data/index.html">CWE List &nbsp; &#x25BA;</a>
<div class="dropdown-content-submenu">
<a href="/data/index.html">Current Version</a>
<a href="/data/reports.html">Reports</a>
<a href="/data/pdfs.html">Visualizations</a>
<a href="/data/archive.html">Releases Archive</a>
</div>
</div>
<a href="/data/downloads.html">Downloads</a>
<a href="https://github.com/CWE-CAPEC/REST-API-wg/blob/main/Quick%20Start.md" target="_blank">REST API</a>
</div>
</div>
</li>
<li>
<div class="dropdown">
<button class="dropbtn">Community &#x25BC;</button>
<div class="dropdown-content">
<div class="dropdown-sub-group">
<a href="/news/">News &nbsp; &#x25BA;</a>
<div class="dropdown-content-submenu">
<a href="/news/archives/news2026.html">Current News</a>
<a href="https://medium.com/@CWE_CAPEC" target="_blank">Blog</a>
<a href="/news/podcast.html">Podcast</a>
<a href="/news/archives/index.html">News Archive</a>
</div>
</div>
<a href="/community/board.html">CWE Board</a>
<a href="/community/working_groups.html">Working Groups &amp; Special Interest Groups</a>
<a href="/community/registration.html">Email Lists</a>
</div>
</div>
</li>
<li>
<div class="dropdown">
<button class="dropbtn">Search &#x25BC;</button>
<div class="dropdown-content">
<a href="/">Search CWE List</a>
<a href="/find/index.html">Search Website</a>
</div>
</li>
</ul>
</div>
<table width="100%" border="0" cellspacing="0" cellpadding="0" id="MainPane">
<tr>
<!-- begin left side menu -->
<td valign="top" rowspan="2" id="LeftPane">
<!--include virtual="/includes/leftsidemenu.html" Removed 11212016-->
<script type="text/javascript">browserheight();</script>
</td>
<!-- end left side menu -->
<td style="height:1px"></td>
<!-- begin right column -->
<td valign="top" align="center" rowspan="2" nowrap="nowrap" id="RightPane">
</td>
<!-- end right side menu -->
</tr>
<tr>
<!-- begin content pane -->
<td valign="top" width="100%" id="Contentpane">
<!--Glossary tags-->
<div id="styled_popup" name="styled_popup" style="display:none; position:fixed; top:300; height:auto; width:300px; z-index:1000">
<table width="300" cellpadding="0" cellspacing="0" border="0" style="border:1px solid #32498D;">
<tr style="background-color:#32498D; color:#ffffff;">
<td width="100%" style="padding:1px 5px 1px 5px; border-bottom:1px solid #000000"><div width="100%" style="font-weight:bold;">CWE Glossary Definition</div></td>
<td nowrap="nowrap" style="padding:1px; border-bottom:1px solid #000000" valign="top"><a href="javascript:styledPopupClose();"><img src="/images/layout/close.gif" border="0" alt="x"></a></td>
</tr>
<tr><td colspan="2" style="background: url(/images/layout/ylgradient.jpg); background-repeat: repeat-x repeat-y; padding:5px; background-color:#FFFFCC; " valign="top">
<div id="output" style="max-height:400px; overflow-y:auto"></div>
</td></tr>
</table>
</div>
<!--begin Main Content-->
<h2>Terms of Use</h2>
<p>CWE&trade; is free to use by any organization or individual for any research, development, and/or commercial purposes, per these CWE Terms of Use. Accordingly, The MITRE Corporation hereby grants you a non-exclusive, royalty-free license to use CWE for research, development, and commercial purposes. Any copy you make for such purposes is authorized on the condition that you reproduce MITRE’s copyright designation and this license in any such copy. CWE is a trademark of The MITRE Corporation. Please contact cwe@mitre.org if you require further clarification on this issue.</p>
<h3>DISCLAIMERS</h3>
<p>By accessing information through this site you (as “the user”) hereby agrees the site and the information is provided on an “as is” basis only without warranty of any kind, express or implied, including but not limited to implied warranties of merchantability, availability, accuracy, noninfringement, or fitness for a particular purpose. Use of this site and the information is at the user’s own risk. The user shall comply with all applicable laws, rules, and regulations, and the data source’s restrictions, when using the site.</p>
<p>By contributing information to this site you (as “the contributor”) hereby represents and warrants the contributor has obtained all necessary permissions from copyright holders and other third parties to allow the contributor to contribute, and this site to host and display, the information and any such contribution, hosting, and displaying will not violate any law, rule, or regulation. Additionally, the contributor hereby grants all users of such information a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable license to reproduce, prepare derivative works of, publicly display, publicly perform, sublicense, and distribute such information and all derivative works.</p>
<p>The MITRE Corporation expressly disclaims any liability for any damages arising from the contributor’s contribution of such information, the user’s use of the site or such information, and The MITRE Corporation’s hosting the tool and displaying the information. The foregoing disclaimer specifically includes but is not limited to general, consequential, indirect, incidental, exemplary, or special or punitive damages (including but not limited to loss of income, program interruption, loss of information, or other pecuniary loss) arising out of use of this information, no matter the cause of action, even if The MITRE Corporation has been advised of the possibility of such damages.</p>
<!--end Main Content-->
</td>
<!-- end content pane -->
</tr>
</table>
<div id="FootPane" class="noprint">
<div id="footbar">
<b>Page Last Updated: </b>
July 20, 2023
</div>
<div class="Footer noprint">
<a name="footer" id="footer"></a>
<table width="100%" cellpadding="0" cellspacing="0" border="0" class="ltgreybackground" style="clear:both">
<tr>
<td colspan="3" id="line"><div class="line">&nbsp;</div></td>
</tr>
<tr>
<td valign="middle" nowrap="nowrap">
<div id="footerlinks" class="footlogo">
<a href="http://www.mitre.org" target="_blank" rel="noopener noreferrer"><img src="/images/mitre_logo.gif" height="36" border="0" alt="MITRE" title="MITRE"/></a>
</div>
</td>
<td width="100%" valign="top" style="padding:6px 0px;">
<div id="footerlinks">
<a href="/sitemap.html">Site Map</a> |
<a href="/about/termsofuse.html">Terms of Use</a> |
<a href="#" onclick="Osano.cm.showDrawer('osano-cm-dom-info-dialog-open')">Manage Cookies</a> |
<a href="/about/cookie_notice.html">Cookie Notice</a> |
<a href="/about/privacy_policy.html">Privacy Policy</a> |
<a href="mailto:cwe@mitre.org">Contact Us</a> |
<a target="_blank" href="https://x.com/CweCapec"><img src="/images/x-logo-black.png" width="18" height="18" style="border:0;vertical-align:right;" alt="CWE on X" title="CWE on X"></a>
<a target="_blank" href="https://www.linkedin.com/showcase/cve-cwe-capec"><img src="/images/linkedin_sm.jpg" width="20" height="20" style="border:0;vertical-align:right;" alt="CWE on LinkedIn" title="CWE on LinkedIn"></a>
<a target="_blank" href="https://bsky.app/profile/cweprogram.bsky.social"><img src="/images/bluesky_logo_sm.png" width="18" height="18" style="border:0;vertical-align:right;" alt="CWE on Bluesky" title="Bluesky"></a>
<a target="_blank" href="https://mastodon.social/@CWE_Program"><img src="/images/mastodon-logo.png" width="20" height="20" style="border:0;vertical-align:right;" alt="CWE on Mastodon" title="CWE on Mastodon"></a>
<a target="_blank" href="https://www.youtube.com/channel/UCpY9VIpRmFK4ebD6orssifA"><img src="/images/youtube.png" width="20" height="20" style="border:0;vertical-align:right;" alt="CWE YouTube channel" title="CWE YouTube Channel"></a>
<a href="/news/podcast.html"><img src="/images/out_of_bounds_read_logo.png" width="22" height="22" style="border:0;vertical-align:right;" alt="CWE Out-of-Bounds-Read Podcast" title="CWE Out-of-Bounds-Read Podcast"></a>
<a target="_blank" href="https://medium.com/@CWE_CAPEC"><img src="/images/medium.png" width="20" height="20" style="border:0;vertical-align:right;" alt="CWE Blog on Medium blog" title="CWE Blog on Medium"></a>
</div>
<p>Use of the Common Weakness Enumeration (CWE&trade;) and the associated references from this website are subject to the <a href="/about/termsofuse.html">Terms of Use</a>. CWE is sponsored by the <a target="_blank" rel="noopener noreferrer" href="https://www.dhs.gov/">U.S. Department of Homeland Security</a> (DHS) <a target="_blank" rel="noopener noreferrer" href="https://www.dhs.gov/cisa/cybersecurity-division">Cybersecurity and Infrastructure Security Agency</a> (CISA) and managed by the <a href="https://www.dhs.gov/science-and-technology/hssedi" target="_blank" rel="noopener noreferrer">Homeland Security Systems Engineering and Development Institute</a> (HSSEDI) which is operated by <a target="_blank" rel="noopener noreferrer" href="http://www.mitre.org/">The MITRE Corporation</a> (MITRE). Copyright &copy; 2006&ndash;2026, The MITRE Corporation. CWE, CWSS, CWRAF, and the CWE logo are trademarks of The MITRE Corporation.</p>
</td>
<td valign="middle" nowrap="nowrap">
<div id="footerlinks" class="footlogo">
<a href="https://www.dhs.gov/science-and-technology/hssedi" target="_blank" rel="noopener noreferrer"><img src="/images/hssedi.png" height="36" border="0" alt="HSSEDI" title="HSSEDI"/></a>
</div>
</td>
</tr>
</table>
</div>
</div>
<!-- Google tag (gtag.js) -->
<script async src="https://www.googletagmanager.com/gtag/js?id=G-TCLW30GNGV"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'G-TCLW30GNGV');
</script>
</body>
</html>
+11
View File
@@ -0,0 +1,11 @@
CWE™ is free to use by any organization or individual for any research,
development, and/or commercial purposes, per these CWE Terms of Use.
Accordingly, The MITRE Corporation hereby grants you a non-exclusive,
royalty-free license to use CWE for research, development, and commercial
purposes. Any copy you make for such purposes is authorized on the condition
that you reproduce MITRE's copyright designation and this license in any such
copy. CWE is a trademark of The MITRE Corporation.
Copyright © 2006-2026, The MITRE Corporation.
Full terms: https://cwe.mitre.org/about/termsofuse.html
+1
View File
@@ -0,0 +1 @@
https://cwe.mitre.org/about/termsofuse.html
+428
View File
@@ -0,0 +1,428 @@
Attribution-ShareAlike 4.0 International
=======================================================================
Creative Commons Corporation ("Creative Commons") is not a law firm and
does not provide legal services or legal advice. Distribution of
Creative Commons public licenses does not create a lawyer-client or
other relationship. Creative Commons makes its licenses and related
information available on an "as-is" basis. Creative Commons gives no
warranties regarding its licenses, any material licensed under their
terms and conditions, or any related information. Creative Commons
disclaims all liability for damages resulting from their use to the
fullest extent possible.
Using Creative Commons Public Licenses
Creative Commons public licenses provide a standard set of terms and
conditions that creators and other rights holders may use to share
original works of authorship and other material subject to copyright
and certain other rights specified in the public license below. The
following considerations are for informational purposes only, are not
exhaustive, and do not form part of our licenses.
Considerations for licensors: Our public licenses are
intended for use by those authorized to give the public
permission to use material in ways otherwise restricted by
copyright and certain other rights. Our licenses are
irrevocable. Licensors should read and understand the terms
and conditions of the license they choose before applying it.
Licensors should also secure all rights necessary before
applying our licenses so that the public can reuse the
material as expected. Licensors should clearly mark any
material not subject to the license. This includes other CC-
licensed material, or material used under an exception or
limitation to copyright. More considerations for licensors:
wiki.creativecommons.org/Considerations_for_licensors
Considerations for the public: By using one of our public
licenses, a licensor grants the public permission to use the
licensed material under specified terms and conditions. If
the licensor's permission is not necessary for any reason--for
example, because of any applicable exception or limitation to
copyright--then that use is not regulated by the license. Our
licenses grant only permissions under copyright and certain
other rights that a licensor has authority to grant. Use of
the licensed material may still be restricted for other
reasons, including because others have copyright or other
rights in the material. A licensor may make special requests,
such as asking that all changes be marked or described.
Although not required by our licenses, you are encouraged to
respect those requests where reasonable. More considerations
for the public:
wiki.creativecommons.org/Considerations_for_licensees
=======================================================================
Creative Commons Attribution-ShareAlike 4.0 International Public
License
By exercising the Licensed Rights (defined below), You accept and agree
to be bound by the terms and conditions of this Creative Commons
Attribution-ShareAlike 4.0 International Public License ("Public
License"). To the extent this Public License may be interpreted as a
contract, You are granted the Licensed Rights in consideration of Your
acceptance of these terms and conditions, and the Licensor grants You
such rights in consideration of benefits the Licensor receives from
making the Licensed Material available under these terms and
conditions.
Section 1 -- Definitions.
a. Adapted Material means material subject to Copyright and Similar
Rights that is derived from or based upon the Licensed Material
and in which the Licensed Material is translated, altered,
arranged, transformed, or otherwise modified in a manner requiring
permission under the Copyright and Similar Rights held by the
Licensor. For purposes of this Public License, where the Licensed
Material is a musical work, performance, or sound recording,
Adapted Material is always produced where the Licensed Material is
synched in timed relation with a moving image.
b. Adapter's License means the license You apply to Your Copyright
and Similar Rights in Your contributions to Adapted Material in
accordance with the terms and conditions of this Public License.
c. BY-SA Compatible License means a license listed at
creativecommons.org/compatiblelicenses, approved by Creative
Commons as essentially the equivalent of this Public License.
d. Copyright and Similar Rights means copyright and/or similar rights
closely related to copyright including, without limitation,
performance, broadcast, sound recording, and Sui Generis Database
Rights, without regard to how the rights are labeled or
categorized. For purposes of this Public License, the rights
specified in Section 2(b)(1)-(2) are not Copyright and Similar
Rights.
e. Effective Technological Measures means those measures that, in the
absence of proper authority, may not be circumvented under laws
fulfilling obligations under Article 11 of the WIPO Copyright
Treaty adopted on December 20, 1996, and/or similar international
agreements.
f. Exceptions and Limitations means fair use, fair dealing, and/or
any other exception or limitation to Copyright and Similar Rights
that applies to Your use of the Licensed Material.
g. License Elements means the license attributes listed in the name
of a Creative Commons Public License. The License Elements of this
Public License are Attribution and ShareAlike.
h. Licensed Material means the artistic or literary work, database,
or other material to which the Licensor applied this Public
License.
i. Licensed Rights means the rights granted to You subject to the
terms and conditions of this Public License, which are limited to
all Copyright and Similar Rights that apply to Your use of the
Licensed Material and that the Licensor has authority to license.
j. Licensor means the individual(s) or entity(ies) granting rights
under this Public License.
k. Share means to provide material to the public by any means or
process that requires permission under the Licensed Rights, such
as reproduction, public display, public performance, distribution,
dissemination, communication, or importation, and to make material
available to the public including in ways that members of the
public may access the material from a place and at a time
individually chosen by them.
l. Sui Generis Database Rights means rights other than copyright
resulting from Directive 96/9/EC of the European Parliament and of
the Council of 11 March 1996 on the legal protection of databases,
as amended and/or succeeded, as well as other essentially
equivalent rights anywhere in the world.
m. You means the individual or entity exercising the Licensed Rights
under this Public License. Your has a corresponding meaning.
Section 2 -- Scope.
a. License grant.
1. Subject to the terms and conditions of this Public License,
the Licensor hereby grants You a worldwide, royalty-free,
non-sublicensable, non-exclusive, irrevocable license to
exercise the Licensed Rights in the Licensed Material to:
a. reproduce and Share the Licensed Material, in whole or
in part; and
b. produce, reproduce, and Share Adapted Material.
2. Exceptions and Limitations. For the avoidance of doubt, where
Exceptions and Limitations apply to Your use, this Public
License does not apply, and You do not need to comply with
its terms and conditions.
3. Term. The term of this Public License is specified in Section
6(a).
4. Media and formats; technical modifications allowed. The
Licensor authorizes You to exercise the Licensed Rights in
all media and formats whether now known or hereafter created,
and to make technical modifications necessary to do so. The
Licensor waives and/or agrees not to assert any right or
authority to forbid You from making technical modifications
necessary to exercise the Licensed Rights, including
technical modifications necessary to circumvent Effective
Technological Measures. For purposes of this Public License,
simply making modifications authorized by this Section 2(a)
(4) never produces Adapted Material.
5. Downstream recipients.
a. Offer from the Licensor -- Licensed Material. Every
recipient of the Licensed Material automatically
receives an offer from the Licensor to exercise the
Licensed Rights under the terms and conditions of this
Public License.
b. Additional offer from the Licensor -- Adapted Material.
Every recipient of Adapted Material from You
automatically receives an offer from the Licensor to
exercise the Licensed Rights in the Adapted Material
under the conditions of the Adapter's License You apply.
c. No downstream restrictions. You may not offer or impose
any additional or different terms or conditions on, or
apply any Effective Technological Measures to, the
Licensed Material if doing so restricts exercise of the
Licensed Rights by any recipient of the Licensed
Material.
6. No endorsement. Nothing in this Public License constitutes or
may be construed as permission to assert or imply that You
are, or that Your use of the Licensed Material is, connected
with, or sponsored, endorsed, or granted official status by,
the Licensor or others designated to receive attribution as
provided in Section 3(a)(1)(A)(i).
b. Other rights.
1. Moral rights, such as the right of integrity, are not
licensed under this Public License, nor are publicity,
privacy, and/or other similar personality rights; however, to
the extent possible, the Licensor waives and/or agrees not to
assert any such rights held by the Licensor to the limited
extent necessary to allow You to exercise the Licensed
Rights, but not otherwise.
2. Patent and trademark rights are not licensed under this
Public License.
3. To the extent possible, the Licensor waives any right to
collect royalties from You for the exercise of the Licensed
Rights, whether directly or through a collecting society
under any voluntary or waivable statutory or compulsory
licensing scheme. In all other cases the Licensor expressly
reserves any right to collect such royalties.
Section 3 -- License Conditions.
Your exercise of the Licensed Rights is expressly made subject to the
following conditions.
a. Attribution.
1. If You Share the Licensed Material (including in modified
form), You must:
a. retain the following if it is supplied by the Licensor
with the Licensed Material:
i. identification of the creator(s) of the Licensed
Material and any others designated to receive
attribution, in any reasonable manner requested by
the Licensor (including by pseudonym if
designated);
ii. a copyright notice;
iii. a notice that refers to this Public License;
iv. a notice that refers to the disclaimer of
warranties;
v. a URI or hyperlink to the Licensed Material to the
extent reasonably practicable;
b. indicate if You modified the Licensed Material and
retain an indication of any previous modifications; and
c. indicate the Licensed Material is licensed under this
Public License, and include the text of, or the URI or
hyperlink to, this Public License.
2. You may satisfy the conditions in Section 3(a)(1) in any
reasonable manner based on the medium, means, and context in
which You Share the Licensed Material. For example, it may be
reasonable to satisfy the conditions by providing a URI or
hyperlink to a resource that includes the required
information.
3. If requested by the Licensor, You must remove any of the
information required by Section 3(a)(1)(A) to the extent
reasonably practicable.
b. ShareAlike.
In addition to the conditions in Section 3(a), if You Share
Adapted Material You produce, the following conditions also apply.
1. The Adapter's License You apply must be a Creative Commons
license with the same License Elements, this version or
later, or a BY-SA Compatible License.
2. You must include the text of, or the URI or hyperlink to, the
Adapter's License You apply. You may satisfy this condition
in any reasonable manner based on the medium, means, and
context in which You Share Adapted Material.
3. You may not offer or impose any additional or different terms
or conditions on, or apply any Effective Technological
Measures to, Adapted Material that restrict exercise of the
rights granted under the Adapter's License You apply.
Section 4 -- Sui Generis Database Rights.
Where the Licensed Rights include Sui Generis Database Rights that
apply to Your use of the Licensed Material:
a. for the avoidance of doubt, Section 2(a)(1) grants You the right
to extract, reuse, reproduce, and Share all or a substantial
portion of the contents of the database;
b. if You include all or a substantial portion of the database
contents in a database in which You have Sui Generis Database
Rights, then the database in which You have Sui Generis Database
Rights (but not its individual contents) is Adapted Material,
including for purposes of Section 3(b); and
c. You must comply with the conditions in Section 3(a) if You Share
all or a substantial portion of the contents of the database.
For the avoidance of doubt, this Section 4 supplements and does not
replace Your obligations under this Public License where the Licensed
Rights include other Copyright and Similar Rights.
Section 5 -- Disclaimer of Warranties and Limitation of Liability.
a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE
EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS
AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF
ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS,
IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION,
WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR
PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS,
ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT
KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT
ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU.
b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE
TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION,
NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT,
INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES,
COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR
USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN
ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR
DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR
IN PART, THIS LIMITATION MAY NOT APPLY TO YOU.
c. The disclaimer of warranties and limitation of liability provided
above shall be interpreted in a manner that, to the extent
possible, most closely approximates an absolute disclaimer and
waiver of all liability.
Section 6 -- Term and Termination.
a. This Public License applies for the term of the Copyright and
Similar Rights licensed here. However, if You fail to comply with
this Public License, then Your rights under this Public License
terminate automatically.
b. Where Your right to use the Licensed Material has terminated under
Section 6(a), it reinstates:
1. automatically as of the date the violation is cured, provided
it is cured within 30 days of Your discovery of the
violation; or
2. upon express reinstatement by the Licensor.
For the avoidance of doubt, this Section 6(b) does not affect any
right the Licensor may have to seek remedies for Your violations
of this Public License.
c. For the avoidance of doubt, the Licensor may also offer the
Licensed Material under separate terms or conditions or stop
distributing the Licensed Material at any time; however, doing so
will not terminate this Public License.
d. Sections 1, 5, 6, 7, and 8 survive termination of this Public
License.
Section 7 -- Other Terms and Conditions.
a. The Licensor shall not be bound by any additional or different
terms or conditions communicated by You unless expressly agreed.
b. Any arrangements, understandings, or agreements regarding the
Licensed Material not stated herein are separate from and
independent of the terms and conditions of this Public License.
Section 8 -- Interpretation.
a. For the avoidance of doubt, this Public License does not, and
shall not be interpreted to, reduce, limit, restrict, or impose
conditions on any use of the Licensed Material that could lawfully
be made without permission under this Public License.
b. To the extent possible, if any provision of this Public License is
deemed unenforceable, it shall be automatically reformed to the
minimum extent necessary to make it enforceable. If the provision
cannot be reformed, it shall be severed from this Public License
without affecting the enforceability of the remaining terms and
conditions.
c. No term or condition of this Public License will be waived and no
failure to comply consented to unless expressly agreed to by the
Licensor.
d. Nothing in this Public License constitutes or may be interpreted
as a limitation upon, or waiver of, any privileges and immunities
that apply to the Licensor or You, including from the legal
processes of any jurisdiction or authority.
=======================================================================
Creative Commons is not a party to its public
licenses. Notwithstanding, Creative Commons may elect to apply one of
its public licenses to material it publishes and in those instances
will be considered the “Licensor.” The text of the Creative Commons
public licenses is dedicated to the public domain under the CC0 Public
Domain Dedication. Except for the limited purpose of indicating that
material is shared under a Creative Commons public license or as
otherwise permitted by the Creative Commons policies published at
creativecommons.org/policies, Creative Commons does not authorize the
use of the trademark "Creative Commons" or any other trademark or logo
of Creative Commons without its prior written consent including,
without limitation, in connection with any unauthorized modifications
to any of its public licenses or any other arrangements,
understandings, or agreements concerning use of licensed material. For
the avoidance of doubt, this paragraph does not form part of the
public licenses.
Creative Commons may be contacted at creativecommons.org.
+13 -8
View File
@@ -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
+13 -3
View File
@@ -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
View File
@@ -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
View File
@@ -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"
}
+81
View File
@@ -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")
}
}
+34
View File
@@ -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.
+244
View File
@@ -0,0 +1,244 @@
#!/usr/bin/env python3
"""Build the embedded knowledge pack from the official sources.
The output is committed so the agent binary does not need network access at
runtime. Re-run this script to refresh the pack; it records the source URL,
license, retrieval date and source digest in knowledge/data/sources.json.
Usage:
python3 scripts/knowledge/build.py
"""
from __future__ import annotations
import csv
import hashlib
import io
import json
import sys
import urllib.request
import zipfile
from datetime import date
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
DATA = ROOT / "knowledge" / "data"
LICENSES = ROOT / "knowledge" / "licenses"
ATTACK_URL = "https://raw.githubusercontent.com/mitre-attack/attack-stix-data/master/enterprise-attack/enterprise-attack.json"
ATTACK_LICENSE_URL = "https://raw.githubusercontent.com/mitre-attack/attack-stix-data/master/LICENSE.txt"
WSTG_URL = "https://raw.githubusercontent.com/OWASP/wstg/master/checklists/checklist.json"
WSTG_LICENSE_URL = "https://raw.githubusercontent.com/OWASP/wstg/master/LICENSE"
CWE_URL = "https://cwe.mitre.org/data/csv/1000.csv"
CWE_TERMS_URL = "https://cwe.mitre.org/about/termsofuse.html"
MAX_ATTACK_DESCRIPTION = 400
MAX_WSTG_DESCRIPTION = 400
MAX_CWE_DESCRIPTION = 300
CWE_TERMS_TEXT = """CWE™ is free to use by any organization or individual for any research,
development, and/or commercial purposes, per these CWE Terms of Use.
Accordingly, The MITRE Corporation hereby grants you a non-exclusive,
royalty-free license to use CWE for research, development, and commercial
purposes. Any copy you make for such purposes is authorized on the condition
that you reproduce MITRE's copyright designation and this license in any such
copy. CWE is a trademark of The MITRE Corporation.
Copyright © 2006-2026, The MITRE Corporation.
Full terms: https://cwe.mitre.org/about/termsofuse.html
"""
def fetch(url: str) -> bytes:
req = urllib.request.Request(url, headers={"User-Agent": "artex-knowledge-build/1"})
with urllib.request.urlopen(req, timeout=120) as resp:
return resp.read()
def digest(raw: bytes) -> str:
return hashlib.sha256(raw).hexdigest()
def clip(text: str, limit: int) -> tuple[str, bool]:
text = " ".join((text or "").split())
if len(text) <= limit:
return text, False
return text[: limit - 1].rstrip() + "…", True
def attack_entries(raw: bytes) -> list[dict]:
bundle = json.loads(raw)
out: list[dict] = []
for obj in bundle.get("objects", []):
if obj.get("type") != "attack-pattern":
continue
if obj.get("revoked") or obj.get("x_mitre_deprecated"):
continue
ref = next(
(r for r in obj.get("external_references", []) if r.get("source_name") == "mitre-attack"),
None,
)
if not ref or not ref.get("external_id"):
continue
description, truncated = clip(obj.get("description", ""), MAX_ATTACK_DESCRIPTION)
tactics = sorted(
{
p.get("phase_name", "")
for p in obj.get("kill_chain_phases", [])
if p.get("kill_chain_name") == "mitre-attack" and p.get("phase_name")
}
)
out.append(
{
"id": ref["external_id"],
"name": obj.get("name", ""),
"category": tactics,
"description": description,
"truncated": truncated,
"url": ref.get("url") or f"https://attack.mitre.org/techniques/{ref['external_id'].replace('.', '/')}/",
}
)
return sorted(out, key=lambda e: e["id"])
def wstg_entries(raw: bytes) -> list[dict]:
checklist = json.loads(raw)
out: list[dict] = []
for category, body in checklist.get("categories", {}).items():
for test in body.get("tests", []):
description, truncated = clip(" ".join(test.get("objectives", [])), MAX_WSTG_DESCRIPTION)
out.append(
{
"id": test.get("id", ""),
"name": test.get("name", ""),
"category": [category],
"description": description,
"truncated": truncated,
"url": test.get("reference", ""),
}
)
return sorted(out, key=lambda e: e["id"])
def cwe_entries(raw_zip: bytes) -> list[dict]:
out: list[dict] = []
with zipfile.ZipFile(io.BytesIO(raw_zip)) as zf:
name = next((n for n in zf.namelist() if n.endswith(".csv")), None)
if not name:
raise SystemExit("CWE archive has no CSV")
text = io.TextIOWrapper(zf.open(name), encoding="utf-8", errors="replace", newline="")
for row in csv.DictReader(text):
cid = (row.get("CWE-ID") or "").strip()
if not cid.isdigit():
continue
description, truncated = clip(row.get("Description", ""), MAX_CWE_DESCRIPTION)
out.append(
{
"id": f"CWE-{cid}",
"name": (row.get("Name") or "").strip(),
"category": [(row.get("Weakness Abstraction") or "").strip()],
"status": (row.get("Status") or "").strip(),
"description": description,
"truncated": truncated,
"url": f"https://cwe.mitre.org/data/definitions/{cid}.html",
}
)
return sorted(out, key=lambda e: int(e["id"].split("-", 1)[1]))
def write_json(path: Path, value: object) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(json.dumps(value, ensure_ascii=False, indent=2) + "\n", encoding="utf-8", newline="\n")
def main() -> int:
retrieved = date.today().isoformat()
attack_raw = fetch(ATTACK_URL)
wstg_raw = fetch(WSTG_URL)
cwe_raw = fetch(CWE_URL)
attack = attack_entries(attack_raw)
wstg = wstg_entries(wstg_raw)
cwe = cwe_entries(cwe_raw)
if not attack or not wstg or not cwe:
raise SystemExit("one of the sources produced no entries")
packs = [
(
"attack",
"MITRE ATT&CK Enterprise",
"MITRE ATT&CK Terms of Use",
ATTACK_URL,
ATTACK_LICENSE_URL,
digest(attack_raw),
attack,
),
(
"wstg",
"OWASP Web Security Testing Guide",
"CC-BY-SA-4.0",
WSTG_URL,
WSTG_LICENSE_URL,
digest(wstg_raw),
wstg,
),
(
"cwe",
"MITRE Common Weakness Enumeration",
"MITRE CWE Terms of Use",
CWE_URL,
CWE_TERMS_URL,
digest(cwe_raw),
cwe,
),
]
manifest = {"generated_at": retrieved, "sources": []}
for source, title, license_name, url, license_url, sha256, entries in packs:
write_json(
DATA / f"{source}.json",
{
"source": source,
"title": title,
"license": license_name,
"license_url": license_url,
"source_url": url,
"retrieved_at": retrieved,
"sha256": sha256,
"entries": entries,
},
)
manifest["sources"].append(
{
"source": source,
"title": title,
"license": license_name,
"license_url": license_url,
"source_url": url,
"retrieved_at": retrieved,
"sha256": sha256,
"entries": len(entries),
"data_file": f"data/{source}.json",
}
)
write_json(DATA / "sources.json", manifest)
LICENSES.mkdir(parents=True, exist_ok=True)
(LICENSES / "ATTACK-LICENSE.txt").write_bytes(fetch(ATTACK_LICENSE_URL).replace(b"\r\n", b"\n"))
(LICENSES / "WSTG-LICENSE.txt").write_bytes(fetch(WSTG_LICENSE_URL).replace(b"\r\n", b"\n"))
(LICENSES / "CWE-TERMS.html").write_bytes(fetch(CWE_TERMS_URL).replace(b"\r\n", b"\n"))
(LICENSES / "CWE-TERMS.txt").write_text(CWE_TERMS_TEXT, encoding="utf-8", newline="\n")
(LICENSES / "CWE-TERMS.url").write_text(CWE_TERMS_URL + "\n", encoding="utf-8", newline="\n")
print(f"attack: {len(attack)} entries")
print(f"wstg: {len(wstg)} entries")
print(f"cwe: {len(cwe)} entries")
print(f"wrote {DATA} and {LICENSES}")
return 0
if __name__ == "__main__":
sys.exit(main())
+13 -1
View File
@@ -2,9 +2,10 @@
# Verify ARTEX locally, reproducing the checks from .github/workflows/ci.yml.
#
# Usage:
# scripts/verify.sh [--full] [--go-only] [--web-only] [--keep-going]
# scripts/verify.sh [--full] [--security] [--go-only] [--web-only] [--keep-going]
#
# --full also run `go test -race` (the CI package list) and the web static build
# --security run `govulncheck ./...` (requires govulncheck in PATH)
# --go-only run only the Go checks
# --web-only run only the web checks
# --keep-going continue after a failed step and report every failure at the end
@@ -18,12 +19,14 @@ cd "$(dirname "$0")/.."
usage() { sed -n '2,14p' "$0" | sed 's/^# \?//'; }
FULL=0
SECURITY=0
GO_ONLY=0
WEB_ONLY=0
KEEP_GOING=0
while [ $# -gt 0 ]; do
case "$1" in
--full) FULL=1; shift ;;
--security) SECURITY=1; shift ;;
--go-only) GO_ONLY=1; shift ;;
--web-only) WEB_ONLY=1; shift ;;
--keep-going) KEEP_GOING=1; shift ;;
@@ -35,6 +38,10 @@ if [ "$GO_ONLY" -eq 1 ] && [ "$WEB_ONLY" -eq 1 ]; then
echo "--go-only and --web-only are mutually exclusive" >&2
exit 2
fi
if [ "$SECURITY" -eq 1 ] && [ "$WEB_ONLY" -eq 1 ]; then
echo "--security requires the Go checks and cannot be combined with --web-only" >&2
exit 2
fi
FAILED=0
run_step() {
@@ -109,6 +116,11 @@ if want_go; then
run_step "go vet" go vet ./...
run_step "go test -p 1" go test -p 1 ./...
if [ "$SECURITY" -eq 1 ]; then
require_cmd govulncheck
run_step "govulncheck" govulncheck ./...
fi
if [ "$FULL" -eq 1 ]; then
RACE_PKGS=(
./agent ./cmd/artex ./config ./db ./evidence ./guard
+26
View File
@@ -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
+51
View File
@@ -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)
}
}
+15
View File
@@ -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
+74
View File
@@ -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")
}
+13
View File
@@ -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
View File
@@ -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"} {
+43
View File
@@ -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)
}
}
+9
View File
@@ -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
+38
View File
@@ -0,0 +1,38 @@
package server
import "testing"
func TestParseTargetURLFollowedByPunctuation(t *testing.T) {
cases := []struct {
text string
scheme string
host string
port int
}{
{"Assess http://juiceshop:3000, then report.", "http", "juiceshop", 3000},
{"Assess http://juiceshop:3000.", "http", "juiceshop", 3000},
{"Scope: http://juiceshop:3000; nothing else", "http", "juiceshop", 3000},
{"The lab (http://juiceshop:3000) is ours", "http", "juiceshop", 3000},
{"Test https://app.example.com:8080, only the API", "https", "app.example.com", 8080},
{"Target is https://example.com.", "https", "example.com", 443},
{"Start at https://example.com/login?next=/a, then pivot", "https", "example.com", 443},
{"http://juiceshop:3000", "http", "juiceshop", 3000},
{"Assess http://juiceshop.", "http", "juiceshop", 80},
{"Assess http://10.0.0.5.", "http", "10.0.0.5", 80},
{"Assess http://juiceshop:3000。", "http", "juiceshop", 3000},
{"Assess “http://juiceshop:3000”", "http", "juiceshop", 3000},
{"See https://en.wikipedia.org/wiki/Foo_(bar).", "https", "en.wikipedia.org", 443},
{"(https://en.wikipedia.org/wiki/Foo_(bar))", "https", "en.wikipedia.org", 443},
{"http://[::1]", "http", "::1", 80},
{"http://[::1]:8080", "http", "::1", 8080},
{"Assess http://[fd00::10].", "http", "fd00::10", 80},
{"[http://[::1]:8080]", "http", "::1", 8080},
}
for _, c := range cases {
scheme, host, port, ok := parseTarget(c.text)
if !ok || scheme != c.scheme || host != c.host || port != c.port {
t.Errorf("parseTarget(%q) = %q, %q, %d, %v; want %q, %q, %d, true",
c.text, scheme, host, port, ok, c.scheme, c.host, c.port)
}
}
}
+41 -29
View File
@@ -28,7 +28,7 @@ type Scheduler struct {
const (
schedKeyLastFinding = "last_finding_id" // watermark: max finding node id fired for
schedKeyFiredGoals = "fired_goals" // JSON array of goal node ids already fired
schedKeyLastTimeout = "last_timeout_id" // watermark: max task id fired for task timeout
schedKeyFiredTimeouts = "fired_timeouts" // JSON array of task ids already fired for task timeout
schedKeyLastToolCall = "last_toolcall_id" // watermark: max activity id fired for tool call
schedKeyLastTaskCreate = "last_taskcreate_id" // watermark: max task id fired for task create
)
@@ -77,18 +77,16 @@ func (sc *Scheduler) init() {
set[e.NodeID] = true
}
}
sc.saveFiredGoalSet(set)
sc.saveFiredSet(schedKeyFiredGoals, set)
}
if sc.mustState(schedKeyLastTimeout) == "" {
var maxID int64
if evs, err := sc.pg.TimedOutTasksSince(0); err == nil {
if sc.mustState(schedKeyFiredTimeouts) == "" {
set := map[int64]bool{}
if evs, err := sc.pg.TimedOutTasks(); err == nil {
for _, e := range evs {
if e.NodeID > maxID {
maxID = e.NodeID
}
set[e.NodeID] = true
}
}
_ = sc.pg.SetSchedState(schedKeyLastTimeout, strconv.FormatInt(maxID, 10))
sc.saveFiredSet(schedKeyFiredTimeouts, set)
}
if sc.mustState(schedKeyLastToolCall) == "" {
var maxID int64
@@ -195,7 +193,7 @@ func (sc *Scheduler) fireGoals(triggers []*db.AgentTrigger) {
}
// Mark goals as consumed whether or not a trigger is active, so enabling an
// on_goal_met trigger later doesn't replay every already-met goal.
fired := sc.firedGoalSet()
fired := sc.firedSet(schedKeyFiredGoals)
changed := false
for _, e := range events {
if fired[e.NodeID] {
@@ -212,12 +210,14 @@ func (sc *Scheduler) fireGoals(triggers []*db.AgentTrigger) {
}
}
if changed {
sc.saveFiredGoalSet(fired)
sc.saveFiredSet(schedKeyFiredGoals, fired)
}
}
// fireTaskTimeouts fires on_task_timeout triggers for tasks that newly reached
// status='timeout' above the persisted watermark (task id → no double-fire).
// status='timeout'. Tasks time out in deadline order, not id order, so fired
// tasks are kept in a persisted set (like goals) rather than an id watermark:
// a watermark would skip an older task that times out after a newer one.
func (sc *Scheduler) fireTaskTimeouts(triggers []*db.AgentTrigger) {
var want []*db.AgentTrigger
for _, tr := range triggers {
@@ -225,17 +225,8 @@ func (sc *Scheduler) fireTaskTimeouts(triggers []*db.AgentTrigger) {
want = append(want, tr)
}
}
last, _ := strconv.ParseInt(sc.mustState(schedKeyLastTimeout), 10, 64)
events, err := sc.pg.TimedOutTasksSince(last)
if err != nil || len(events) == 0 {
return
}
// Advance the watermark even with no active trigger — see fireFindings.
maxID := last
for _, e := range events {
if e.NodeID > maxID {
maxID = e.NodeID
}
// Consume the timeouts even with no active trigger — see fireFindings.
for _, e := range sc.newTaskTimeouts() {
if len(want) == 0 {
continue
}
@@ -244,7 +235,28 @@ func (sc *Scheduler) fireTaskTimeouts(triggers []*db.AgentTrigger) {
sc.s.StartTriggeredRun(tr.AgentKey, fmt.Sprintf("Timeout trigger · task#%d", e.TaskID), tr.TaskTimeoutMessage+msgCtx, e.TaskID, true, e.TaskDesc, e.TaskGoal)
}
}
_ = sc.pg.SetSchedState(schedKeyLastTimeout, strconv.FormatInt(maxID, 10))
}
// newTaskTimeouts returns the timed-out tasks not fired for yet and records
// them as consumed.
func (sc *Scheduler) newTaskTimeouts() []db.TaskEvent {
events, err := sc.pg.TimedOutTasks()
if err != nil || len(events) == 0 {
return nil
}
fired := sc.firedSet(schedKeyFiredTimeouts)
var out []db.TaskEvent
for _, e := range events {
if fired[e.NodeID] {
continue
}
fired[e.NodeID] = true
out = append(out, e)
}
if len(out) > 0 {
sc.saveFiredSet(schedKeyFiredTimeouts, fired)
}
return out
}
// fireTaskCreates fires on_task_create triggers for tasks newly created above the
@@ -347,9 +359,9 @@ func (sc *Scheduler) mustState(key string) string {
return v
}
func (sc *Scheduler) firedGoalSet() map[int64]bool {
func (sc *Scheduler) firedSet(key string) map[int64]bool {
out := map[int64]bool{}
raw := sc.mustState(schedKeyFiredGoals)
raw := sc.mustState(key)
if raw == "" {
return out
}
@@ -362,13 +374,13 @@ func (sc *Scheduler) firedGoalSet() map[int64]bool {
return out
}
func (sc *Scheduler) saveFiredGoalSet(set map[int64]bool) {
func (sc *Scheduler) saveFiredSet(key string, set map[int64]bool) {
ids := make([]int64, 0, len(set))
for id := range set {
ids = append(ids, id)
}
b, _ := json.Marshal(ids)
if err := sc.pg.SetSchedState(schedKeyFiredGoals, string(b)); err != nil {
log.Printf("[scheduler] save fired goals failed: %v", err)
if err := sc.pg.SetSchedState(key, string(b)); err != nil {
log.Printf("[scheduler] save %s failed: %v", key, err)
}
}
+58
View File
@@ -0,0 +1,58 @@
package server
import (
"testing"
"github.com/Autumn-27/artex/db"
)
// Tasks time out in deadline order, not in id order: a task created later with
// a shorter timeout can time out first. Each timeout must still fire once.
func TestSchedulerTaskTimeoutsFireOutOfIDOrder(t *testing.T) {
skipWithoutDSN(t)
m, err := NewManager(t.TempDir(), "")
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { m.Close() })
sc := &Scheduler{pg: m.pg}
sc.newTaskTimeouts() // consume timeouts other tests left behind
var ids [2]int64
for i := range ids {
task, err := m.pg.CreateTaskWithOptions("timeout order", "goal", db.TaskCreateOptions{})
if err != nil {
t.Fatal(err)
}
ids[i] = task.ID
t.Cleanup(func() { _ = m.pg.DeleteTask(task.ID) })
}
older, newer := ids[0], ids[1]
timeOut := func(id int64) {
t.Helper()
if _, err := m.pg.Exec(`UPDATE tasks SET status='timeout' WHERE id=$1`, id); err != nil {
t.Fatal(err)
}
}
fired := func() []int64 {
var out []int64
for _, e := range sc.newTaskTimeouts() {
if e.TaskID == older || e.TaskID == newer {
out = append(out, e.TaskID)
}
}
return out
}
timeOut(newer)
if got := fired(); len(got) != 1 || got[0] != newer {
t.Fatalf("after the newer task timed out: fired %v, want [%d]", got, newer)
}
timeOut(older)
if got := fired(); len(got) != 1 || got[0] != older {
t.Fatalf("after the older task timed out: fired %v, want [%d]", got, older)
}
if got := fired(); len(got) != 0 {
t.Fatalf("second scan fired %v again, want nothing", got)
}
}
+66
View File
@@ -23,6 +23,7 @@ import (
"sync"
"sync/atomic"
"time"
"unicode/utf8"
"github.com/Autumn-27/artex/agent"
"github.com/Autumn-27/artex/archivestore"
@@ -1945,11 +1946,33 @@ var (
reDomain = regexp.MustCompile(`\b((?:[a-zA-Z0-9-]+\.)+[a-zA-Z]{2,})(?::(\d{1,5}))?`)
)
// trimURLTail drops sentence punctuation that free text puts after a URL
// ("Assess http://host:3000."). A closing bracket is dropped only when it has no
// opener in the URL, so "http://[::1]" keeps its "]".
func trimURLTail(s string) string {
for s != "" {
r, size := utf8.DecodeLastRuneInString(s)
switch r {
case '.', ',', ';', ':', '!', '?', '。', ',', '、', ';', ':', '!', '?', '”', '’':
case ')', ']', '}', '>':
open := string("([{<"[strings.IndexRune(")]}>", r)])
if strings.Count(s, open) >= strings.Count(s, string(r)) {
return s
}
default:
return s
}
s = s[:len(s)-size]
}
return s
}
// parseTarget extracts a target (scheme, host, port) from free text, supporting
// full URLs, IP[:port] and domain[:port]. ok=false when nothing parseable.
func parseTarget(text string) (scheme, host string, port int, ok bool) {
text = strings.TrimSpace(text)
if m := reURL.FindString(text); m != "" {
m = trimURLTail(m)
if u, err := url.Parse(m); err == nil && u.Hostname() != "" {
scheme = strings.ToLower(u.Scheme)
host = strings.ToLower(u.Hostname())
@@ -3897,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,
@@ -3998,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
@@ -4029,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)
@@ -4044,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 {
+6
View File
@@ -639,6 +639,12 @@ func writeTaskArchivePackage(path, payloadDir string, snapshot *pgdb.TaskArchive
log.Printf("[task-archive] skipping symlink (unsupported by the archive, other files unaffected): %s", current)
return nil
}
if !entry.IsDir() && !info.Mode().IsRegular() {
// A named pipe, socket or device left by a command: opening a pipe blocks until
// a writer appears, tar refuses a socket, and the unpacker refuses the rest.
log.Printf("[task-archive] skipping a file that is not regular (unsupported by the archive): %s", current)
return nil
}
header, err := tar.FileInfoHeader(info, "")
if err != nil {
return err
+70
View File
@@ -0,0 +1,70 @@
//go:build unix
package server
import (
"net"
"os"
"path/filepath"
"syscall"
"testing"
pgdb "github.com/Autumn-27/artex/db"
)
// A named pipe or a socket left in the task workspace by a command must not
// make the archive unrestorable, nor stop the task from being archived.
func TestTaskArchiveSkipsSpecialFiles(t *testing.T) {
// A short root: a socket path is limited to about 100 bytes.
dataDir, err := os.MkdirTemp("/tmp", "arch")
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { os.RemoveAll(dataDir) })
taskID := "42"
runDir := filepath.Join(dataDir, "tasks", taskID, "main")
if err := os.MkdirAll(runDir, 0o755); err != nil {
t.Fatal(err)
}
evidence := filepath.Join(runDir, "evidence.txt")
if err := os.WriteFile(evidence, []byte("task evidence"), 0o600); err != nil {
t.Fatal(err)
}
if err := syscall.Mkfifo(filepath.Join(runDir, "backpipe"), 0o600); err != nil {
t.Skipf("mkfifo: %v", err)
}
ln, err := net.Listen("unix", filepath.Join(runDir, "ctl.sock"))
if err != nil {
t.Skipf("unix socket: %v", err)
}
ln.(*net.UnixListener).SetUnlinkOnClose(false)
ln.Close()
stage, err := stageTaskArchiveFiles(dataDir, 1, taskID, 7)
if err != nil {
t.Fatal(err)
}
archivePath := taskArchivePath(dataDir, 1, taskID)
snapshot := &pgdb.TaskArchiveSnapshot{FormatVersion: pgdb.TaskArchiveFormatVersion, TaskID: 42, ExplorationID: 7}
_, _, checksum, err := writeTaskArchivePackage(archivePath, stage.payload, snapshot)
if err != nil {
t.Fatalf("the task could not be archived: %v", err)
}
if err := stage.commit(); err != nil {
t.Fatal(err)
}
extracted := filepath.Join(dataDir, "restore")
if err := extractTaskArchivePackage(archivePath, checksum, extracted); err != nil {
t.Fatalf("the archive of the task cannot be restored: %v", err)
}
installed, err := installTaskArchiveFiles(dataDir, extracted, taskID, 1, ExecPrivilege{})
if err != nil {
t.Fatal(err)
}
if err := installed.commit(); err != nil {
t.Fatal(err)
}
if got, err := os.ReadFile(evidence); err != nil || string(got) != "task evidence" {
t.Fatalf("restored %s = %q, %v", evidence, got, err)
}
}
+3
View File
@@ -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)
+121
View File
@@ -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
}
+114
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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]...), ""
}
}
+8 -8
View File
@@ -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
}
+3 -3
View File
@@ -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
View File
@@ -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 {
+2 -3
View File
@@ -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
View File
@@ -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
View File
@@ -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)
}
})
}
+4 -4
View File
@@ -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)
}
}
}
+2
View File
@@ -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
+10 -6
View File
@@ -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;
}