Files
BaaRai 9d887c0df3 Merge pull request #1054 from AdrianSantamariaR/fix/sandbox-dual-stack-ipv6
fix(sandbox): allow public global IPv6 and prefer IPv4 on dual-stack hosts
2026-12-06 20:10:23 +01:00

191 lines
13 KiB
Markdown

# ARTEX Sandbox MVP (`docker-compose.sandbox.yml`)
The sandbox overlay separates the privileged **panel** (`artex`, holding
PostgreSQL credentials, `jwt.key`, `secret.key`, `config.json`, and LLM keys)
from disposable per-task **worker** containers (`artex-worker:local`).
## Components
1. **`artex` (panel)**: API, UI, DB-only tools (`report_finding`, `insert_assets`,
`record_fact`). Never mounts `/var/run/docker.sock` and never executes agent
commands locally when `ARTEX_SANDBOX=required` (default).
2. **`artex-runner` (`:8789` on internal `runner-net`)**: The **only** service
mounting an engine socket. The host side comes from `ARTEX_DOCKER_SOCK` (default
`/var/run/docker.sock`, set automatically for rootless Podman), and it is always
mounted at `/var/run/docker.sock` inside the runner so that path is the only one
the runner ever dials. Requires `Authorization: Bearer $ARTEX_RUNNER_TOKEN`
on every endpoint including `GET /v1/health`. Creates and tracks one worker +
one egress proxy per task by Docker label (`artex.task=<id>`).
3. **`artex-worker-<id>` (`artex-worker:local`)**: Runs as `10001:10001`,
`--read-only`, `--cap-drop ALL`, `--security-opt no-new-privileges:true`,
`--pids-limit 512`, `--memory 2g`, `--cpus 2`, bounded `tmpfs` on `/tmp` and
`/home/exec`, mounted **only** with `/app/data/tasks/<id>:/workspace:rw`, and
attached **only** to the per-task `internal: true` network `artex-task-<id>`.
4. **`artex-egress-<id>` (`artex-egress-proxy:local`)**: Attached to
`artex-task-<id>` and `egress-net`. Enforces the task's domain suffix and CIDR
allowlists (deny by default, blocking RFC1918, loopback, link-local, metadata
endpoints `169.254.169.254`, `fd00:ec2::254`, `168.63.129.16`, `100.100.100.200`,
and non-public/special-use IPv6 outside global unicast `2000::/3` unless explicitly in `ARTEX_SCOPE_CIDRS`) on both HTTP/HTTPS CONNECT
(`:3128`) and SOCKS5 (`:1080`) with DNS pinning (no rebinding window).
No scope opens loopback, the unspecified addresses, link-local
(`169.254.0.0/16`, `fe80::/10`), `168.63.129.16`, `100.100.100.200`,
`fd00:ec2::254`, `fd20:ce::254`, the subnets of `egress-net` (every task's
proxy is on it) and of the task network, the gateway of every bridge network
(an address of the Docker host), or the NAT64 forms of the denied IPv4
ranges: the runner reads the networks when it creates the proxy and passes
the list as `ARTEX_NEVER_CIDRS`. The host's other addresses (LAN, public)
stay reachable when a scope covers them.
`ARTEX_TASK_DNS` can pin the proxy's resolver; the worker never resolves
names. Logs one JSON line per connection to `/app/data/egress-audit/<id>/egress.jsonl` and stdout.
## 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
./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
`artex-runner` is unavailable, ARTEX refuses to start new tasks and pauses
running tasks rather than falling back to local execution on the panel.
To opt out explicitly in development (degraded mode — logs a prominent startup
warning banner and records `sandbox=off` in every task event log):
```bash
ARTEX_SANDBOX=off
```
### Tool availability in required mode
Task commands use the tools installed in the worker image. The stock worker
includes Bash, curl, DNS utilities, Git, jq, Nmap, and Python. The panel and
worker have separate package lists in [the panel Dockerfile](../Dockerfile) and
[the worker Dockerfile](../Dockerfile.worker). The task egress policy also
applies to any runtime dependency downloads initiated inside the worker.
In required mode, a finding retest gets its own worker, egress proxy and
workspace at `tasks/retest-<conversation-id>`. Bash and the confined file tools
share that workspace. The first retest turn inherits the source task's current
operator-approved egress scope through the same scope builder as normal tasks.
Finding evidence, retest notes and conversation approval pins do not grant
egress. A finding without a source task or approved scope can run local commands
in the worker, but its network access remains denied by default. The conversation's
target approval gate still applies.
The worker, proxy and network are removed when the retest finishes, fails or is
cancelled; workspace files and the conversation transcript are retained. A new
retest uses a new workspace. Follow-up discussion of a completed retest and
ordinary standalone chats do not gain sandbox execution context (see #805).
Check the transcript before interpreting **Cannot confirm**: a denied target,
missing worker dependency or unavailable runner still prevents verification.
## Startup permission migration
With a root server and executor privilege dropping enabled, the first start
repairs existing task/session workspace permissions recursively. Successful
directory migrations are recorded in `<data>/.exec-permissions-v1` (root-owned,
0700, outside task archives). Later starts check task/session/run directory
metadata without opening the contents of unchanged, migrated workspaces.
Missing records, a changed executor UID/GID, replaced directories, changed root
permissions or direct additions/removals trigger another migration of that
directory. Archive restores always repair the extracted tree. Records are
published only after successful migration of a stable directory snapshot; an
interrupted pass or additions/removals during the walk are retried. Replacing
the directory during migration fails startup rather than certifying a different tree.
Without a cache (including archive restores), concurrent writes do not add a
new failure condition; ordinary I/O and hard-link errors still fail the repair.
This is a **first-start migration**, not a recurring permission repair. Unlike
previous releases, a restart does not repair files or directories newly created
below an already-migrated root: nested 0600/0700 entries stay that way, and may
be inaccessible to the executor. After an external restore or manual changes **inside** an
existing workspace, remove `<data>/.exec-permissions-v1` while ARTEX is stopped
to force a complete repair at the next start. Preserve file permissions when
copying data. A data directory writable by other users cannot safely hold these
records, so it retains the full startup walk.
Isolation self-tests, key protection and recursive repair's symlink/hard-link
checks remain enabled. Traffic blob permission scanning is unchanged. Startup
logs report reused/migrated directory counts and elapsed permission-setup time.
## Security Hardening Notes
### Worker cleanup after execution errors
Command timeout, cancellation or a broken execution stream removes the worker
container that ran the command. The runner also removes it when Docker cannot
confirm that the exec has finished. This terminates detached children and **all
other concurrent commands and background services in that task**. The next exec
recreates the worker; the task's `/workspace` directory survives. Successful
commands keep their worker and may leave intentional background services running.
Cleanup uses the captured container ID, so a delayed completion cannot remove a
replacement worker or another task's worker. Failed removal returns an error and
keeps the worker tracked for retry. Deleting a task removes its worker before its
proxy and network, including when no application processes remain in the worker.
Run the unit and simulated Engine tests with `go test -race ./sandbox`. On a
dedicated Docker host with the sandbox images built, enable the detached-child
cleanup test with:
```bash
ARTEX_SANDBOX_DOCKER_TEST=1 go test ./sandbox -run TestDockerTimeoutRemovesDetachedChild -v
```
- **Tamper-proof egress audit log**: `artex-egress-<id>` writes JSONL connection logs to a proxy-only bind mount (`/app/data/egress-audit/<id>/egress.jsonl`, mounted at `/audit:rw` inside the proxy) and stdout. The worker container only mounts `/app/data/tasks/<id>:/workspace:rw` and cannot read, truncate, or forge the egress audit log.
- **Kernel-backed kill-switch (no agent-writable state)**: `artex-worker-<id>` runs `/usr/local/bin/artex-exec-wrap --init` as PID 1 (reaping all orphaned children). On `POST /v1/tasks/{id}/kill`, `artex-runner` executes `/usr/local/bin/artex-exec-wrap --kill-uid 10001` as uid `10001` (preserving `--cap-drop ALL`) scanning `/proc` directly (defeating `setsid`, `nohup`, nested double-forked daemons, `trap '' TERM`, and `/tmp` tampering), verifies zero non-PID-1 uid-10001 processes remain, and falls back to force-removing the worker container if any check fails.
- **Browser & `WebFetch` containment**: In `ARTEX_SANDBOX=required` mode, local stdio MCP servers (including the default private browser MCP) are skipped on the panel; `WebFetch` enforces the task's `sandbox.EgressPolicy` on every URL, redirect hop, and pinned dial (with direct retry disabled); and the opt-in panel-hosted shared browser MCP is only attached when `target_gate` is enabled or an explicit egress proxy is configured, with every browser navigation URL gated against the task's `sandbox.EgressPolicy` (execution containment + scope-gated panel fetch/browser; full subresource browser network isolation requires running the shared browser behind `egress-guard` in `EGRESS_MODE=enforce`).
- **No scope drift (`approved_by_operator`)**: Only operator-approved `task_scope` rows (`approved_by_operator = true`, set exclusively via the operator API/UI or `TaskCreateOptions.CompanyIDs`) and operator `task_intercept_rules` grant sandbox egress to Bash, `WebFetch`, and the shared browser. Agent-added (`add_task_scope`), auto-added (`insert_assets`), and expanded rows are coverage-only (`approved_by_operator = false`). Tasks with no approved scope deny all egress by default.
### Operator Scope Writers & Archive Restore Semantics
| Write path | Sets `approved_by_operator` | Notes |
|---|---|---|
| `POST /api/tasks` (`TaskCreateOptions.CompanyIDs`, operator API) | `true` | Operator-selected companies at task creation |
| `POST /api/tasks/{id}/scope` (`AddOperatorScope`) | `true` | Operator API/UI; promotes existing unapproved coverage row if present |
| `POST /api/tasks/{id}/retarget` (`db.RetargetTask`) | `true` | Operator retarget to a newly provisioned target host |
| `add_task_scope` (`AddAgentScope`) | `false` | Agent coverage-only (even if `source="manual"` is passed) |
| `insert_assets` (`AddAutoScope`) | `false` | Auto-discovered coverage-only |
| `spawn_task` (`CompanyScopeByAgent: true`) | `false`; `true` only for a company whose whole inventory the operator approved **and** the calling task is itself operator-approved for | Standing consent inherits only through the caller's trust boundary (#841); a spawn with no task caller (chat session, direct API) stays coverage-only pending operator confirmation (#830) |
| Archive restore (`restoreTaskScopes`) | preserved (`false` if absent) | Post-0023 archives preserve `approved_by_operator`; legacy pre-0023 archives default to `false` (fail-closed — operators must re-approve scope rows before sandbox egress is granted) |
### Target-Gate Approval vs. Worker Egress (MVP Behavior)
In `ARTEX_SANDBOX=required` mode, **target-gate approval only clears the tool-call approval gate; worker egress (as well as sandbox `WebFetch` and shared-browser navigation) still requires an operator-approved Task Scope entry (`POST /api/tasks/{id}/scope`) or a task allow rule.**
This behavior is surfaced explicitly rather than failing silently:
- Approving a pending target-gate request via `POST /api/intercept/pending/{id}/decide` or `POST /api/intercept/pending/batch-decide` includes `sandbox_egress_note` in the JSON response when `ARTEX_SANDBOX=required`.
- Every sandbox egress denial from the per-task proxy (`HTTP 403`), `WebFetch`, and the shared browser states verbatim that target-gate approval only clears the tool gate and directs the operator to approve the target in Task Scope.
### Upgrade Notes (Migration `0023`)
- Migration `0023_task_scope_operator_approval.sql` adds `task_scope.approved_by_operator BOOLEAN NOT NULL DEFAULT FALSE` and backfills `approved_by_operator = TRUE` for all existing `source = 'manual'` rows so upgraded operator-scoped tasks retain sandbox egress immediately.
- Goal-derived/agent scopes (`source = 'agent'`, created via `add_task_scope`) and auto-discovered scopes (`source = 'auto'`, created via `insert_assets`) remain `approved_by_operator = FALSE` (coverage-only) and **must be re-approved once via the Task Scope UI (`POST /api/tasks/{id}/scope`)** if sandbox egress is required for those hosts.