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.
166 lines
4.8 KiB
Go
166 lines
4.8 KiB
Go
package sandbox
|
|
|
|
import (
|
|
"context"
|
|
"crypto/subtle"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"log"
|
|
"net/http"
|
|
"strings"
|
|
)
|
|
|
|
// Backend is the container lifecycle backend used by RunnerServer (DockerBackend in production,
|
|
// fake backend in unit tests).
|
|
type Backend interface {
|
|
Ping(ctx context.Context) error
|
|
Recover(ctx context.Context) (int, error)
|
|
WorkerCount() int
|
|
Exec(ctx context.Context, taskID string, req ExecRequest) (ExecResponse, error)
|
|
Kill(ctx context.Context, taskID string) error
|
|
Delete(ctx context.Context, taskID string) error
|
|
}
|
|
|
|
// RunnerServer implements the pinned HTTP API from CONTRACT.md §3.
|
|
type RunnerServer struct {
|
|
token string
|
|
version string
|
|
backend Backend
|
|
mux *http.ServeMux
|
|
}
|
|
|
|
// NewRunnerServer builds an authenticated RunnerServer. Empty token is refused.
|
|
func NewRunnerServer(token, version string, backend Backend) (*RunnerServer, error) {
|
|
token = strings.TrimSpace(token)
|
|
if token == "" {
|
|
return nil, errors.New("ARTEX_RUNNER_TOKEN is required")
|
|
}
|
|
if version == "" {
|
|
version = "dev"
|
|
}
|
|
rs := &RunnerServer{
|
|
token: token,
|
|
version: version,
|
|
backend: backend,
|
|
mux: http.NewServeMux(),
|
|
}
|
|
rs.mux.HandleFunc("GET /v1/health", rs.withAuth(rs.handleHealth))
|
|
rs.mux.HandleFunc("POST /v1/tasks/{id}/exec", rs.withAuth(rs.handleExec))
|
|
rs.mux.HandleFunc("POST /v1/tasks/{id}/kill", rs.withAuth(rs.handleKill))
|
|
rs.mux.HandleFunc("DELETE /v1/tasks/{id}", rs.withAuth(rs.handleDelete))
|
|
return rs, nil
|
|
}
|
|
|
|
// Handler returns the HTTP handler for artex-runner.
|
|
func (rs *RunnerServer) Handler() http.Handler { return rs.mux }
|
|
|
|
func (rs *RunnerServer) withAuth(next http.HandlerFunc) http.HandlerFunc {
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
auth := r.Header.Get("Authorization")
|
|
if !strings.HasPrefix(auth, "Bearer ") {
|
|
writeRunnerErr(w, http.StatusUnauthorized, "missing bearer token")
|
|
return
|
|
}
|
|
got := strings.TrimPrefix(auth, "Bearer ")
|
|
if subtle.ConstantTimeCompare([]byte(got), []byte(rs.token)) != 1 {
|
|
writeRunnerErr(w, http.StatusUnauthorized, "invalid bearer token")
|
|
return
|
|
}
|
|
next(w, r)
|
|
}
|
|
}
|
|
|
|
func (rs *RunnerServer) handleHealth(w http.ResponseWriter, r *http.Request) {
|
|
dockerOK := rs.backend != nil && rs.backend.Ping(r.Context()) == nil
|
|
workers := 0
|
|
if rs.backend != nil {
|
|
workers = rs.backend.WorkerCount()
|
|
}
|
|
resp := HealthResponse{
|
|
OK: dockerOK,
|
|
Docker: dockerOK,
|
|
Workers: workers,
|
|
Version: rs.version,
|
|
}
|
|
if !dockerOK {
|
|
writeRunnerJSON(w, http.StatusConflict, resp)
|
|
return
|
|
}
|
|
writeRunnerJSON(w, http.StatusOK, resp)
|
|
}
|
|
|
|
func (rs *RunnerServer) handleExec(w http.ResponseWriter, r *http.Request) {
|
|
taskID := r.PathValue("id")
|
|
if err := ValidateTaskID(taskID); err != nil {
|
|
writeRunnerErr(w, http.StatusBadRequest, err.Error())
|
|
return
|
|
}
|
|
var req ExecRequest
|
|
dec := json.NewDecoder(io.LimitReader(r.Body, 1<<20))
|
|
if err := dec.Decode(&req); err != nil {
|
|
writeRunnerErr(w, http.StatusBadRequest, "invalid json: "+err.Error())
|
|
return
|
|
}
|
|
if err := ValidateExecRequest(&req); err != nil {
|
|
writeRunnerErr(w, http.StatusBadRequest, err.Error())
|
|
return
|
|
}
|
|
res, err := rs.backend.Exec(r.Context(), taskID, req)
|
|
if err != nil {
|
|
rs.writeBackendErr(w, err)
|
|
return
|
|
}
|
|
writeRunnerJSON(w, http.StatusOK, res)
|
|
}
|
|
|
|
func (rs *RunnerServer) handleKill(w http.ResponseWriter, r *http.Request) {
|
|
taskID := r.PathValue("id")
|
|
if err := ValidateTaskID(taskID); err != nil {
|
|
writeRunnerErr(w, http.StatusBadRequest, err.Error())
|
|
return
|
|
}
|
|
if err := rs.backend.Kill(r.Context(), taskID); err != nil {
|
|
rs.writeBackendErr(w, err)
|
|
return
|
|
}
|
|
writeRunnerJSON(w, http.StatusOK, KillResponse{Killed: true})
|
|
}
|
|
|
|
func (rs *RunnerServer) handleDelete(w http.ResponseWriter, r *http.Request) {
|
|
taskID := r.PathValue("id")
|
|
if err := ValidateTaskID(taskID); err != nil {
|
|
writeRunnerErr(w, http.StatusBadRequest, err.Error())
|
|
return
|
|
}
|
|
if err := rs.backend.Delete(r.Context(), taskID); err != nil {
|
|
rs.writeBackendErr(w, err)
|
|
return
|
|
}
|
|
writeRunnerJSON(w, http.StatusOK, DeleteResponse{Deleted: true})
|
|
}
|
|
|
|
func (rs *RunnerServer) writeBackendErr(w http.ResponseWriter, err error) {
|
|
switch {
|
|
case errors.Is(err, ErrBadRequest):
|
|
writeRunnerErr(w, http.StatusBadRequest, err.Error())
|
|
case errors.Is(err, ErrNotFound):
|
|
writeRunnerErr(w, http.StatusNotFound, err.Error())
|
|
case errors.Is(err, ErrDockerUnavailable):
|
|
writeRunnerErr(w, http.StatusConflict, err.Error())
|
|
default:
|
|
log.Printf("[runner] backend error: %v", err)
|
|
writeRunnerErr(w, http.StatusInternalServerError, fmt.Sprintf("runner error: %v", err))
|
|
}
|
|
}
|
|
|
|
func writeRunnerJSON(w http.ResponseWriter, code int, v any) {
|
|
w.Header().Set("Content-Type", "application/json")
|
|
w.WriteHeader(code)
|
|
_ = json.NewEncoder(w).Encode(v)
|
|
}
|
|
|
|
func writeRunnerErr(w http.ResponseWriter, code int, msg string) {
|
|
writeRunnerJSON(w, code, map[string]string{"error": msg})
|
|
}
|