mirror of
https://github.com/BaaRai/ARTEX.git
synced 2026-12-03 21:17:28 +00:00
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.
236 lines
8 KiB
Go
236 lines
8 KiB
Go
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)
|
|
}
|