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.
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>
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.
<!-- 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
"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"}{
// 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
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.
@@ -759,7 +778,7 @@ func (w *Worker) execute(ctx context.Context, name string, taskID int64, as *db.
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)")
iferr:=d.QueryRow(`SELECT approved_by_operator, source FROM task_scope WHERE task_id=$1 AND kind='company' AND company_id=$2`,task.ID,fullID).Scan(&approved,&source);err!=nil{
t.Fatalf("read task_scope link: %v",err)
}
ifapproved{
t.Error("spawn with no task caller auto-approved the company link; want coverage-only pending operator confirmation")
}
ifsource!="agent"{
t.Errorf("source=%q, want agent (provenance must survive either way)",source)
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.