ARTEX/sandbox/client.go
BaaRai 643e814ad6 security: isolate task execution in per-task sandbox worker and egress proxy
Introduce the sandbox MVP architecture separating panel credentials and
PostgreSQL access from model-controlled tool execution:

- Runner service (cmd/artex-runner, sandbox/) owning /var/run/docker.sock
  behind bearer-token auth (ARTEX_RUNNER_TOKEN) with POST /v1/tasks/{id}/exec,
  POST /v1/tasks/{id}/kill, DELETE /v1/tasks/{id}, and GET /v1/health.
- Strict input and env validation (400 on forbidden secret/DB/cloud env
  patterns or values > 8192 bytes, strict task ID and /workspace workdir).
- Hardened per-task worker containers (Dockerfile.worker, artex-worker:local,
  cmd/artex-exec-wrap): uid/gid 10001, artex-exec-wrap --init PID 1 zombie
  reaper, read-only rootfs, cap-drop ALL, no-new-privileges, pids/mem/cpu
  limits, tmpfs /tmp and /home/exec, only /app/data/tasks/<id>:/workspace:rw,
  only verified internal=true runner-labeled network artex-task-<id>.
- Kernel-backed kill-switch (zero agent-writable state): Kill executes
  artex-exec-wrap --kill-uid 10001 as uid 10001 scanning /proc directly
  (defeating setsid, nohup, nested double-forked trap-TERM daemons, 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. Dead
  workers/proxies are recreated automatically when startContainer fails.
- Operator-only scope approval (migration 0023_task_scope_operator_approval.sql):
  adds task_scope.approved_by_operator BOOLEAN NOT NULL DEFAULT FALSE, set
  true exclusively by operator API/UI (AddOperatorScope) and operator-selected
  TaskCreateOptions.CompanyIDs (insertTaskCompanies). AddAgentScope and
  AddAutoScope leave it false (coverage-only). taskSandboxRunInfo reads only
  approved, non-expanded rows (and expands company scope only for approved
  company rows); tasks with no approved scope deny all egress.
- Per-task egress proxy (cmd/artex-egress-proxy, Dockerfile.egress-proxy,
  artex-egress-proxy:local): HTTP/HTTPS CONNECT (:3128) and SOCKS5 (:1080),
  deny-by-default allowlist with strict domain suffix enforcement, blocks
  RFC1918/loopback/link-local/IMDS and IPv6 unless in scope CIDRs, DNS
  pinning, and tamper-proof JSONL audit logging to a proxy-only mount
  (/app/data/egress-audit/<id>:/audit:rw) never mounted into the worker.
- Panel integration (agent/sandbox.go, agent/webfetch.go, server/sandbox.go,
  server/sharedbrowser_guard.go, server/assembly.go, server/customtool.go,
  docker-compose.sandbox.yml): ARTEX_SANDBOX defaults to required (fail closed,
  no local fallback), WebFetch and opt-in shared browser inherit the
  operator-approved sandbox.EgressPolicy (with target_gate or explicit proxy
  required for shared browser), custom script tools staged via symlink-confined
  workspace files (avoiding argv E2BIG), Pause/Stop/Delete wired to runner
  Kill/Delete.
- Documented breaking change and hardening details in docs/SANDBOX.md,
  README.md, and CHANGELOG.md.
2026-11-30 19:09:32 +01:00

129 lines
3.7 KiB
Go

package sandbox
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"strings"
"time"
)
// Client is the panel-side HTTP client for artex-runner.
type Client struct {
baseURL string
token string
http *http.Client
}
// NewClient constructs a runner client. Ambient HTTP_PROXY is explicitly disabled
// (Proxy: nil) so panel->runner calls on runner-net are never proxied.
func NewClient(baseURL, token string) *Client {
tr := &http.Transport{
Proxy: nil,
MaxIdleConns: 16,
IdleConnTimeout: 60 * time.Second,
ResponseHeaderTimeout: 0, // exec calls can run up to MaxTimeoutMS
}
return &Client{
baseURL: strings.TrimRight(strings.TrimSpace(baseURL), "/"),
token: strings.TrimSpace(token),
http: &http.Client{Transport: tr},
}
}
func (c *Client) doJSON(ctx context.Context, method, path string, reqBody, out any) error {
if c == nil || c.baseURL == "" {
return fmt.Errorf("%w: runner URL is empty", ErrRunnerUnavailable)
}
var body io.Reader
if reqBody != nil {
raw, err := json.Marshal(reqBody)
if err != nil {
return err
}
body = bytes.NewReader(raw)
}
req, err := http.NewRequestWithContext(ctx, method, c.baseURL+path, body)
if err != nil {
return err
}
if reqBody != nil {
req.Header.Set("Content-Type", "application/json")
}
if c.token != "" {
req.Header.Set("Authorization", "Bearer "+c.token)
}
resp, err := c.http.Do(req)
if err != nil {
return fmt.Errorf("%w: %v", ErrRunnerUnavailable, err)
}
defer resp.Body.Close()
// Cap error/JSON reads to 4 MiB (ExecResponse carries <= 2 MiB of stdout+stderr + JSON overhead).
respRaw, err := io.ReadAll(io.LimitReader(resp.Body, 4<<20))
if err != nil {
return fmt.Errorf("%w: read response: %v", ErrRunnerUnavailable, err)
}
if resp.StatusCode >= 400 {
msg := strings.TrimSpace(string(respRaw))
switch resp.StatusCode {
case http.StatusBadRequest:
return fmt.Errorf("%w: %s", ErrBadRequest, msg)
case http.StatusUnauthorized:
return fmt.Errorf("%w: %s", ErrUnauthorized, msg)
case http.StatusNotFound:
return fmt.Errorf("%w: %s", ErrNotFound, msg)
case http.StatusConflict:
return fmt.Errorf("%w: %s", ErrDockerUnavailable, msg)
default:
return fmt.Errorf("%w: HTTP %d: %s", ErrRunnerUnavailable, resp.StatusCode, msg)
}
}
if out != nil && len(respRaw) > 0 {
if err := json.Unmarshal(respRaw, out); err != nil {
return fmt.Errorf("decode runner response: %w", err)
}
}
return nil
}
// Health calls GET /v1/health.
func (c *Client) Health(ctx context.Context) (HealthResponse, error) {
var out HealthResponse
err := c.doJSON(ctx, http.MethodGet, "/v1/health", nil, &out)
return out, err
}
// Exec calls POST /v1/tasks/{id}/exec.
func (c *Client) Exec(ctx context.Context, taskID string, req ExecRequest) (ExecResponse, error) {
if err := ValidateTaskID(taskID); err != nil {
return ExecResponse{}, err
}
var out ExecResponse
err := c.doJSON(ctx, http.MethodPost, "/v1/tasks/"+url.PathEscape(taskID)+"/exec", req, &out)
return out, err
}
// Kill calls POST /v1/tasks/{id}/kill.
func (c *Client) Kill(ctx context.Context, taskID string) (KillResponse, error) {
if err := ValidateTaskID(taskID); err != nil {
return KillResponse{}, err
}
var out KillResponse
err := c.doJSON(ctx, http.MethodPost, "/v1/tasks/"+url.PathEscape(taskID)+"/kill", nil, &out)
return out, err
}
// Delete calls DELETE /v1/tasks/{id}.
func (c *Client) Delete(ctx context.Context, taskID string) (DeleteResponse, error) {
if err := ValidateTaskID(taskID); err != nil {
return DeleteResponse{}, err
}
var out DeleteResponse
err := c.doJSON(ctx, http.MethodDelete, "/v1/tasks/"+url.PathEscape(taskID), nil, &out)
return out, err
}