Compare commits

...
Author SHA1 Message Date
BaaRai 8fb9e365e3 docs(changelog): dedupe the 0.7.1 notes and cover the CORS proof check
Five entries in the 0.7.1 Fixed section described the same change twice:
browser capture truncation, the #542 indexing move, the (host, ts) traffic
index, the traffic host delete directory guard, and the skill endpoint
error text. Each keeps the version that matches the code and the facts the
other copy added are folded in.

The CORS proof validation from #720 gets its entry: a CORS finding now
stays unverified unless the bound exchange carries a browser-serialized
Origin and an Access-Control-Allow-Origin that authorizes it.
2026-11-30 21:41:16 +01:00
BaaRai 1ba49e04f0 Merge pull request #720 from tausifzaman/fix/cors-origin-proof-validation
security: validate CORS Origin proof evidence
2026-11-30 21:40:26 +01:00
BaaRai 86a5eb9544 Merge pull request #722 from BaaRai/release/0.7.1-addons
security/release: 0.7.1 add-ons and stdio MCP sandbox guard
2026-11-30 21:36:52 +01:00
BaaRai 6c6b353dab docs(changelog): cover notable changes since 0.6.0
The 0.7.1 release notes now list the security, interception, workspace, traffic and data changes from the v0.6.0 window that were not already detailed in the 0.7.0 or 0.7.1 sections, with their pull request numbers.
2026-11-30 21:18:23 +01:00
BaaRai 518739be3b security(server): refuse stdio MCP discovery on the panel in sandbox mode
In ARTEX_SANDBOX=required the panel must not start agent-controlled local processes. discoverAndCacheMCP now refuses stdio before connectMCP, which covers startup auto-discovery, the operator add/refresh paths and ScopeSentry; the Auto agent's create_mcp and update_mcp reject stdio transports as well. HTTP and SSE MCP clients keep their existing checks. The canary test proves the command is not spawned.
2026-11-30 21:18:09 +01:00
BaaRai 2438d1f4c0 fix(docker): keep the worker's existing exec user
Dockerfile.worker already creates exec (10001:10001) with HOME=/home/exec; #708's artex-exec rename was unnecessary and would have changed the worker identity name. The panel image keeps the artex-exec entry it needed; the worker is unchanged. The changelog now says so.
2026-11-30 21:14:11 +01:00
KKhandBaaRai f7f097ec2c fix(isolation): verify secret reads under each probe identity with descriptor metadata
Rebase #700 onto P0's isolation changes in server/isolation_unix.go (preserving
LockDownKeyDir, keys/ dir checking, and fail-closed EnforceIsolation): probe
each protected path directly with O_RDONLY|O_NONBLOCK|O_NOCTTY under the file-
tool and Bash identities, report descriptor mode/uid/gid or unexpected open
errors, and add the 0.7.1 CHANGELOG entry.

Co-authored-by: BaaRai <130491490+BaaRai@users.noreply.github.com>
2026-11-30 21:13:50 +01:00
Jędrzej SierackiandBaaRai 2276a3a023 fix(docker): give the agent executor an artex-exec passwd entry in panel and worker images
Port #708 into the panel Dockerfile and Dockerfile.worker so uid/gid 10001
resolves to artex-exec in both images (fixing tools such as ssh that require
a passwd entry for the running UID) and add the 0.7.1 CHANGELOG entry.

