Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,9 @@
## [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/).
Expand Down
18 changes: 18 additions & 0 deletions Dockerfile.egress-proxy
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
# ARTEX per-task egress allowlist proxy (HTTP/CONNECT :3128 + SOCKS5 :1080, CONTRACT.md §5).
FROM --platform=$BUILDPLATFORM golang:1.26.11-bookworm@sha256:dc40a13b61304647ed7e5d581d246b86413dfc29d63c6d018310feb93cd98fc0 AS build
WORKDIR /src
COPY go.mod go.sum ./
COPY sandbox/ ./sandbox/
COPY cmd/artex-egress-proxy/ ./cmd/artex-egress-proxy/
ARG TARGETOS=linux
ARG TARGETARCH=amd64
RUN CGO_ENABLED=0 GOOS=${TARGETOS} GOARCH=${TARGETARCH} go build -trimpath -ldflags="-s -w" \
-o /out/artex-egress-proxy ./cmd/artex-egress-proxy

FROM debian:bookworm-slim
RUN apt-get update && apt-get install -y --no-install-recommends ca-certificates && rm -rf /var/lib/apt/lists/* \
&& groupadd -g 10001 exec && useradd -u 10001 -g 10001 -d /nonexistent -s /usr/sbin/nologin exec
COPY --from=build /out/artex-egress-proxy /usr/local/bin/artex-egress-proxy
USER 10001:10001
EXPOSE 3128 1080
ENTRYPOINT ["/usr/local/bin/artex-egress-proxy"]
19 changes: 19 additions & 0 deletions Dockerfile.runner
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
# ARTEX sandbox runner service (CONTRACT.md §2).
# The ONLY component that mounts /var/run/docker.sock.
FROM --platform=$BUILDPLATFORM golang:1.26.11-bookworm@sha256:dc40a13b61304647ed7e5d581d246b86413dfc29d63c6d018310feb93cd98fc0 AS build
WORKDIR /src
COPY go.mod go.sum ./
COPY sandbox/ ./sandbox/
COPY cmd/artex-runner/ ./cmd/artex-runner/
ARG ARTEX_VERSION=dev
ARG TARGETOS=linux
ARG TARGETARCH=amd64
RUN CGO_ENABLED=0 GOOS=${TARGETOS} GOARCH=${TARGETARCH} go build -trimpath \
-ldflags="-s -w -X main.version=${ARTEX_VERSION}" \
-o /out/artex-runner ./cmd/artex-runner

FROM debian:bookworm-slim
RUN apt-get update && apt-get install -y --no-install-recommends ca-certificates curl && rm -rf /var/lib/apt/lists/*
COPY --from=build /out/artex-runner /usr/local/bin/artex-runner
EXPOSE 8789
ENTRYPOINT ["/usr/local/bin/artex-runner"]
34 changes: 34 additions & 0 deletions Dockerfile.worker
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
# ARTEX isolated per-task worker image (CONTRACT.md §4).
# Runs as uid/gid 10001, read-only rootfs, cap_drop ALL, no-new-privileges,
# mounted ONLY with /app/data/tasks/<id>:/workspace:rw and connected ONLY to
# the per-task internal network artex-task-<id>.
FROM --platform=$BUILDPLATFORM golang:1.26.11-bookworm@sha256:dc40a13b61304647ed7e5d581d246b86413dfc29d63c6d018310feb93cd98fc0 AS wrap-build
WORKDIR /src
COPY go.mod go.sum ./
COPY cmd/artex-exec-wrap/ ./cmd/artex-exec-wrap/
ARG TARGETOS=linux
ARG TARGETARCH=amd64
RUN CGO_ENABLED=0 GOOS=${TARGETOS} GOARCH=${TARGETARCH} go build -trimpath -ldflags="-s -w" -o /out/artex-exec-wrap ./cmd/artex-exec-wrap

FROM debian:bookworm-slim
RUN set -eux; \
apt-get update; \
apt-get install -y --no-install-recommends \
bash ca-certificates curl dnsutils git iputils-ping jq netcat-openbsd \
nmap openssh-client perl python3 procps; \
rm -rf /var/lib/apt/lists/*; \
groupadd -g 10001 exec; \
useradd -u 10001 -g 10001 -d /home/exec -m -s /bin/bash exec; \
mkdir -p /workspace /home/exec; \
chown -R 10001:10001 /workspace /home/exec; \
find / -xdev -perm /6000 -type f -exec chmod a-s {} +

COPY --from=wrap-build /out/artex-exec-wrap /usr/local/bin/artex-exec-wrap
RUN chmod 0755 /usr/local/bin/artex-exec-wrap

USER 10001:10001
WORKDIR /workspace
ENV HOME=/home/exec \
LANG=C.UTF-8 \
TERM=xterm
CMD ["sleep", "infinity"]
20 changes: 20 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -1167,3 +1167,23 @@ This project is provided "as is", without any express or implied warranty. The a
contributors are not liable for any direct or indirect loss, data loss, system damage or legal
dispute caused by the use of this tool (whether used properly or not). **Downloading, installing or
using this project means you have read, understood and agreed to all of the above terms.**

## Container Sandbox (`ARTEX_SANDBOX=required` default)

> **Breaking change:** `ARTEX_SANDBOX` defaults to `required`. Agent commands
> (`Bash`, shell, custom command/script tools) execute inside disposable per-task
> `artex-worker` containers via `artex-runner` rather than on the panel container.
> If `artex-runner` is unavailable, ARTEX refuses to start tasks and pauses
> running tasks with no local fallback. To explicitly opt out for local
> 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:

```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
```

See [`docs/SANDBOX.md`](docs/SANDBOX.md) for the runner API, per-task internal
network, HTTP/SOCKS5 egress allowlist proxy, and security boundary.
11 changes: 11 additions & 0 deletions SECURITY.md
Original file line number Diff line number Diff line change
Expand Up @@ -97,3 +97,14 @@ We welcome ethical security research. If you follow this policy and test only wi
- If you do not receive a response within a reasonable time, please ping the contact channel above before disclosing.

Thank you for helping make ARTEX safer.

## Key rotation & fail-closed startup

- **Fail-closed startup**: ARTEX tightens the key directory to `0700` on startup
(counteracting host bind mounts that mask the image's `0700`), verifies in
`IsolationSelfTest` that `keys/`, `jwt.key`, `secret.key`, and `config.json`
are unreadable by the executor UID, and refuses to start if isolation checks
fail unless `ARTEX_ALLOW_UNISOLATED=1` is explicitly set.
- **Secret rotation**: Use `scripts/rotate-secrets.sh` (see `docs/OPS.md`) to
atomically rotate `jwt.key` and `secret.key`, re-encrypt all database secrets
at rest in one transaction, and invalidate all active JWT sessions.
2 changes: 2 additions & 0 deletions agent/filetools.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,8 @@ func defaultTools(base string) []actool.CoreTool {
for _, t := range all {
if run, ok := confinedFileToolNames[t.Name()]; ok {
t = &confinedFileTool{CoreTool: t, base: base, run: run}
} else if t.Name() == "Bash" {
t = &sandboxBashTool{CoreTool: t}
}
out = append(out, t)
}
Expand Down
236 changes: 236 additions & 0 deletions agent/sandbox.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,236 @@
package agent

import (
"context"
"encoding/json"
"errors"
"fmt"
"net"
"path"
"path/filepath"
"strconv"
"strings"
"sync/atomic"

"github.com/Autumn-27/artex/sandbox"
actool "github.com/Autumn-27/norma/tool"
)

// SandboxRunner is the minimal execution interface the agent package needs from
// the runner client (*sandbox.Client in production, fakes in unit tests).
type SandboxRunner interface {
Exec(ctx context.Context, taskID string, req sandbox.ExecRequest) (sandbox.ExecResponse, error)
}

// SandboxExecutor wires the panel's sandbox mode and runner client into agent tools.
type SandboxExecutor struct {
Mode string
Runner SandboxRunner
OnUnavailable func(taskID string, err error)
}

var activeSandboxExecutor atomic.Pointer[SandboxExecutor]

// SetSandboxExecutor installs (or clears when nil) the process-wide sandbox executor.
func SetSandboxExecutor(ex *SandboxExecutor) {
activeSandboxExecutor.Store(ex)
}

// CurrentSandboxExecutor returns the installed sandbox executor, if any.
func CurrentSandboxExecutor() *SandboxExecutor {
return activeSandboxExecutor.Load()
}

// SandboxRequired reports whether the process-wide sandbox executor is in required mode.
func SandboxRequired() bool {
ex := activeSandboxExecutor.Load()
return ex != nil && ex.Mode == sandbox.ModeRequired
}

// SandboxRunInfo carries per-task sandbox metadata on context.Context.
type SandboxRunInfo struct {
TaskID string
TaskDir string // panel host path for /app/data/tasks/<id>
ScopeDomains []string
ScopeCIDRs []string
}

type sandboxCtxKey struct{}

// WithSandboxRunInfo attaches per-task sandbox metadata to ctx.
func WithSandboxRunInfo(ctx context.Context, info SandboxRunInfo) context.Context {
return context.WithValue(ctx, sandboxCtxKey{}, info)
}

// SandboxRunInfoFromContext retrieves per-task sandbox metadata from ctx.
func SandboxRunInfoFromContext(ctx context.Context) (SandboxRunInfo, bool) {
if ctx == nil {
return SandboxRunInfo{}, false
}
v, ok := ctx.Value(sandboxCtxKey{}).(SandboxRunInfo)
return v, ok && v.TaskID != ""
}

// containerWorkdir maps a panel WorkingDir under TaskDir onto /workspace inside the worker.
func containerWorkdir(taskDir, workingDir string) string {
if strings.TrimSpace(workingDir) == "" || strings.TrimSpace(taskDir) == "" {
return "/workspace"
}
rel, err := filepath.Rel(filepath.Clean(taskDir), filepath.Clean(workingDir))
if err != nil || rel == "." || strings.HasPrefix(rel, "..") || filepath.IsAbs(rel) {
return "/workspace"
}
return path.Clean("/workspace/" + filepath.ToSlash(rel))
}

// ExecInSandbox runs argv inside the task's worker container via the configured runner.
// In ARTEX_SANDBOX=required mode it fails closed (no local fallback) and notifies
// OnUnavailable when the runner cannot be reached so the engine pauses the task.
func ExecInSandbox(ctx context.Context, argv []string, workingDir string, timeoutMS int, env []string) (sandbox.ExecResponse, error) {
ex := activeSandboxExecutor.Load()
if ex == nil || ex.Mode != sandbox.ModeRequired {
return sandbox.ExecResponse{}, errors.New("sandbox executor not in required mode")
}
info, ok := SandboxRunInfoFromContext(ctx)
if !ok || info.TaskID == "" {
return sandbox.ExecResponse{}, fmt.Errorf("%w: missing task sandbox context (no local fallback)", sandbox.ErrRunnerUnavailable)
}
if ex.Runner == nil {
err := fmt.Errorf("%w: runner client is not configured", sandbox.ErrRunnerUnavailable)
if ex.OnUnavailable != nil {
ex.OnUnavailable(info.TaskID, err)
}
return sandbox.ExecResponse{}, err
}
req := sandbox.ExecRequest{
Argv: argv,
Workdir: containerWorkdir(info.TaskDir, workingDir),
TimeoutMS: timeoutMS,
Env: sandbox.FilterPanelEnv(env),
ScopeDomains: info.ScopeDomains,
ScopeCIDRs: info.ScopeCIDRs,
}
resp, err := ex.Runner.Exec(ctx, info.TaskID, req)
if err != nil && sandbox.IsUnavailable(err) && ex.OnUnavailable != nil {
ex.OnUnavailable(info.TaskID, err)
}
return resp, err
}

// sandboxBashTool wraps the SDK Bash tool so all Bash invocations route through
// artex-runner when ARTEX_SANDBOX=required (CONTRACT.md §§3, 6).
type sandboxBashTool struct {
actool.CoreTool
}

func (t *sandboxBashTool) Call(ctx context.Context, input json.RawMessage, tc *actool.ToolContext) (actool.Result, error) {
if !SandboxRequired() {
return t.CoreTool.Call(ctx, input, tc)
}
var in struct {
Command string `json:"command"`
TimeoutMS int `json:"timeout_ms"`
}
if err := json.Unmarshal(input, &in); err != nil {
return actool.Errorf(fmt.Sprintf("Error: invalid Bash arguments: %v", err)), nil
}
if strings.TrimSpace(in.Command) == "" {
return actool.Errorf("Error: command is required"), nil
}
workDir := ""
var env []string
if tc != nil {
workDir = tc.WorkingDir
env = tc.Env
}
resp, err := ExecInSandbox(ctx, []string{"bash", "-c", in.Command}, workDir, in.TimeoutMS, env)
if err != nil {
return actool.Errorf(fmt.Sprintf("Error: sandbox execution failed (ARTEX_SANDBOX=required, no local fallback): %v", err)), nil
}
return formatSandboxExecResult(resp, tc), nil
}

func formatSandboxExecResult(resp sandbox.ExecResponse, tc *actool.ToolContext) actool.Result {
var b strings.Builder
if resp.Stdout != "" {
b.WriteString(resp.Stdout)
}
if resp.Stderr != "" {
if b.Len() > 0 && !strings.HasSuffix(b.String(), "\n") {
b.WriteByte('\n')
}
b.WriteString(resp.Stderr)
}
if resp.Truncated {
b.WriteString("\n[output truncated at 1 MiB]")
}
out := b.String()
if tc != nil {
out = actool.Capture(tc, out)
}
if resp.TimedOut {
return actool.Errorf(fmt.Sprintf("%s\n\n[command timed out (exit code %d)]", out, resp.ExitCode))
}
if resp.ExitCode != 0 {
if strings.TrimSpace(out) == "" {
out = "(no output)"
}
return actool.Errorf(fmt.Sprintf("%s\n\n[exit code %d]", out, resp.ExitCode))
}
if strings.TrimSpace(out) == "" {
out = "(command produced no output)"
}
return actool.Text(out)
}

// sandboxScopeDialContext wraps baseDial so every TCP connection made by panel
// WebFetch in ARTEX_SANDBOX=required mode validates and pins the target IP via
// the task's sandbox.EgressPolicy (blocking non-scope IPs, IMDS, loopback,
// RFC1918, and IPv6 across all hops and redirects).
func sandboxScopeDialContext(policy *sandbox.EgressPolicy, baseDial func(ctx context.Context, network, addr string) (net.Conn, error)) func(ctx context.Context, network, addr string) (net.Conn, error) {
return func(ctx context.Context, network, addr string) (net.Conn, error) {
host, portStr, err := net.SplitHostPort(addr)
if err != nil {
return nil, fmt.Errorf("sandbox WebFetch blocked invalid target %q: %w", addr, err)
}
port, err := strconv.Atoi(portStr)
if err != nil || port <= 0 || port > 65535 {
return nil, fmt.Errorf("sandbox WebFetch blocked invalid port %q", portStr)
}
pinnedIP, err := policy.ResolveAndCheck(ctx, host)
if err != nil {
return nil, fmt.Errorf("sandbox WebFetch blocked: %w", err)
}
pinnedAddr := net.JoinHostPort(pinnedIP.String(), strconv.Itoa(port))
if baseDial != nil {
return baseDial(ctx, network, pinnedAddr)
}
var d net.Dialer
return d.DialContext(ctx, network, pinnedAddr)
}
}

// sandboxScopeWebFetchTool gates WebFetch inputs against the task's
// sandbox.EgressPolicy before Norma issues any HTTP request.
type sandboxScopeWebFetchTool struct {
actool.CoreTool
policy *sandbox.EgressPolicy
}

func (t *sandboxScopeWebFetchTool) Call(ctx context.Context, input json.RawMessage, tc *actool.ToolContext) (actool.Result, error) {
if SandboxRequired() {
var in struct {
URL string `json:"url"`
}
if err := json.Unmarshal(input, &in); err != nil {
return actool.Errorf(fmt.Sprintf("Error: invalid WebFetch arguments: %v", err)), nil
}
if t.policy == nil {
return actool.Errorf("Error: sandbox WebFetch blocked: missing task egress policy"), nil
}
if err := t.policy.CheckURL(ctx, in.URL); err != nil {
return actool.Errorf(fmt.Sprintf("Error: sandbox WebFetch blocked: %v", err)), nil
}
}
return t.CoreTool.Call(ctx, input, tc)
}
Loading
Loading