ARTEX/docs/SANDBOX.md
BaaRai 406153628c
Merge pull request #798 from 00xcyd/fix/742-configurable-docker-sock
sandbox: make the runner Docker socket configurable (rootless Podman, #742)
2026-12-02 23:34:44 +01:00

141 lines
9.9 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 IPv6 unless explicitly in `ARTEX_SCOPE_CIDRS`) on both HTTP/HTTPS CONNECT
(`:3128`) and SOCKS5 (`:1080`) with DNS pinning (no rebinding window). 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.
Finding retests run in a conversation without a task sandbox context. In
required mode, Bash reports a missing task sandbox context and WebFetch can
reject the request for lack of a task egress policy. When these restrictions
prevent verification, a retest may return **Cannot confirm**. Check the retest
transcript for the reason before interpreting the result.
## 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.