Co-authored-by: BaaRai <130491490+BaaRai@users.noreply.github.com>
2026-11-30 21:13:50 +01:00
BaaRai 5bd3dd2c89 Merge pull request #718 from BaaRai/release/0.7.1
release: package the sandbox images for the 0.7.1 default
2026-11-30 21:13:30 +01:00
Tausif Zaman f3b0df7f2c security: validate CORS Origin proof evidence 2026-12-01 00:52:33 +06:00
BaaRai b9f90d9216 test(ghidra): set the runner token in the compose fixture
The default compose now requires ARTEX_RUNNER_TOKEN for the panel, so the ghidra overlay config test must provide it like the sandbox compose test already does.
2026-11-30 19:48:11 +01:00
BaaRai a37b5b7025 release: package the sandbox images for the 0.7.1 default
The panel refuses tasks when artex-runner is unavailable, so the runner, worker and egress proxy are now part of docker-compose.yml and docker-compose.ghcr.yml. install.sh and update.sh generate ARTEX_RUNNER_TOKEN and build the three images; the release workflow publishes them beside the panel image. The changelog records the security fixes, the upgrade steps and the scope re-approval.
2026-11-30 19:34:59 +01:00
BaaRai b384b0823d Merge pull request #717 from BaaRai/fix/chatbridge-approval-recheck
security(chatbridge): recheck bridge access before spending an approval button
2026-11-30 19:29:50 +01:00
BaaRai 02b64521c6 Merge pull request #716 from BaaRai/sec/sandbox-mvp
security: isolate agent execution in a per-task sandbox worker
2026-11-30 19:29:38 +01:00
BaaRai 4d8c2c74e6 Merge pull request #715 from BaaRai/sec/p0-failclosed
security: fail-closed startup, secret rotation, target-gate backfill and kernel kill-switch
2026-11-30 19:29:26 +01:00
BaaRai fe9a0813c4 fix(chatbridge): recheck bridge access before spending an approval button
The poller authorizes a batch with the allowlist it read. A member removed, a chat unlisted, or the bridge disabled while that batch was queued could still reach the approval handler and spend a valid button. The handler now re-reads the bridge, refuses when access or the enabled state changed, and the consume statement requires the current config_version, so a save between the read and the press is refused instead of raced.
2026-11-30 19:13:50 +01:00
26 changed files with 1101 additions and 69 deletions
+6
View File
@@ -17,6 +17,12 @@ POSTGRES_USER=artex
# because Compose reads this file that way.
POSTGRES_PASSWORD=change-me-please
POSTGRES_DB=artex
# Shared secret between the panel and artex-runner for the internal execution
# API. install.sh and update.sh generate it when empty. Keep it private.
ARTEX_RUNNER_TOKEN=
# Agent execution isolation: required (default, one worker per task) or off
# (explicit degraded mode, loud warning). docker-compose.yml includes the runner.
# ARTEX_SANDBOX=required
# Prebuilt GHCR image tag for docker-compose.ghcr.yml. Unset uses latest.
# ARTEX_IMAGE_TAG=latest
# Build identity shown in the UI and the startup banner. update.sh refreshes both
+63 -2
View File
@@ -82,7 +82,7 @@ jobs:
# ③ Collect all zips → create the GitHub Release
release:
needs: binaries
needs: [binaries, sandbox-images]
runs-on: ubuntu-latest
permissions:
contents: write # create the Release (softprops/action-gh-release)
@@ -152,7 +152,68 @@ jobs:
generate_release_notes: false
body_path: ${{ runner.temp }}/release-body.md
# ④ Multi-arch image → push to GitHub Container Registry (and optionally Docker Hub
# ④ Sandbox images: the runner, the per-task worker and the egress proxy.
# The panel image above is useless for agent execution without them when
# ARTEX_SANDBOX=required, so they are published from the same tag.
sandbox-images:
runs-on: ubuntu-latest
permissions:
contents: read
packages: write
strategy:
matrix:
include:
- { name: runner, dockerfile: Dockerfile.runner }
- { name: worker, dockerfile: Dockerfile.worker }
- { name: egress-proxy, dockerfile: Dockerfile.egress-proxy }
steps:
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
- uses: docker/setup-qemu-action@c7c53464625b32c7a7e944ae62b3e17d2b600130 # v3.7.0
- uses: docker/setup-buildx-action@8d2750c68a42422c14e847fe6c8ac0403b4cbd6f # v3.12.0
- name: Log in to GitHub Container Registry
if: github.event_name == 'push'
uses: docker/login-action@c94ce9fb468520275223c153574b00df6fe4bcc9 # v3.7.0
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- uses: docker/metadata-action@c299e40c65443455700f0fdfc63efafe5b349051 # v5.10.0
id: meta
with:
images: ghcr.io/baarai/artex-${{ matrix.name }}
tags: |
type=ref,event=tag
type=semver,pattern={{version}}
type=raw,value=latest
- uses: docker/build-push-action@10e90e3645eae34f1e60eeb005ba3a3d33f178e8 # v6.19.2
with:
context: .
file: ${{ matrix.dockerfile }}
platforms: linux/amd64,linux/arm64
push: ${{ github.event_name == 'push' }}
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
build-args: |
ARTEX_VERSION=${{ github.ref_name }}
ARTEX_REVISION=${{ github.sha }}
provenance: true
sbom: true
- name: Verify the image pulls anonymously
if: github.event_name == 'push'
run: |
tag="${GITHUB_REF_NAME}"
image="ghcr.io/baarai/artex-${{ matrix.name }}:${tag}"
cfg="$(mktemp -d)"
for attempt in 1 2 3; do
if DOCKER_CONFIG="$cfg" docker manifest inspect "$image" >/dev/null; then
exit 0
fi
sleep 10
done
echo "anonymous pull of $image is denied; set the package visibility to Public" >&2
exit 1
# ⑤ Multi-arch image → push to GitHub Container Registry (and optionally Docker Hub
# when DOCKERHUB_ENABLED is set to 'true' alongside DOCKERHUB_IMAGE and
# DOCKERHUB_USERNAME / DOCKERHUB_TOKEN secrets). Dry runs (workflow_dispatch)
# build both platforms without logging in or pushing.
+38 -13
View File
@@ -1,15 +1,30 @@
## [Unreleased]
### Breaking Changes
- **Upgrade note (migration `0023_task_scope_operator_approval.sql`)**: Existing `source = 'manual'` `task_scope` rows are backfilled to `approved_by_operator = TRUE`, while goal-derived/agent (`source = 'agent'`) and auto (`source = 'auto'`) scopes remain `FALSE` and must be re-approved once via the Task Scope UI to grant sandbox egress. Target-gate approval clears only the tool gate; worker egress still requires operator-approved Task Scope.
- **Container sandbox required by default (`ARTEX_SANDBOX=required`)**: agent execution (`Bash`, custom command/script tools) now routes to disposable per-task `artex-worker` containers via `artex-runner` (`docker-compose.sandbox.yml`) with an `internal: true` per-task network and DNS-pinning HTTP/SOCKS5 egress allowlist proxy (`artex-egress-proxy`). Tasks refuse to start or pause when the runner is unavailable (no silent local fallback). Pass `ARTEX_SANDBOX=off` for explicit degraded local mode (logs a loud startup warning and records `sandbox=off` in every task event log).
# Changelog
All notable changes to this project are documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
## [Unreleased]
## [0.7.1] - 2026-11-30
### Security
- **Per-task execution sandbox is the default.** `Bash`, custom command and script tools run in a disposable `artex-worker` container created by `artex-runner`, never in the panel container. Stdio MCP servers are not started on the panel in required mode; HTTP and SSE MCP clients keep their existing checks. The worker has uid/gid 10001, a read-only rootfs, `cap-drop ALL`, no key or database mount, only its task workspace, and only an internal task network. A per-task `artex-egress-proxy` enforces a deny-by-default domain and CIDR allowlist with DNS pinning, HTTP/HTTPS CONNECT and SOCKS5, blocks IMDS, RFC1918, loopback, link-local and IPv6 unless explicitly approved, and writes its audit log outside the worker workspace. The runner and the three images are part of `docker-compose.yml`, `docker-compose.ghcr.yml`, `install.sh` and `update.sh`; the release publishes the runner, worker and egress-proxy images beside the panel. `ARTEX_SANDBOX=off` is the explicit, loud degraded mode.
- **The sandbox egress allowlist is operator-owned, not agent-writable.** Migration `0023_task_scope_operator_approval.sql` adds `task_scope.approved_by_operator`. Only operator-approved rows (Task Scope UI, operator-selected companies, operator retarget) grant egress; `add_task_scope`, `insert_assets`, agent-spawned company scope and expanded rows are coverage-only. `WebFetch` and the shared browser use the same policy. Existing `source='manual'` rows are backfilled; goal-derived (`source='agent'`) and auto (`source='auto'`) scopes must be re-approved once in Task Scope. Target-gate approval clears only the tool-call gate, and the denial message says so.
- **Startup is fail-closed and key permissions are enforced.** The isolation self-test stops the server on every platform unless `ARTEX_ALLOW_UNISOLATED=1` is explicitly set. The key directory is tightened to 0700 and existing key files to 0600 at startup, so a host bind mount cannot mask the image permissions.
- **Secret rotation is atomic.** `db.RotateSecretKey`, `artex -rotate-secrets` and `scripts/rotate-secrets.sh` re-encrypt every sealed database value and bump `auth.password_version` in one transaction before the new key is moved into place. Existing sessions are invalidated.
- **Target gate backfill and a real kill switch.** Migration `0022_target_gate_backfill.sql` enables the gate on active scoped tasks that did not opt out, with `tasks.target_gate_opt_out` for the explicit opt-out. `Engine.Pause` and `Engine.BeginDelete` set `PR_SET_CHILD_SUBREAPER` and terminate the executor UID or task descendants from `/proc`; the sandbox kill scans `/proc` for uid 10001 and never trusts agent-writable state, with a container-removal fallback.
- **The panel does not start stdio MCP servers in sandbox mode.** Discovery, startup auto-discovery, the operator refresh path and the Auto agent's `create_mcp` / `update_mcp` tools reject stdio transports while `ARTEX_SANDBOX=required`; an agent-created stdio MCP cannot be launched on the panel at the next restart. HTTP and SSE MCP clients are unchanged. This closes the remaining panel-side local execution path.
- **Chat bridge approval buttons recheck access.** A member removed, a chat unlisted or the bridge disabled while a batch was queued can no longer spend a valid button. The handler re-reads the bridge, refuses when access or the enabled state changed, and the consume statement requires the current `config_version`. Reported privately by @jamesKhor.
### Breaking Changes
- **`ARTEX_SANDBOX=required` by default.** If `artex-runner` is unavailable, ARTEX refuses to start tasks and pauses running tasks, with no local fallback. `ARTEX_SANDBOX=off` is the explicit degraded mode and writes `sandbox=off` into each task event log. The runner needs access to the Docker socket; `install.sh` and `update.sh` generate `ARTEX_RUNNER_TOKEN` and build the runner, worker and egress-proxy images. GHCR users pull the sandbox profile from the same release tag.
- **Existing task scopes need one re-approval.** Operator-entered `source='manual'` scopes are backfilled by migration 0023. Goal-derived and auto-discovered scopes remain coverage-only and must be re-approved once in Task Scope before sandbox egress is granted.
### Credits
The execution-scope gap and its remediation were tracked in public before the November 2026 writeup: #421 and #423 by @youssefmedhatl, #554, #555 and #553 by @renaesop, with the two-sources-of-truth analysis by @Dukotah in #421. The chat bridge advisory was reported by @jamesKhor. The public writeup is by Kevin Joensen. Thank you.
### Added
- **The last four `src/lib` test files run in CI**: `activity-merge`, `chat-mentions`, `format` and `http-href` existed and passed, but no `package.json` script named them and the `web` job runs scripts by name, so their 15 assertions could not fail a build. `test:activity-merge`, `test:chat-mentions`, `test:format` and `test:http-href` now match the existing one-script-per-file shape and run in the `web` job; `http-href` is the guard that refuses `javascript:`, `data:` and `vbscript:` URLs before they reach an href (#678).
@@ -31,6 +46,8 @@ All notable changes to this project are documented in this file. The format is b
- **Go vulnerability scanning in CI**: every push and pull request runs the official `govulncheck` action against packages reachable from `./...`, using the Go version declared by `go.mod`. Run the same check locally with `./scripts/verify.sh --security`.
### Fixed
- **Startup isolation self-test verifies secret opens under each probe identity and reports file metadata**: `fileToolIsolationFailures` and `checkIsolationAsExecutor` now open every protected target directly with `O_RDONLY|O_NONBLOCK|O_NOCTTY` (avoiding a server-identity `os.Stat` pre-check and never blocking on FIFOs), report the opened descriptor's `mode`, `uid` and `gid`, and surface unexpected open errors such as symlink loops (#700).
- **The panel executor uid/gid 10001 has a named `artex-exec` passwd/group entry**: programs that look up their own user, such as ssh-based stdio MCP servers, refuse to start without one. The worker image already had `exec` (10001:10001) with `/home/exec` and `/bin/bash`; the panel image now defines `artex-exec` (`/app/data/exec-home`, `/usr/sbin/nologin`). A custom `-exec-uid` still needs its own entry (#708).
- **Attached curl body flags no longer bypass the stateful target guard**: `ClassifyHTTPAction` required a separator after `-d`, `-F` and `-T`, but curl takes the value fully attached, so `curl -dfoo=1`, `-Tshell.php` and `-Ffile=@payload` were classified read-only. That skipped the pre-mutation baseline gate and let `RecordStatefulReadOnly` store the mutation itself as the host's read-only baseline, a fail-open on a safety invariant. The attached forms are now mutating, including a spaced value (`-T shell.php`), while `-D` (dump headers), `-f`, `-o` and wget's `-T` timeout stay read-only. A body flag inside a multi-letter cluster (`-sSd...`) is still not detected.
- **The chat agent filter no longer keeps a thread from another agent open**: switching the filter left the previously selected conversation in place, so a thread started with one agent could still be read while the filter showed another, and the draft could pick the wrong agent. The selection is now cleared when it does not belong to the new filter, and the draft uses the filtered agent. `npm run test:chat-filter` covers both helpers and now runs in CI.
- **Session tokens are no longer accepted from a URL query string**: the SSE, log and browser endpoints accepted `?token=`, which put a console JWT into browser history, proxy logs and `Referer` headers. Those endpoints now require the same Bearer header as the rest of the API; the console uses a `fetch` based SSE reader, the client-written auth cookie is gone, and the same-origin CORS preflight allows `Authorization` and `Last-Event-ID`. Login and uploads no longer carry a token in the URL either (#660).
@@ -49,12 +66,8 @@ All notable changes to this project are documented in this file. The format is b
- **`traffic_get` keeps compressed binary responses encoded** (follow-up to #606): the decoded view judged a body as binary only by a NUL byte in its first 512 bytes, so a gzip `application/pdf` without one was shown as text. It now uses the response `Content-Type` as well, the same check the body index applies. The response head is read before the body, so an exchange without a `Content-Encoding` no longer loads its spilled blobs, and the request blob is never loaded.
- **`traffic_search` host matching**: a port search such as `host:8443` matched any capture of that host whose URL quoted `host:8443` in its query string (`?next=http://host:8443/`, typical of open-redirect and SSRF probes), because the authority prefix was not anchored to the scheme. It is now anchored to `http`, `https`, `ws` and `wss`. The recorded host keeps the client's case while the search is lowercased, so a capture of `https://Mixed.Example.com/` was not found by any host search; the comparison now ignores case. A compressed body with a bad checksum or trailing garbage now keeps the text decoded before the error instead of dropping out of the index, and the store directory guard on host delete ignores case for case-insensitive filesystems.
- **Browser capture keeps a bounded request map**: unfinished debugger requests are capped at 500, and a request that fails to load is dropped instead of waiting for eviction. A stored body longer than 256K JavaScript characters is cut and marked `[truncated by extension]`. That count is UTF-16 code units, not bytes; the server still enforces its byte cap on ingest.
- **Browser capture keeps a bounded request map**: unfinished debugger requests are capped at 500, and a stored request body is cut at the same 256 KiB limit as ingest.
- **The capture proxy no longer holds a response while indexing it** (#542): recording wrote the trigram full-text index of each body (up to 4 MiB) before the client got its response, under the recorder's global lock, so a 1 MB script added about 160 ms to its own response and to every response recorded behind it. The index is now written by a background worker. Body searches wait for entries queued before them, so they still find every exchange recorded before the search. An entry whose exchange was deleted in the meantime is dropped.
- **The capture proxy no longer holds a response while indexing it** (#542): recording wrote the trigram full-text index of each body (up to 4 MiB) before the client got its response, so a 1 MB script added about 160 ms to its own response. The index text is now committed with the exchange into `ex_fts_pending` and indexed by a background worker; with the indexer idle, recording a 1 MiB script takes about 5 ms. Under a burst of large bodies a recording can still wait behind the entry being indexed, since both need the recorder's write lock. Body searches wait (up to 30 s) for entries queued before them, so they still find every exchange recorded before the search. Entries left by a crash or a stop are indexed on the next start, and shutdown no longer drains the queue.
- **The capture proxy no longer holds a response while indexing it** (#542): recording wrote the trigram full-text index of each body (up to 4 MiB) before the client got its response, so a 1 MB script added about 160 ms to its own response. The index text is now committed with the exchange into `ex_fts_pending` and indexed by a background worker; with the indexer idle, recording a 1 MiB script takes about 5 ms. Under a burst of large bodies a recording can still wait behind the entry being indexed, since both need the recorder's write lock. Body searches wait (up to 30 s) for entries queued before them, so they still find every exchange recorded before the search. Entries left by a crash or a stop are indexed on the next start, and shutdown no longer drains the queue. An entry whose exchange was deleted after it was queued is dropped.
- **Host-filtered traffic searches no longer sort a host's whole history**: the capture index had `host` and `ts` indexed separately, so `traffic_search` and `Search` (`WHERE host=? ORDER BY ts DESC`) sorted every exchange of the host to return the newest few, and the host picker (`Hosts()`, polled every 5 s) scanned the table. A `(host, ts)` index replaces the `host` one. With 45k exchanges on one host, a host search drops from about 42 ms to 0.04 ms and the host list from 20 ms to 8 ms. The traffic page's own list (`Page()`) is unchanged. The index is built once, synchronously, on the first start after upgrading; on a store with millions of exchanges that delays startup and needs temporary disk space about the size of the index.
- **Traffic host lists no longer sort a host's whole history**: the capture index had `host` and `ts` indexed separately, so `traffic_search` and the traffic page's host filter sorted every exchange of the host to return the newest few, and the host picker (polled every 5 s) scanned the table. A `(host, ts)` index replaces the `host` one. With 45k exchanges on one host, a host search drops from about 42 ms to 0.04 ms and the host list from 20 ms to 8 ms.
- **Traffic host delete leaves the store directories in place**: a requested host whose sanitized name is `_index`, `_blobs`, `_ca`, `_delete_staging`, `.`, or `..` is not used as a directory. Those paths are the capture index, the blob store, the MITM CA, the delete staging area, or the traffic directory itself. Index rows for that host are still removed.
- **The SOCKS5 listener refuses non-loopback clients for every auth method**: username/password was offered to any client and accepted any credentials, so a remote client got past the loopback-only rule for no-auth by offering method `0x02`. Credentials are still not verified (the username carries only the pace marker), so both methods are now accepted from loopback clients only; binding `ARTEX_SOCKS5_ADDR` to a non-loopback address no longer exposes an open proxy.
- **Request bodies labelled multipart are capped**: the 32 MiB body cap skipped any request with a multipart `Content-Type`, so a JSON handler reading the body directly could be sent an unbounded body. Multipart bodies now get an upload-sized cap (the largest limit an upload handler sets).
- **The `traffic_search` host example no longer names a real IP**: the tool description shown to the model used a routable third-party address; it now uses `192.0.2.10` (RFC 5737).
@@ -63,7 +76,6 @@ All notable changes to this project are documented in this file. The format is b
- **Asset insert applies the JSON body cap**: `POST /api/assets` decodes through the shared JSON limit, including a `multipart/` request that the upload middleware leaves uncapped. A body over the cap is rejected before the database is touched.
- **The LLM connection test honours the output-cap field name**: `POST /api/llm/test` never read a profile's `max_tokens_field`, so the Test button always sent the cap as `max_tokens`. An OpenAI reasoning model (o-series, GPT-5) rejects that with `unsupported_parameter` and a 400, so a profile set to `max_completion_tokens` failed the test even though conversations with it worked. The test now resolves the field from the form, falling back to the stored profile for the list-view test button, and normalises it the same way a profile save does (only the openai format with `max_completion_tokens` is kept).
- **Skill endpoints no longer return database driver text**: a failure loading skill usage, missing-skill stats, or skill visibility is logged on the server and the client receives a fixed message.
- **Skill endpoints no longer return database driver text**: a failure loading skill usage or missing-skill stats is logged on the server and the client receives a fixed message.
- **Hook `ReplaceAll` counts against the memory budget before it runs**: `strings.ReplaceAll`, `bytes.ReplaceAll` and `regexp.ReplaceAllString` built their result first and charged it after, so a hook that repeats a long string over many matches allocated far past the 4 MiB budget. With 1 MiB replaced into each byte of 1 MiB, the runtime asked for 1 TiB and the server process exited with `fatal error: runtime: out of memory`, in a dry run as on live traffic. The size of the result is now charged before it is built, and the hook stops with the memory limit.
- **Agent list tools cap their page size**: `list_worker_traces`, `list_assets`, and `list_untested_assets` clamp a model-supplied limit or page size to 100, and clamp the page number and offset. A limit is no longer used raw as a slice capacity or a SQL page size.
- **Legacy MCP SSE refuses an overlong line**: the endpoint announcement and the legacy event reader stop a line that grows past the existing JSON-RPC buffer cap, instead of buffering it with an unbounded read.
@@ -85,6 +97,18 @@ All notable changes to this project are documented in this file. The format is b
- **Uploads do not follow a symlink**: chat and workspace uploads `Lstat` the destination and refuse to write when it is already a symlink. A dangling link is no longer treated as a free name.
- **Hardening follow-up for the upload and capture fixes**: existing spill blob directories and files are tightened on startup, hook `range` charges 32 bytes per pair, and uploads open with `O_NOFOLLOW` on Unix. The Windows upload path keeps the `Lstat` check.
- **Docker Compose database passwords with URL-special characters**: `docker-compose.yml` no longer pastes `POSTGRES_PASSWORD` into `ARTEX_PG_DSN`. The server builds the URL from `ARTEX_PG_HOST`, `ARTEX_PG_PORT`, `ARTEX_PG_USER`, `ARTEX_PG_PASSWORD`, `ARTEX_PG_DBNAME` and `ARTEX_PG_SSLMODE`, percent-encoding the user and password, so `/`, `?`, `%`, `@`, `:` and spaces connect. An explicit `ARTEX_PG_DSN` still wins and is not rewritten. `ARTEX_PG_PASSWORD` is removed from the environment with the other startup secrets (#450).
- **A CORS proof must use a browser-serialized origin and a matching response**: a finding could reach `verified` when the bound exchange carried an `Origin` header no browser sends, or a response that never authorized that origin, because verification only checked that the quoted body was present. CORS-class findings now parse the bound request and response heads, require an RFC 6454 serialized origin, and require `Access-Control-Allow-Origin` to be that exact origin or `*` without credentials; otherwise the finding stays `unverified` with the reason in the verification note. The check reads the finding's own class, so other verification paths are unchanged (#720).
### Other changes since 0.6.0
The full commit list is in the compare view. The notable changes not already detailed above:
- **Sessions and authentication**: sessions issued before a password change are rejected (#301); password-change guesses are rate-limited (#343).
- **Interception and scope**: `insert_assets` is refused when the intercept rules cannot be loaded (#336); an allow is recorded only after the gate decides (#355); target pins stay name-only behind a proxy (#370); deny and ask argv rules match across compound commands (#377); always-allow is denied for git, cmake, ctest and cpack (#385); `ExecuteExtraTool` and `Monitor` are gated by default (#389).
- **Workspace, network and execution boundaries**: `ask_operator` image paths are confined to the task directory (#337); workspace and skill paths are confined against symlink escapes (#372); the capture CA and index stay out of the workspace file API (#387); the model-list endpoint blocks SSRF (#390); agent execution is contained with the executor UID drop (#395); the optional DNS-driven egress allowlist is available as a compose overlay (#418).
- **Traffic and evidence**: WebSocket and SSE messages are recorded and shown (#254, #255); an edited request can be replayed through the recording proxy (#258); rewrite rules apply in the capture proxy (#309); rewrite provenance is recorded on snapshots and archives (#392, #394, #399); HAR 1.2 import and export are available (#412); SOCKS5, transparent TCP, UDP recording and constrained tampering hooks are opt-in (#431, #432, #433, #434); `record_fact` ties evidence to recorded activity and captures (#441).
- **Data and export**: formula cells are neutralized in the findings CSV export (#340); asset DSL length and parenthesis depth are bounded (#353); keyword-value and query DSN passwords are masked (#354); CR and LF are rejected in ingested methods and headers (#344).
- **Third-party code and install**: acquiring third-party code can require explicit operator approval (#417); the runtime image adds more recon staples (#442); `install.sh` stops using get.docker.com on unsupported distributions such as Kali (#443).
## [0.7.0] - 2026-11-21
@@ -1285,7 +1309,8 @@ First release of this fork. The engine underneath is still upstream's, but this
- [@Autumn-27](https://github.com/Autumn-27)
- [@neouks](https://github.com/neouks)
[Unreleased]: https://github.com/BaaRai/ARTEX/compare/v0.7.0...HEAD
[Unreleased]: https://github.com/BaaRai/ARTEX/compare/v0.7.1...HEAD
[0.7.1]: https://github.com/BaaRai/ARTEX/compare/v0.7.0...v0.7.1
[0.7.0]: https://github.com/BaaRai/ARTEX/compare/v0.6.0...v0.7.0
[0.6.0]: https://github.com/BaaRai/ARTEX/compare/v0.5.1...v0.6.0
[0.5.1]: https://github.com/BaaRai/ARTEX/compare/v0.5.0...v0.5.1
+8
View File
@@ -291,6 +291,14 @@ RUN npm install -g "@playwright/mcp@${PLAYWRIGHT_MCP_VERSION}" "@playwright/cli@
# cache, which /root's 0711 lets the executor reach.
ENV PLAYWRIGHT_BROWSERS_PATH=/root/.cache/ms-playwright
WORKDIR /app
# A passwd and group entry for the agent executor (the default -exec-uid and
# -exec-gid, 10001). Agent processes and stdio MCP servers run as that uid, and
# programs that look their own user up refuse to start without an entry: ssh
# exits with "No user exists for uid 10001". The home is the executor home the
# server prepares under the data directory. A custom -exec-uid needs its own entry.
RUN groupadd --gid 10001 artex-exec \
&& useradd --uid 10001 --gid 10001 --no-create-home --home-dir /app/data/exec-home \
--shell /usr/sbin/nologin artex-exec
# Binary compiled from source in the build stage above.
COPY --from=build /out/artex /app/artex
# Daemon startup script: relaunches the process after a crash and forwards SIGTERM
+25 -3
View File
@@ -1178,12 +1178,34 @@ using this project means you have read, understood and agreed to all of the abov
> development, set `ARTEX_SANDBOX=off` (logs a loud startup banner and writes
> `sandbox=off` into each task's event log).
Launch with the sandbox overlay:
The runner, worker and proxy services are part of `docker-compose.yml` and the
GHCR compose file. `install.sh` and `update.sh` generate `ARTEX_RUNNER_TOKEN` and
build the three images:
```bash
docker compose -f docker-compose.yml -f docker-compose.sandbox.yml --profile build-only build
docker compose -f docker-compose.yml -f docker-compose.sandbox.yml up -d
./install.sh # first install
./update.sh # existing checkout
```
Manual, from a source checkout:
```bash
# Put ARTEX_RUNNER_TOKEN=$(openssl rand -hex 32) in .env once.
docker compose build artex artex-runner
docker compose --profile build-only build artex-worker artex-egress-proxy
docker compose up -d
```
From the published images:
```bash
# ARTEX_RUNNER_TOKEN must be set in .env.
docker compose -f docker-compose.ghcr.yml --profile build-only pull
docker compose -f docker-compose.ghcr.yml up -d
```
`docker-compose.sandbox.yml` remains as a compatibility overlay for existing
commands; it is no longer required.
See [`docs/SANDBOX.md`](docs/SANDBOX.md) for the runner API, per-task internal
network, HTTP/SOCKS5 egress allowlist proxy, and security boundary.
+12 -7
View File
@@ -107,15 +107,20 @@ func (d *DB) SetChatBridgeApprovalMessage(ctx context.Context, id int64, message
// UseChatBridgeApproval spends the nonce of a button press. It succeeds once,
// for the chat and message the buttons were sent to, before they expire, and
// closes the buttons in the same statement. It returns nil when the press
// does not count: unknown nonce, another chat or message, expired, or used.
func (d *DB) UseChatBridgeApproval(ctx context.Context, kind, chatID, messageID, nonceHash, by string) (*ChatBridgeApproval, error) {
// does not count: unknown nonce, another chat or message, expired, used, or
// the bridge's configuration changed (config_version) or was disabled since
// the caller read it, so a member removed after the dispatch snapshot cannot
// spend a button with stale access.
func (d *DB) UseChatBridgeApproval(ctx context.Context, kind, chatID, messageID, nonceHash, by string, configVersion int64) (*ChatBridgeApproval, error) {
var a ChatBridgeApproval
err := d.QueryRowContext(ctx, `
UPDATE chat_bridge_approvals SET closed_at=NOW(), closed_by=$5
WHERE kind=$1 AND chat_id=$2 AND message_id=$3 AND message_id<>'' AND nonce_hash=$4
AND closed_at IS NULL AND expires_at > NOW()
RETURNING id, kind, chat_id, pending_id, message_id, message_text, expires_at`,
kind, chatID, messageID, nonceHash, by).Scan(&a.ID, &a.Kind, &a.ChatID, &a.PendingID, &a.MessageID, &a.MessageText, &a.ExpiresAt)
UPDATE chat_bridge_approvals a SET closed_at=NOW(), closed_by=$5
FROM chat_bridges b
WHERE a.kind=$1 AND b.kind=a.kind AND b.config_version=$6 AND b.enabled
AND a.chat_id=$2 AND a.message_id=$3 AND a.message_id<>'' AND a.nonce_hash=$4
AND a.closed_at IS NULL AND a.expires_at > NOW()
RETURNING a.id, a.kind, a.chat_id, a.pending_id, a.message_id, a.message_text, a.expires_at`,
kind, chatID, messageID, nonceHash, by, configVersion).Scan(&a.ID, &a.Kind, &a.ChatID, &a.PendingID, &a.MessageID, &a.MessageText, &a.ExpiresAt)
if errors.Is(err, sql.ErrNoRows) {
return nil, nil
}
+57 -7
View File
@@ -16,7 +16,8 @@ func TestChatBridgeApprovalLifecycle(t *testing.T) {
ctx := context.Background()
const kind = "t-bridge-approvals"
t.Cleanup(func() { _, _ = d.Exec(`DELETE FROM chat_bridges WHERE kind=$1`, kind) })
if _, err := d.SaveChatBridge(ctx, &ChatBridge{Kind: kind, Enabled: true, AllowedChats: []string{"100"}}, false); err != nil {
br, err := d.SaveChatBridge(ctx, &ChatBridge{Kind: kind, Enabled: true, AllowedChats: []string{"100"}}, false)
if err != nil {
t.Fatal(err)
}
task, err := d.CreateTask("chat bridge approvals", "", nil, 0, 0)
@@ -69,7 +70,7 @@ func TestChatBridgeApprovalLifecycle(t *testing.T) {
t.Fatalf("still to push after create: %+v", got)
}
// Before the message id is known, a press cannot count.
if a, err := d.UseChatBridgeApproval(ctx, kind, "100", "", "hash-1", "u"); err != nil || a != nil {
if a, err := d.UseChatBridgeApproval(ctx, kind, "100", "", "hash-1", "u", br.ConfigVersion); err != nil || a != nil {
t.Fatalf("press before send = %+v %v", a, err)
}
if err := d.SetChatBridgeApprovalMessage(ctx, id, "555"); err != nil {
@@ -79,16 +80,16 @@ func TestChatBridgeApprovalLifecycle(t *testing.T) {
// A press from another chat, on another message or with another nonce
// does not count.
for _, c := range []struct{ chat, msg, hash string }{{"200", "555", "hash-1"}, {"100", "556", "hash-1"}, {"100", "555", "hash-x"}} {
if a, err := d.UseChatBridgeApproval(ctx, kind, c.chat, c.msg, c.hash, "u"); err != nil || a != nil {
if a, err := d.UseChatBridgeApproval(ctx, kind, c.chat, c.msg, c.hash, "u", br.ConfigVersion); err != nil || a != nil {
t.Fatalf("press %+v = %+v %v", c, a, err)
}
}
// The right press counts once.
a, err := d.UseChatBridgeApproval(ctx, kind, "100", "555", "hash-1", "telegram user 7")
a, err := d.UseChatBridgeApproval(ctx, kind, "100", "555", "hash-1", "telegram user 7", br.ConfigVersion)
if err != nil || a == nil || a.PendingID != pending || a.MessageText != "Approval needed" {
t.Fatalf("press = %+v %v", a, err)
}
if a, err := d.UseChatBridgeApproval(ctx, kind, "100", "555", "hash-1", "telegram user 7"); err != nil || a != nil {
if a, err := d.UseChatBridgeApproval(ctx, kind, "100", "555", "hash-1", "telegram user 7", br.ConfigVersion); err != nil || a != nil {
t.Fatalf("second press = %+v %v", a, err)
}
// A used push is not closed again.
@@ -106,7 +107,8 @@ func TestChatBridgeApprovalsToClose(t *testing.T) {
ctx := context.Background()
const kind = "t-bridge-approvals-close"
t.Cleanup(func() { _, _ = d.Exec(`DELETE FROM chat_bridges WHERE kind=$1`, kind) })
if _, err := d.SaveChatBridge(ctx, &ChatBridge{Kind: kind, Enabled: true, AllowedChats: []string{"100"}}, false); err != nil {
br, err := d.SaveChatBridge(ctx, &ChatBridge{Kind: kind, Enabled: true, AllowedChats: []string{"100"}}, false)
if err != nil {
t.Fatal(err)
}
newPending := func() int64 {
@@ -142,7 +144,7 @@ func TestChatBridgeApprovalsToClose(t *testing.T) {
t.Fatalf("to close = %+v %v", got, err)
}
// An expired nonce no longer counts.
if a, err := d.UseChatBridgeApproval(ctx, kind, "100", "mh-expired", "h-expired", "u"); err != nil || a != nil {
if a, err := d.UseChatBridgeApproval(ctx, kind, "100", "mh-expired", "h-expired", "u", br.ConfigVersion); err != nil || a != nil {
t.Fatalf("expired press = %+v %v", a, err)
}
for _, a := range got {
@@ -154,3 +156,51 @@ func TestChatBridgeApprovalsToClose(t *testing.T) {
t.Fatalf("after close: %+v", got)
}
}
// TestChatBridgeApprovalStaleConfig verifies that a button press is refused
// after the bridge configuration changed, and counts only with the current
// config version. This is the batch-dispatch race: the poller authorized the
// update with an older allowlist.
func TestChatBridgeApprovalStaleConfig(t *testing.T) {
d, err := Open(testDSN(t))
if err != nil {
SkipPGUnavailable(t, err)
}
t.Cleanup(func() { _ = d.Close() })
ctx := context.Background()
const kind = "t-bridge-approval-stale"
t.Cleanup(func() { _, _ = d.Exec(`DELETE FROM chat_bridges WHERE kind=$1`, kind) })
br, err := d.SaveChatBridge(ctx, &ChatBridge{Kind: kind, Enabled: true, AllowedChats: []string{"-100"}, AllowedUsers: []string{"7"}}, false)
if err != nil {
t.Fatal(err)
}
pending, err := d.CreateInterceptPending(0, 0, "", "worker-1", "bash", []byte(`{}`), "ask")
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _, _ = d.Exec(`DELETE FROM intercept_pending WHERE id=$1`, pending) })
id, created, err := d.CreateChatBridgeApproval(ctx, kind, "-100", pending, "hash-stale", "text", time.Now().Add(time.Hour))
if err != nil || !created {
t.Fatalf("create = %v %v", created, err)
}
if err := d.SetChatBridgeApprovalMessage(ctx, id, "m-stale"); err != nil {
t.Fatal(err)
}
next, err := d.SaveChatBridge(ctx, &ChatBridge{Kind: kind, Enabled: true, AllowedChats: []string{"-100"}, AllowedUsers: []string{}}, false)
if err != nil {
t.Fatal(err)
}
if next.ConfigVersion == br.ConfigVersion {
t.Fatalf("config version did not change: %d", next.ConfigVersion)
}
if a, err := d.UseChatBridgeApproval(ctx, kind, "-100", "m-stale", "hash-stale", "7", br.ConfigVersion); err != nil || a != nil {
t.Fatalf("stale press = %+v %v", a, err)
}
var open bool
if err := d.QueryRow(`SELECT closed_at IS NULL FROM chat_bridge_approvals WHERE id=$1`, id).Scan(&open); err != nil || !open {
t.Fatalf("button after stale press: open=%v err=%v", open, err)
}
if a, err := d.UseChatBridgeApproval(ctx, kind, "-100", "m-stale", "hash-stale", "7", next.ConfigVersion); err != nil || a == nil {
t.Fatalf("current press = %+v %v", a, err)
}
}
+275
View File
@@ -0,0 +1,275 @@
package db
import (
"bufio"
"fmt"
"net/http"
"net/netip"
"net/textproto"
"strconv"
"strings"
)
// ValidateBrowserOrigin validates an Origin header value as a browser origin
// serialized by RFC 6454 / the Fetch standard. The opaque origin "null" is
// valid and is handled separately from network origins. The Fetch grammar is
// intentionally stricter than a general URL parser: browser serialization is
// lowercase ASCII, uses canonical IP literals, and omits default ports.
func ValidateBrowserOrigin(raw string) error {
if raw == "" {
return fmt.Errorf("origin is empty")
}
if raw == "null" {
return nil
}
for i := 0; i < len(raw); i++ {
if raw[i] < 0x21 || raw[i] > 0x7e {
return fmt.Errorf("origin contains a non-ASCII or whitespace byte")
}
}
separator := strings.Index(raw, "://")
if separator <= 0 {
return fmt.Errorf("origin must be a serialized origin")
}
scheme := raw[:separator]
if !validSerializedScheme(scheme) {
return fmt.Errorf("origin scheme is not a lowercase serialized scheme")
}
authority := raw[separator+3:]
if authority == "" {
return fmt.Errorf("origin host is empty")
}
host, port, hasPort, err := splitSerializedAuthority(authority)
if err != nil {
return err
}
if err := validateSerializedHost(host); err != nil {
return err
}
if hasPort {
if err := validateSerializedPort(port); err != nil {
return err
}
if port == defaultOriginPort(scheme) {
return fmt.Errorf("origin must omit the default port")
}
}
return nil
}
func validSerializedScheme(scheme string) bool {
if scheme == "" || scheme[0] < 'a' || scheme[0] > 'z' {
return false
}
for i := 1; i < len(scheme); i++ {
c := scheme[i]
if (c < 'a' || c > 'z') && (c < '0' || c > '9') && c != '+' && c != '-' && c != '.' {
return false
}
}
return true
}
func splitSerializedAuthority(authority string) (host, port string, hasPort bool, err error) {
if strings.HasPrefix(authority, "[") {
close := strings.IndexByte(authority, ']')
if close < 0 {
return "", "", false, fmt.Errorf("origin IPv6 host is not bracketed")
}
rest := authority[close+1:]
if rest != "" && rest[0] != ':' {
return "", "", false, fmt.Errorf("origin has an invalid authority")
}
if rest != "" {
return authority[1:close], rest[1:], true, nil
}
return authority[1:close], "", false, nil
}
if strings.ContainsAny(authority, "[]/@\\/?#") {
return "", "", false, fmt.Errorf("origin authority contains an invalid character")
}
if colon := strings.IndexByte(authority, ':'); colon >= 0 {
return authority[:colon], authority[colon+1:], true, nil
}
return authority, "", false, nil
}
func validateSerializedHost(host string) error {
if host == "" {
return fmt.Errorf("origin host is empty")
}
if strings.Contains(host, ":") {
addr, err := netip.ParseAddr(host)
if err != nil || !addr.Is6() || addr.String() != host {
return fmt.Errorf("origin IPv6 host is not canonical")
}
return nil
}
for _, label := range strings.Split(host, ".") {
if label == "" || !isSerializedDomainLabel(label) {
return fmt.Errorf("origin host is not a serialized domain")
}
}
return nil
}
func isSerializedDomainLabel(label string) bool {
if !isLowerAlphaNum(label[0]) || !isLowerAlphaNum(label[len(label)-1]) {
return false
}
for i := 1; i < len(label)-1; i++ {
if !isLowerAlphaNum(label[i]) && label[i] != '-' {
return false
}
}
return true
}
func isLowerAlphaNum(c byte) bool {
return (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9')
}
func validateSerializedPort(port string) error {
if port == "" || len(port) > 5 || (len(port) > 1 && port[0] == '0') {
return fmt.Errorf("origin port is not a serialized port")
}
for i := 0; i < len(port); i++ {
if port[i] < '0' || port[i] > '9' {
return fmt.Errorf("origin port is not a serialized port")
}
}
n, err := strconv.ParseUint(port, 10, 16)
if err != nil || n > 65535 {
return fmt.Errorf("origin port is out of range")
}
return nil
}
func defaultOriginPort(scheme string) string {
switch scheme {
case "http", "ws":
return "80"
case "https", "wss":
return "443"
case "ftp":
return "21"
default:
return ""
}
}
// ValidateCORSProof validates the request Origin and the response CORS
// headers that claim to authorize it.
func ValidateCORSProof(reqHeaders, respHeaders http.Header) error {
origin, err := singleHeaderValue(reqHeaders, "Origin")
if err != nil {
return fmt.Errorf("invalid Origin header: %w", err)
}
if err := ValidateBrowserOrigin(origin); err != nil {
return fmt.Errorf("invalid Origin header: %w", err)
}
acao, err := singleHeaderValue(respHeaders, "Access-Control-Allow-Origin")
if err != nil {
return fmt.Errorf("invalid Access-Control-Allow-Origin header: %w", err)
}
acao = strings.TrimSpace(acao)
if acao == "" {
return fmt.Errorf("Access-Control-Allow-Origin is empty")
}
acac, err := singleHeaderValueOptional(respHeaders, "Access-Control-Allow-Credentials")
if err != nil {
return fmt.Errorf("invalid Access-Control-Allow-Credentials header: %w", err)
}
if acao == "*" && strings.EqualFold(strings.TrimSpace(acac), "true") {
return fmt.Errorf("wildcard Access-Control-Allow-Origin is invalid with credentials")
}
if acao != "*" && acao != origin {
return fmt.Errorf("Access-Control-Allow-Origin %q does not match Origin %q", acao, origin)
}
return nil
}
// ValidateCORSProofHeads parses the raw request and response head blocks used
// by traffic evidence and validates their CORS headers.
func ValidateCORSProofHeads(reqHead, respHead string) error {
reqHeaders, err := parseStoredHeaders(reqHead)
if err != nil {
return fmt.Errorf("invalid request head: %w", err)
}
respHeaders, err := parseStoredHeaders(respHead)
if err != nil {
return fmt.Errorf("invalid response head: %w", err)
}
return ValidateCORSProof(reqHeaders, respHeaders)
}
// IsCORSFinding reports whether vulnclass identifies a CORS finding. Finding
// class is the canonical vulnerability type stored on a findings row; task
// categories are not part of this decision.
func IsCORSFinding(vulnClass string) bool {
for _, token := range strings.FieldsFunc(strings.ToLower(strings.TrimSpace(vulnClass)), func(r rune) bool {
return r < 'a' || r > 'z'
}) {
if token == "cors" {
return true
}
}
return false
}
func singleHeaderValue(headers http.Header, name string) (string, error) {
values := headerValues(headers, name)
if len(values) == 0 {
return "", fmt.Errorf("header is missing")
}
if len(values) != 1 {
return "", fmt.Errorf("header has multiple values")
}
return values[0], nil
}
func singleHeaderValueOptional(headers http.Header, name string) (string, error) {
values := headerValues(headers, name)
if len(values) == 0 {
return "", nil
}
if len(values) != 1 {
return "", fmt.Errorf("header has multiple values")
}
return values[0], nil
}
// headerValues performs a case-insensitive lookup even for maps constructed
// directly by callers rather than through Header.Set, while preserving duplicate
// values so malformed CORS responses fail closed.
func headerValues(headers http.Header, name string) []string {
var values []string
for key, current := range headers {
if strings.EqualFold(key, name) {
values = append(values, current...)
}
}
return values
}
// parseStoredHeaders parses the first-line-prefixed raw header format used by
// traffic evidence. MIMEHeader is deliberately used here instead of splitting
// on colons so folded/malformed header lines follow the standard parser.
func parseStoredHeaders(raw string) (http.Header, error) {
raw = strings.ReplaceAll(raw, "\r\n", "\n")
raw = strings.ReplaceAll(raw, "\r", "\n")
lineEnd := strings.IndexByte(raw, '\n')
if lineEnd < 0 {
return nil, fmt.Errorf("missing HTTP start line")
}
headerBlock := strings.ReplaceAll(raw[lineEnd+1:], "\n", "\r\n") + "\r\n"
mime, err := textproto.NewReader(bufio.NewReader(strings.NewReader(headerBlock))).ReadMIMEHeader()
if err != nil {
return nil, err
}
return http.Header(mime), nil
}
+128
View File
@@ -0,0 +1,128 @@
package db
import (
"net/http"
"strings"
"testing"
)
func TestValidateBrowserOrigin(t *testing.T) {
tests := []struct {
name string
origin string
wantOK bool
}{
{name: "https", origin: "https://evil.com", wantOK: true},
{name: "http port", origin: "http://attacker.example:8443", wantOK: true},
{name: "custom scheme", origin: "chrome-extension://abcdefghijklmnop", wantOK: true},
{name: "IPv6", origin: "https://[2001:db8::1]", wantOK: true},
{name: "opaque", origin: "null", wantOK: true},
{name: "missing scheme", origin: "evil.com"},
{name: "trailing slash", origin: "https://evil.com/"},
{name: "empty fragment", origin: "https://evil.com#"},
{name: "path", origin: "https://evil.com/path"},
{name: "query", origin: "https://evil.com?x=1"},
{name: "fragment", origin: "https://evil.com#frag"},
{name: "userinfo", origin: "https://user:pass@evil.com"},
{name: "internal whitespace", origin: "https://target.com\tevil.com"},
{name: "uppercase scheme", origin: "HTTPS://evil.com"},
{name: "uppercase host", origin: "https://EVIL.com"},
{name: "explicit default port", origin: "https://evil.com:443"},
{name: "leading zero port", origin: "https://evil.com:0443"},
{name: "empty port", origin: "https://evil.com:"},
{name: "invalid IPv6 serialization", origin: "https://[2001:0DB8::1]"},
{name: "domain underscore", origin: "https://evil_site.com"},
{name: "unicode host", origin: "https://例え.テスト"},
{name: "javascript", origin: "javascript:alert(1)"},
{name: "empty", origin: ""},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
err := ValidateBrowserOrigin(tt.origin)
if tt.wantOK && err != nil {
t.Fatalf("ValidateBrowserOrigin(%q) = %v, want success", tt.origin, err)
}
if !tt.wantOK && err == nil {
t.Fatalf("ValidateBrowserOrigin(%q) succeeded, want error", tt.origin)
}
})
}
}
func TestValidateCORSProof(t *testing.T) {
tests := []struct {
name string
origin string
acao string
acac string
wantOK bool
wantReason string
}{
{name: "wildcard without credentials", origin: "https://evil.com", acao: "*", wantOK: true},
{name: "wildcard credentials", origin: "https://evil.com", acao: "*", acac: "TrUe", wantReason: "wildcard"},
{name: "mismatch", origin: "https://evil.com", acao: "https://other.example", wantReason: "does not match"},
{name: "missing ACAO", origin: "https://evil.com", wantReason: "missing"},
{name: "valid reflection with credentials", origin: "https://evil.com", acao: "https://evil.com", acac: "true", wantOK: true},
{name: "opaque reflection", origin: "null", acao: "null", wantOK: true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
req := http.Header{}
req.Set("Origin", tt.origin)
resp := http.Header{}
if tt.acao != "" {
resp.Set("Access-Control-Allow-Origin", tt.acao)
}
if tt.acac != "" {
resp.Set("Access-Control-Allow-Credentials", tt.acac)
}
err := ValidateCORSProof(req, resp)
if tt.wantOK && err != nil {
t.Fatalf("ValidateCORSProof() = %v, want success", err)
}
if !tt.wantOK {
if err == nil {
t.Fatal("ValidateCORSProof() succeeded, want error")
}
if !strings.Contains(strings.ToLower(err.Error()), strings.ToLower(tt.wantReason)) {
t.Fatalf("error %q does not contain %q", err, tt.wantReason)
}
}
})
}
}
func TestValidateCORSProofHeads(t *testing.T) {
err := ValidateCORSProofHeads(
"GET / HTTP/1.1\nOrigin: https://evil.com\n",
"HTTP/1.1 200 OK\nAccess-Control-Allow-Origin: https://evil.com\nAccess-Control-Allow-Credentials: true\n",
)
if err != nil {
t.Fatalf("ValidateCORSProofHeads() = %v, want success", err)
}
err = ValidateCORSProofHeads(
"GET / HTTP/1.1\nOrigin: https://evil.com\n",
"HTTP/1.1 200 OK\nAccess-Control-Allow-Origin: https://other.example\n",
)
if err == nil || !strings.Contains(err.Error(), "does not match") {
t.Fatalf("invalid head proof error = %v, want mismatch", err)
}
}
func TestIsCORSFinding(t *testing.T) {
for _, tc := range []struct {
class string
want bool
}{
{class: "CORS", want: true},
{class: "cors misconfiguration", want: true},
{class: "cors_misconfiguration", want: true},
{class: "course injection", want: false},
{class: "XSS", want: false},
} {
if got := IsCORSFinding(tc.class); got != tc.want {
t.Errorf("IsCORSFinding(%q) = %v, want %v", tc.class, got, tc.want)
}
}
}
+52
View File
@@ -37,6 +37,11 @@ services:
depends_on:
postgres:
condition: service_healthy
artex-runner:
condition: service_healthy
networks:
- default
- runner-net
environment:
# Parts, not a pasted URL. PostgresDSN percent-encodes the password, so a
# value with / ? % @ : or a space still connects.
@@ -71,6 +76,11 @@ services:
ARTEX_TASK_BUDGET_TURNS: ${ARTEX_TASK_BUDGET_TURNS:-}
ARTEX_INTENT_BUDGET_TOKENS: ${ARTEX_INTENT_BUDGET_TOKENS:-}
ARTEX_INTENT_BUDGET_TURNS: ${ARTEX_INTENT_BUDGET_TURNS:-}
# Agent execution runs in disposable per-task worker containers. The
# sandbox images are published beside the panel image.
ARTEX_SANDBOX: ${ARTEX_SANDBOX:-required}
ARTEX_RUNNER_URL: ${ARTEX_RUNNER_URL:-http://artex-runner:8789}
ARTEX_RUNNER_TOKEN: ${ARTEX_RUNNER_TOKEN:?Please set ARTEX_RUNNER_TOKEN in .env}
ports:
- "${ARTEX_BIND_ADDR:-127.0.0.1}:8787:8787"
- "127.0.0.1:8788:8788"
@@ -79,5 +89,47 @@ services:
- ./keys:/app/keys
restart: unless-stopped
artex-runner:
image: ghcr.io/baarai/artex-runner:${ARTEX_IMAGE_TAG:-latest}
networks:
- runner-net
volumes:
- /var/run/docker.sock:/var/run/docker.sock
- ./data/tasks:/app/data/tasks
- ./data/egress-audit:/app/data/egress-audit
environment:
ARTEX_RUNNER_TOKEN: ${ARTEX_RUNNER_TOKEN:?Please set ARTEX_RUNNER_TOKEN in .env}
ARTEX_WORKER_IMAGE: ${ARTEX_WORKER_IMAGE:-ghcr.io/baarai/artex-worker:${ARTEX_IMAGE_TAG:-latest}}
ARTEX_EGRESS_PROXY_IMAGE: ${ARTEX_EGRESS_PROXY_IMAGE:-ghcr.io/baarai/artex-egress-proxy:${ARTEX_IMAGE_TAG:-latest}}
ARTEX_WORKSPACE_ROOT: /app/data/tasks
ARTEX_HOST_WORKSPACE_ROOT: ${ARTEX_HOST_WORKSPACE_ROOT:-./data/tasks}
ARTEX_AUDIT_ROOT: /app/data/egress-audit
ARTEX_HOST_AUDIT_ROOT: ${ARTEX_HOST_AUDIT_ROOT:-./data/egress-audit}
ARTEX_TASK_NET_PREFIX: ${ARTEX_TASK_NET_PREFIX:-artex-task-}
ARTEX_EGRESS_NET: ${ARTEX_EGRESS_NET:-egress-net}
healthcheck:
test: ["CMD-SHELL", "curl -fsS -H \"Authorization: Bearer $$ARTEX_RUNNER_TOKEN\" http://127.0.0.1:8789/v1/health"]
interval: 5s
timeout: 3s
retries: 10
restart: unless-stopped
# Images the runner instantiates per task. They are pulled with
# `docker compose -f docker-compose.ghcr.yml --profile build-only pull`.
artex-worker:
image: ghcr.io/baarai/artex-worker:${ARTEX_IMAGE_TAG:-latest}
profiles: ["build-only"]
artex-egress-proxy:
image: ghcr.io/baarai/artex-egress-proxy:${ARTEX_IMAGE_TAG:-latest}
profiles: ["build-only"]
networks:
runner-net:
internal: true
egress-net:
name: ${ARTEX_EGRESS_NET:-egress-net}
driver: bridge
volumes:
pgdata:
+7 -4
View File
@@ -1,7 +1,10 @@
# ARTEX Sandbox MVP overlay (CONTRACT.md §§1-6).
# Usage:
# docker compose -f docker-compose.yml -f docker-compose.sandbox.yml build
# docker compose -f docker-compose.yml -f docker-compose.sandbox.yml up -d
# ARTEX sandbox compatibility overlay.
#
# Since 0.7.1 the runner, worker and egress proxy are part of
# docker-compose.yml and docker-compose.ghcr.yml, so a plain
# `docker compose up -d` runs the sandbox. This file is kept so existing
# `-f docker-compose.yml -f docker-compose.sandbox.yml` commands keep working;
# it is no longer required.
#
# Security boundary:
# - artex (panel): holds DB credentials, keys, LLM keys; never mounts docker.sock;
+59
View File
@@ -39,6 +39,11 @@ services:
depends_on:
postgres:
condition: service_healthy
artex-runner:
condition: service_healthy
networks:
- default
- runner-net
environment:
# Parts, not a pasted URL. PostgresDSN percent-encodes the password, so a
# value with / ? % @ : or a space still connects. ARTEX_PG_DSN, when set,
@@ -73,6 +78,11 @@ services:
ARTEX_TASK_BUDGET_TURNS: ${ARTEX_TASK_BUDGET_TURNS:-}
ARTEX_INTENT_BUDGET_TOKENS: ${ARTEX_INTENT_BUDGET_TOKENS:-}
ARTEX_INTENT_BUDGET_TURNS: ${ARTEX_INTENT_BUDGET_TURNS:-}
# Agent execution runs in disposable per-task worker containers. The
# runner is part of this compose file; its token must be set in .env.
ARTEX_SANDBOX: ${ARTEX_SANDBOX:-required}
ARTEX_RUNNER_URL: ${ARTEX_RUNNER_URL:-http://artex-runner:8789}
ARTEX_RUNNER_TOKEN: ${ARTEX_RUNNER_TOKEN:?Please set ARTEX_RUNNER_TOKEN in .env}
ports:
- "${ARTEX_BIND_ADDR:-127.0.0.1}:8787:8787"
- "127.0.0.1:8788:8788"
@@ -88,5 +98,54 @@ services:
- ./skills:/app/skills
restart: unless-stopped
artex-runner:
build:
context: .
dockerfile: Dockerfile.runner
image: artex-runner:local
networks:
- runner-net
volumes:
- /var/run/docker.sock:/var/run/docker.sock
- ./data/tasks:/app/data/tasks
- ./data/egress-audit:/app/data/egress-audit
environment:
ARTEX_RUNNER_TOKEN: ${ARTEX_RUNNER_TOKEN:?Please set ARTEX_RUNNER_TOKEN in .env}
ARTEX_WORKER_IMAGE: ${ARTEX_WORKER_IMAGE:-artex-worker:local}
ARTEX_EGRESS_PROXY_IMAGE: ${ARTEX_EGRESS_PROXY_IMAGE:-artex-egress-proxy:local}
ARTEX_WORKSPACE_ROOT: /app/data/tasks
ARTEX_HOST_WORKSPACE_ROOT: ${ARTEX_HOST_WORKSPACE_ROOT:-./data/tasks}
ARTEX_AUDIT_ROOT: /app/data/egress-audit
ARTEX_HOST_AUDIT_ROOT: ${ARTEX_HOST_AUDIT_ROOT:-./data/egress-audit}
ARTEX_TASK_NET_PREFIX: ${ARTEX_TASK_NET_PREFIX:-artex-task-}
ARTEX_EGRESS_NET: ${ARTEX_EGRESS_NET:-egress-net}
healthcheck:
test: ["CMD-SHELL", "curl -fsS -H \"Authorization: Bearer $$ARTEX_RUNNER_TOKEN\" http://127.0.0.1:8789/v1/health"]
interval: 5s
timeout: 3s
retries: 10
restart: unless-stopped
artex-worker:
build:
context: .
dockerfile: Dockerfile.worker
image: artex-worker:local
profiles: ["build-only"]
artex-egress-proxy:
build:
context: .
dockerfile: Dockerfile.egress-proxy
image: artex-egress-proxy:local
profiles: ["build-only"]
networks:
runner-net:
internal: true
egress-net:
name: ${ARTEX_EGRESS_NET:-egress-net}
driver: bridge
volumes:
pgdata:
+24 -4
View File
@@ -28,13 +28,33 @@ from disposable per-task **worker** containers (`artex-worker:local`).
## Running with the sandbox
The runner, worker and proxy are part of `docker-compose.yml` and
`docker-compose.ghcr.yml`. `install.sh` and `update.sh` generate
`ARTEX_RUNNER_TOKEN` and build the three images:
```bash
export ARTEX_RUNNER_TOKEN="$(openssl rand -hex 32)"
docker compose -f docker-compose.yml -f docker-compose.sandbox.yml --profile build-only build
docker compose -f docker-compose.yml -f docker-compose.sandbox.yml build
docker compose -f docker-compose.yml -f docker-compose.sandbox.yml up -d
./install.sh # first install
./update.sh # existing checkout
```
Manual, from a source checkout (put `ARTEX_RUNNER_TOKEN` in `.env` once):
```bash
docker compose build artex artex-runner
docker compose --profile build-only build artex-worker artex-egress-proxy
docker compose up -d
```
From the published images:
```bash
docker compose -f docker-compose.ghcr.yml --profile build-only pull
docker compose -f docker-compose.ghcr.yml up -d
```
`docker-compose.sandbox.yml` is kept as a compatibility overlay; it is no longer
required.
## Breaking change: `ARTEX_SANDBOX=required` by default
Starting with this release, `ARTEX_SANDBOX` defaults to **`required`**. If
+1 -1
View File
@@ -49,7 +49,7 @@ func TestComposeOverlayConfigHasInternalNetworkAndHardening(t *testing.T) {
t.Skip("docker CLI not available; static overlay assertions passed")
}
cmd := exec.Command("docker", "compose", "-f", baseFile, "-f", overlayFile, "config", "--format", "json")
cmd.Env = append(os.Environ(), "POSTGRES_PASSWORD=test")
cmd.Env = append(os.Environ(), "POSTGRES_PASSWORD=test", "ARTEX_RUNNER_TOKEN=testtoken")
out, err := cmd.CombinedOutput()
if err != nil {
t.Fatalf("docker compose config failed: %v\n%s", err, out)
+16 -2
View File
@@ -43,6 +43,16 @@ stamp_version(){
fi
ok "Build identity: ${BUILD_VERSION}${BUILD_REVISION:+ (${BUILD_REVISION:0:12})}"
}
# ensure_runner_token fills ARTEX_RUNNER_TOKEN in .env once. The panel and the
# runner authenticate the internal execution API with it; an empty value makes
# the panel fail closed, so the token is generated with the rest of the setup.
ensure_runner_token(){
[ -f .env ] || return 0
grep -q '^ARTEX_RUNNER_TOKEN=.' .env && return 0
set_env ARTEX_RUNNER_TOKEN "$(rand)"
ok "ARTEX_RUNNER_TOKEN generated"
}
# json_str prints $1 as a JSON string literal: backslash, double quote and the
# control characters read -r can return are escaped.
json_str(){
@@ -156,8 +166,12 @@ install_docker(){
info "reusing existing .env"
fi
stamp_version
info "building the image from this checkout and starting..."
docker compose up -d --build
ensure_runner_token
info "building the panel and the sandbox images from this checkout..."
docker compose build artex artex-runner
docker compose --profile build-only build artex-worker artex-egress-proxy
info "starting..."
docker compose up -d
ok "started → http://localhost:8787"
info "view logs: docker compose logs -f artex"
}
+11 -1
View File
@@ -149,8 +149,18 @@ func (s *Server) bridgeApprovalPress(ctx context.Context, req chatbridge.Request
if !ok || s.m.interceptor == nil {
return chatbridge.CallbackReply{Toast: "This button is not recognized."}
}
// The poller authorized this batch with the allowlist it read at the time.
// Re-read the bridge before spending the button: a member removed, a chat
// unlisted, or the bridge disabled since that snapshot must not count. The
// consume statement below also requires this exact config_version, so a
// save between this read and the press is refused instead of raced.
b, err := s.m.PG().ChatBridgeByKind(ctx, req.Kind)
if err != nil || !b.Enabled || !stillAllowed(b, req) {
log.Printf("%s refused approval press in chat %s from user %s: bridge access changed", tag, req.ChatID, req.UserID)
return chatbridge.CallbackReply{Toast: "This button no longer works. Decide in ARTEX."}
}
by := bridgeApprover(req)
a, err := s.m.PG().UseChatBridgeApproval(ctx, req.Kind, req.ChatID, req.MessageID, approvalNonceHash(nonce), by)
a, err := s.m.PG().UseChatBridgeApproval(ctx, req.Kind, req.ChatID, req.MessageID, approvalNonceHash(nonce), by, b.ConfigVersion)
if err != nil {
log.Printf("%s check approval button in chat %s: %v", tag, req.ChatID, err)
return chatbridge.CallbackReply{Toast: "Could not check the button. Try again."}
+73
View File
@@ -155,3 +155,76 @@ func TestParseApprovalData(t *testing.T) {
}
}
}
// TestChatBridgeApprovalRechecksAccess covers the batch-dispatch race: the
// poller authorized the button with the allowlist it loaded, and the sender is
// removed before the queued press is handled. The handler must re-read the
// bridge, refuse the press, and leave the button open for the current members.
func TestChatBridgeApprovalRechecksAccess(t *testing.T) {
s, task, fake := bridgeCommandServer(t)
ctx := context.Background()
pg := s.m.PG()
tid, _ := strconv.ParseInt(task.ID, 10, 64)
if _, err := pg.SaveChatBridge(ctx, &db.ChatBridge{
Kind: fakeBridgeKind, Enabled: true, Config: json.RawMessage(`{"bot_token":"x"}`),
AllowedChats: []string{"-100"}, AllowedUsers: []string{"7"},
}, false); err != nil {
t.Fatal(err)
}
if err := pg.SetChatBridgeTask(ctx, fakeBridgeKind, "-100", "supergroup", tid); err != nil {
t.Fatal(err)
}
pending, err := pg.CreateInterceptPending(0, 0, task.ID, "worker-1", "bash", []byte(`{"command":"id"}`), "rule says ask")
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _, _ = pg.Exec(`DELETE FROM intercept_pending WHERE id=$1`, pending) })
s.chatBridgeApprovalTick(ctx, fakeBridgeKind)
if len(fake.buttons) != 1 || fake.buttons[0].chatID != "-100" {
t.Fatalf("pushes = %+v, want one to the group", fake.buttons)
}
msg := fake.buttons[0]
allowData := msg.rows[0][0].Data
// The member is removed while the update is queued. The stale dispatcher
// still reaches the handler; the handler must not spend the button.
if _, err := pg.SaveChatBridge(ctx, &db.ChatBridge{
Kind: fakeBridgeKind, Enabled: true, Config: json.RawMessage(`{"bot_token":"x"}`),
AllowedChats: []string{"-100"}, AllowedUsers: []string{},
}, false); err != nil {
t.Fatal(err)
}
reply := s.bridgeApprovalPress(ctx, chatbridge.Request{
Kind: fakeBridgeKind, ChatID: "-100", ChatType: "supergroup", UserID: "7",
Args: allowData, MessageID: msg.messageID,
})
if !strings.Contains(reply.Toast, "no longer works") {
t.Fatalf("removed member press = %+v", reply)
}
if p, _ := pg.GetInterceptPending(pending); p == nil || p.Status != "pending" {
t.Fatalf("removed member decided the request: %+v", p)
}
var open bool
if err := pg.QueryRow(`SELECT closed_at IS NULL FROM chat_bridge_approvals WHERE pending_id=$1`, pending).Scan(&open); err != nil || !open {
t.Fatalf("button after removed member press: open=%v err=%v", open, err)
}
// A current member can still use the same button.
if _, err := pg.SaveChatBridge(ctx, &db.ChatBridge{
Kind: fakeBridgeKind, Enabled: true, Config: json.RawMessage(`{"bot_token":"x"}`),
AllowedChats: []string{"-100"}, AllowedUsers: []string{"7"},
}, false); err != nil {
t.Fatal(err)
}
reply = s.bridgeApprovalPress(ctx, chatbridge.Request{
Kind: fakeBridgeKind, ChatID: "-100", ChatType: "supergroup", UserID: "7",
Args: allowData, MessageID: msg.messageID,
})
if !strings.Contains(reply.Toast, "Allowed") {
t.Fatalf("current member press = %+v", reply)
}
if p, _ := pg.GetInterceptPending(pending); p == nil || p.Status != "allowed" {
t.Fatalf("current member did not decide: %+v", p)
}
}
+44
View File
@@ -0,0 +1,44 @@
package server
import (
"fmt"
"strings"
"testing"
"github.com/Autumn-27/artex/db"
)
func TestCORSVerificationRejectsInvalidBoundProof(t *testing.T) {
s, finding, request := trafficEvidenceServer(t)
if _, err := s.m.pg.Exec(`UPDATE findings SET vulnclass='CORS' WHERE id=$1`, finding.FindingID); err != nil {
t.Fatal(err)
}
trafficID := "cors-invalid-proof"
_, err := s.m.traffic.DB().Exec(`INSERT INTO exchanges(id,ts,host,method,url_template,url,status,content_type,req_len,resp_len,path)
VALUES(?,1,'evidence.local','GET','/','https://evidence.local/',200,'text/plain',0,?,'')`, trafficID, len("cors proof body"))
if err != nil {
t.Fatal(err)
}
_, err = s.m.traffic.DB().Exec(`INSERT INTO exchange_bodies(id,req_head,resp_head,req_body,resp_body)
VALUES(?, ?, ?, ?, ?)`, trafficID,
"GET / HTTP/1.1\nOrigin: https://evil.com\n",
"HTTP/1.1 200 OK\nAccess-Control-Allow-Origin: https://other.example\n",
[]byte{}, []byte("cors proof body"))
if err != nil {
t.Fatal(err)
}
bindPath := fmt.Sprintf("/api/exploration/findings/%d/traffic", finding.FindingID)
if w := request("POST", bindPath, fmt.Sprintf(`{"traffic_refs":[{"traffic_id":%q,"role":"proof"}]}`, trafficID)); w.Code != 200 {
t.Fatalf("bind: %d %s", w.Code, w.Body)
}
msg, isErr := updateReport(t, s, finding.NodeID, `,"poe_level":3,"evidence_quotes":["cors proof body"]`)
if isErr || !strings.Contains(msg, "verification: unverified") {
t.Fatalf("unexpected result: err=%v %q", isErr, msg)
}
status, _, note, report := storedVerification(t, s, finding.FindingID)
if status != db.VerificationUnverified || !strings.Contains(note, "CORS proof validation failed") || report == "" {
t.Fatalf("stored: status=%s note=%q report=%q", status, note, report)
}
}
+14
View File
@@ -138,6 +138,13 @@ func readBoundResponse(store *evidence.Store, snap db.TrafficEvidenceSnapshot) (
// its bound traffic and the quotes the agent supplied. poe is the declared POE
// level (0 when absent). It never returns "verified" unless every rule passes.
func (s *Server) assessFindingVerification(ctx context.Context, findingID int64, poe int, quotes []string) (status, note string) {
finding, err := s.m.pg.GetFinding(findingID)
if err != nil {
return db.VerificationNotAssessed, "finding read error: " + err.Error()
}
if finding == nil {
return db.VerificationNotAssessed, "finding not found"
}
tr, err := s.m.pg.GetFindingTraffic(ctx, findingID)
if err != nil {
return db.VerificationNotAssessed, "binding read error: " + err.Error()
@@ -151,6 +158,13 @@ func (s *Server) assessFindingVerification(ctx context.Context, findingID int64,
if len(proofs) == 0 {
return db.VerificationUnverified, "no proof traffic bound"
}
if db.IsCORSFinding(finding.VulnClass) {
for _, proof := range proofs {
if err := db.ValidateCORSProofHeads(proof.Snapshot.ReqHead, proof.Snapshot.RespHead); err != nil {
return db.VerificationUnverified, "CORS proof validation failed: " + err.Error()
}
}
}
if poe < verificationMinPOE {
return db.VerificationUnverified, fmt.Sprintf("POE L%d below L3", poe)
}
+30 -2
View File
@@ -10,6 +10,7 @@ import (
"strings"
"syscall"
"testing"
"time"
)
// isolationRootFixture is newExecRootFixture with the Bash shim installed, a key
@@ -73,9 +74,36 @@ func TestIsolationSelfTestDetectsReadableSecretAsRoot(t *testing.T) {
if err := os.Chmod(key, 0o644); err != nil {
t.Fatal(err)
}
var st syscall.Stat_t
if err := syscall.Stat(key, &st); err != nil {
t.Fatal(err)
}
err := IsolationSelfTest(f.priv, f.targets())
if err == nil || !strings.Contains(err.Error(), "Bash can read "+key) || !strings.Contains(err.Error(), "the file tools can read "+key) {
t.Fatalf("self-test with a world-readable key: %v", err)
if err == nil {
t.Fatal("self-test accepted a world-readable key")
}
for _, actor := range []string{"Bash", "the file tools"} {
if !strings.Contains(err.Error(), actor+" opened "+key+" for reading (mode=-rw-r--r-- uid=0 gid="+strconv.FormatUint(uint64(st.Gid), 10)+")") {
t.Errorf("self-test with a world-readable key did not report its metadata for %s: %v", actor, err)
}
}
}
func TestSecretOpenFailureOnFIFO(t *testing.T) {
path := filepath.Join(t.TempDir(), "key")
if err := syscall.Mkfifo(path, 0o600); err != nil {
t.Fatal(err)
}
// A FIFO with no writer must still be reported without waiting for bytes.
done := make(chan string, 1)
go func() { done <- secretOpenFailure("probe", path) }()
select {
case msg := <-done:
if !strings.Contains(msg, "opened "+path+" for reading (mode=p") {
t.Fatalf("unexpected FIFO diagnostic: %q", msg)
}
case <-time.After(5 * time.Second):
t.Fatal("probe blocked on a FIFO with no writer")
}
}
+29 -16
View File
@@ -258,30 +258,44 @@ func skillTreeFailures(root string, execUID, execGID uint32) []string {
return failures
}
// fileToolIsolationFailures opens each existing secret through the file tool
// identity (agent/filetools_identity.go): the open must be refused.
// secretOpenFailure checks the open under the caller's identity. Inspect the
// descriptor so the diagnostic describes the object at the time of the probe.
func secretOpenFailure(actor, path string) string {
f, err := os.OpenFile(path, os.O_RDONLY|syscall.O_NONBLOCK|syscall.O_NOCTTY, 0)
if errors.Is(err, fs.ErrNotExist) || errors.Is(err, fs.ErrPermission) {
return ""
}
if err != nil {
return fmt.Sprintf("%s could not check %s: %v", actor, path, err)
}
defer f.Close()
msg := fmt.Sprintf("%s opened %s for reading", actor, path)
info, err := f.Stat()
if err != nil {
return fmt.Sprintf("%s (stat failed: %v)", msg, err)
}
if st, ok := info.Sys().(*syscall.Stat_t); ok {
return fmt.Sprintf("%s (mode=%s uid=%d gid=%d)", msg, info.Mode(), st.Uid, st.Gid)
}
return fmt.Sprintf("%s (mode=%s)", msg, info.Mode())
}
// fileToolIsolationFailures checks each secret through the file tool identity.
func fileToolIsolationFailures(secrets []string) []string {
if !agent.FileToolIdentitySupported() {
return []string{"the agent's file tools run with the server's identity on this platform"}
}
var failures []string
for _, path := range secrets {
if _, err := os.Stat(path); err != nil {
continue
}
var openErr error
var failure string
if err := agent.RunAsFileToolIdentity(func() {
f, err := os.Open(path)
if err == nil {
f.Close()
}
openErr = err
failure = secretOpenFailure("the file tools", path)
}); err != nil {
failures = append(failures, fmt.Sprintf("the file tool identity cannot be applied: %v", err))
break
}
if openErr == nil {
failures = append(failures, fmt.Sprintf("the file tools can read %s", path))
if failure != "" {
failures = append(failures, failure)
}
}
return failures
@@ -350,9 +364,8 @@ func checkIsolationAsExecutor(spec isolationProbeSpec) []string {
fail("Bash has the supplementary groups %v, want only the executor gid %d", groups, spec.GID)
}
for _, path := range spec.Unreadable {
if f, err := os.Open(path); err == nil {
f.Close()
fail("Bash can read %s", path)
if failure := secretOpenFailure("Bash", path); failure != "" {
failures = append(failures, failure)
}
}
if spec.ServerPID > 0 {
+21 -1
View File
@@ -97,7 +97,7 @@ func TestCheckIsolationReportsEachExposure(t *testing.T) {
})
for _, want := range []string{
"not the executor uid 10001",
"Bash can read " + secret,
"Bash opened " + secret + " for reading (mode=-rw-------",
"Bash can create files in " + dir,
"ARTEX_ISOLATION_CANARY reached Bash",
`database session as "artex"`,
@@ -114,6 +114,26 @@ func TestCheckIsolationReportsEachExposure(t *testing.T) {
}
}
func TestSecretOpenFailureReportsUnexpectedError(t *testing.T) {
link := filepath.Join(t.TempDir(), "key")
if err := os.Symlink(link, link); err != nil {
t.Fatal(err)
}
if msg := secretOpenFailure("probe", link); !strings.HasPrefix(msg, "probe could not check "+link) {
t.Fatalf("unexpected diagnostic for a symlink loop: %q", msg)
}
}
func TestSecretOpenFailureDetectsReadableKeyDir(t *testing.T) {
dir := filepath.Join(t.TempDir(), "keys")
if err := os.MkdirAll(dir, 0o755); err != nil {
t.Fatal(err)
}
if msg := secretOpenFailure("Bash", dir); !strings.Contains(msg, "Bash opened "+dir+" for reading (mode=d") {
t.Fatalf("unexpected diagnostic for readable key dir: %q", msg)
}
}
// A database that asks for a password, or none listening, is not an exposure.
func TestConnectWithoutPasswordRefused(t *testing.T) {
ln, err := net.Listen("tcp", "127.0.0.1:0")
+13
View File
@@ -6,6 +6,7 @@ import (
"log"
"time"
"github.com/Autumn-27/artex/agent"
"github.com/Autumn-27/artex/db"
"github.com/Autumn-27/artex/mcphttp"
"github.com/Autumn-27/norma/mcp"
@@ -51,9 +52,21 @@ func connectMCP(ctx context.Context, m *db.MCPServer, priv ExecPrivilege) (mcpCl
}
}
// sandboxBlocksStdioMCP reports whether this stdio MCP must not run on the
// panel. In ARTEX_SANDBOX=required the panel never starts agent-controlled
// local processes: stdio MCP servers stay unavailable until the per-task
// runner hosts them. HTTP and SSE MCP clients are platform-owned transports and
// keep their existing checks.
func sandboxBlocksStdioMCP(m *db.MCPServer) bool {
return agent.SandboxRequired() && (m.Transport == "" || m.Transport == "stdio")
}
// discoverAndCacheMCP connects to one MCP, lists its tools, and persists the tool
// names to mcp_tools_cache so the UI shows them without a live connection.
func (s *Server) discoverAndCacheMCP(ctx context.Context, m *db.MCPServer) error {
if sandboxBlocksStdioMCP(m) {
return fmt.Errorf("stdio MCP servers are not started on the panel while ARTEX_SANDBOX=required; use an HTTP/SSE MCP server or set ARTEX_SANDBOX=off")
}
cl, err := connectMCP(ctx, m, s.execPriv)
if err != nil {
_ = s.m.pg.UpdateMCPHealth(m.ID, false, err.Error())
+69
View File
@@ -0,0 +1,69 @@
package server
import (
"context"
"encoding/json"
"os"
"path/filepath"
"strings"
"testing"
"github.com/Autumn-27/artex/agent"
"github.com/Autumn-27/artex/db"
"github.com/Autumn-27/artex/sandbox"
)
func withSandboxRequired(t *testing.T) {
t.Helper()
prev := agent.CurrentSandboxExecutor()
agent.SetSandboxExecutor(&agent.SandboxExecutor{Mode: sandbox.ModeRequired})
t.Cleanup(func() { agent.SetSandboxExecutor(prev) })
}
// The panel must never start a stdio MCP process in required mode. The canary
// command would create a file if connectMCP reached it; the guard returns before
// the process is spawned.
func TestSandboxSkipsStdioMCPDiscovery(t *testing.T) {
withSandboxRequired(t)
dir := t.TempDir()
canary := filepath.Join(dir, "stdio-mcp-ran")
args, _ := json.Marshal([]string{"-c", "touch " + canary})
m := &db.MCPServer{Name: "t-sandbox-stdio", Transport: "stdio", Command: "sh", Args: args, Enabled: true}
s := &Server{}
err := s.discoverAndCacheMCP(context.Background(), m)
if err == nil || !strings.Contains(err.Error(), "ARTEX_SANDBOX=required") {
t.Fatalf("discovery error = %v, want the sandbox refusal", err)
}
if _, statErr := os.Stat(canary); statErr == nil {
t.Fatal("stdio MCP command ran on the panel in required mode")
}
}
func TestSandboxMCPToolGuardsStdioOnly(t *testing.T) {
withSandboxRequired(t)
for _, tc := range []struct {
transport string
blocked bool
}{
{"", true},
{"stdio", true},
{"http", false},
{"sse", false},
} {
if got := sandboxBlocksStdioMCP(&db.MCPServer{Transport: tc.transport}); got != tc.blocked {
t.Errorf("transport %q blocked=%v, want %v", tc.transport, got, tc.blocked)
}
}
}
func TestSandboxCreateMCPRejectsStdio(t *testing.T) {
withSandboxRequired(t)
tool := (&Server{}).toolCreateMCP()
res, err := tool.Call(context.Background(), json.RawMessage(`{"name":"t-stdio","transport":"stdio","command":"sh"}`), nil)
if err != nil {
t.Fatal(err)
}
if !res.IsError || !strings.Contains(res.Flatten(), "ARTEX_SANDBOX=required") {
t.Fatalf("create_mcp result = %q, want the sandbox refusal", res.Flatten())
}
}
+6
View File
@@ -370,6 +370,9 @@ func (s *Server) toolCreateMCP() actool.CoreTool {
if strings.TrimSpace(a.Name) == "" || strings.TrimSpace(a.Transport) == "" {
return actool.Errorf("name / transport are required"), nil
}
if sandboxBlocksStdioMCP(a.toDB()) {
return actool.Errorf("stdio MCP servers are unavailable while ARTEX_SANDBOX=required; use an HTTP/SSE MCP server or set ARTEX_SANDBOX=off"), nil
}
id, err := s.m.pg.SaveMCP(a.toDB())
if err != nil {
return actool.Errorf(err.Error()), nil
@@ -387,6 +390,9 @@ func (s *Server) toolUpdateMCP() actool.CoreTool {
if a.ID == 0 {
return actool.Errorf("id is required"), nil
}
if sandboxBlocksStdioMCP(a.toDB()) {
return actool.Errorf("stdio MCP servers are unavailable while ARTEX_SANDBOX=required; use an HTTP/SSE MCP server or set ARTEX_SANDBOX=off"), nil
}
if _, err := s.m.pg.SaveMCP(a.toDB()); err != nil {
return actool.Errorf(err.Error()), nil
}
+20 -6
View File
@@ -11,6 +11,7 @@ ok(){ printf '\033[32m[+]\033[0m %s\n' "$*"; }
warn(){ printf '\033[33m[!]\033[0m %s\n' "$*"; }
die(){ printf '\033[31m[x]\033[0m %s\n' "$*" >&2; exit 1; }
ask(){ local p="$1" d="${2:-}" a; read -rp "$p${d:+ [$d]}: " a; echo "${a:-$d}"; }
rand(){ head -c 18 /dev/urandom | base64 | tr -dc 'A-Za-z0-9' | head -c 24; }
# ── Build identity: keep .env and the binary in step with the checkout ─────────
BUILD_VERSION="dev"
@@ -46,6 +47,16 @@ stamp_version(){
ok "Build identity: ${BUILD_VERSION}${BUILD_REVISION:+ (${BUILD_REVISION:0:12})}"
}
# ensure_runner_token fills ARTEX_RUNNER_TOKEN in .env once. The panel and the
# runner authenticate the internal execution API with it; an empty value makes
# the panel fail closed, so an existing .env gets one before the upgrade.
ensure_runner_token(){
[ -f .env ] || return 0
grep -q '^ARTEX_RUNNER_TOKEN=.' .env && return 0
set_env ARTEX_RUNNER_TOKEN "$(rand)"
ok "ARTEX_RUNNER_TOKEN generated"
}
# ── Optional: sync the repo to the latest code (compose/scripts/local build sources all update through it) ───────
sync_repo(){
[ -d .git ] && command -v git >/dev/null 2>&1 || { warn "not a git working copy, skipping git pull"; return 0; }
@@ -73,12 +84,15 @@ update_docker(){
|| die "docker buildx not detected; the image build needs it (see the Docker section of the README)"
[ -f .env ] || die ".env not found; run ./install.sh first to complete the initial deployment"
# Touch only artex: postgres is pinned to 16-alpine and does not need upgrading along
# (pulling it wastes bandwidth, and a major version bump risks compatibility). artex
# declares depends_on postgres, so an up with the service name starts pg if needed and leaves a running one untouched.
info "Building the image from this checkout (artex only)…"
docker compose build artex
info "Recreating artex (schema migrates automatically on restart)…"
ensure_runner_token
# Touch only artex and artex-runner: postgres is pinned to 16-alpine and does not
# need upgrading along (pulling it wastes bandwidth, and a major version bump
# risks compatibility). The worker and proxy images are built locally because the
# runner creates one container of each per task.
info "Building the panel and the sandbox images from this checkout…"
docker compose build artex artex-runner
docker compose --profile build-only build artex-worker artex-egress-proxy
info "Recreating artex and artex-runner (schema migrates automatically on restart)…"
docker compose up -d artex
ok "Update complete → http://localhost:8787"
info "View logs: docker compose logs -f artex"