mirror of
https://github.com/BaaRai/ARTEX.git
synced 2026-12-03 13:11:05 +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.
253 lines
9.1 KiB
Go
253 lines
9.1 KiB
Go
package server
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"fmt"
|
|
"strings"
|
|
|
|
"github.com/Autumn-27/artex/agent"
|
|
"github.com/Autumn-27/artex/db"
|
|
"github.com/Autumn-27/artex/sandbox"
|
|
actool "github.com/Autumn-27/norma/tool"
|
|
"github.com/google/uuid"
|
|
)
|
|
|
|
// sharedBrowserToolNote is appended to the description of every browser MCP tool
|
|
// while the shared browser is on, so the model knows the operator can see and
|
|
// take over the page, and what to do at a CAPTCHA.
|
|
const sharedBrowserToolNote = "\nThis browser is shared with the human operator, who watches it live and can take over. " +
|
|
"At a CAPTCHA, a \"verify you are human\" page, an email/SMS code or a 2FA prompt: do not try to solve or bypass it; " +
|
|
"call ask_operator (attach a screenshot) and the operator completes it in this same browser, then continue after their reply."
|
|
|
|
// isSharedBrowserMCP reports whether an MCP row is the browser MCP the shared
|
|
// browser takes over: the seeded "browser" server running Playwright MCP.
|
|
func isSharedBrowserMCP(m *db.MCPServer) bool {
|
|
if m == nil || m.Name != browserMCPName || m.Transport != "stdio" {
|
|
return false
|
|
}
|
|
line := m.Command + " " + strings.Join(jsonStrSlice(m.Args), " ")
|
|
return strings.Contains(line, "playwright-mcp") || strings.Contains(line, "@playwright/mcp")
|
|
}
|
|
|
|
// browserMCPProxy reads the proxy that syncBrowserMCPProxy put on the row, and
|
|
// the recording proxy CA PEM path (NODE_EXTRA_CA_CERTS) when capture is on.
|
|
// Chromium trusts only that CA's SPKI pin (--ignore-certificate-errors-spki-list)
|
|
// rather than disabling certificate verification globally.
|
|
func browserMCPProxy(args []string, env map[string]string) (proxy string, caCertPath string) {
|
|
for i := 0; i < len(args); i++ {
|
|
a := args[i]
|
|
if a == "--proxy-server" && i+1 < len(args) {
|
|
proxy = args[i+1]
|
|
i++
|
|
} else if v, ok := strings.CutPrefix(a, "--proxy-server="); ok {
|
|
proxy = v
|
|
}
|
|
}
|
|
if proxy != "" && env != nil {
|
|
caCertPath = strings.TrimSpace(env["NODE_EXTRA_CA_CERTS"])
|
|
}
|
|
return proxy, caCertPath
|
|
}
|
|
|
|
// sharedBrowserMCPArgs rewrites the browser MCP's arguments to drive the shared
|
|
// browser: launch options that no longer apply (headless, isolated profile, proxy,
|
|
// a browser binary or profile of its own) are dropped, and --cdp-endpoint is set
|
|
// to ARTEX's per-run authenticated CDP proxy endpoint.
|
|
func sharedBrowserMCPArgs(args []string, endpoint string) []string {
|
|
withValue := map[string]bool{
|
|
"--proxy-server": true, "--proxy-bypass": true, "--user-data-dir": true, "--cdp-endpoint": true,
|
|
"--executable-path": true, "--storage-state": true, "--device": true, "--user-agent": true,
|
|
}
|
|
flags := map[string]bool{"--headless": true, "--isolated": true, "--headed": true}
|
|
out := make([]string, 0, len(args)+2)
|
|
for i := 0; i < len(args); i++ {
|
|
a := args[i]
|
|
name, _, hasEq := strings.Cut(a, "=")
|
|
if flags[name] {
|
|
continue
|
|
}
|
|
if withValue[name] {
|
|
if !hasEq {
|
|
i++ // its value is the next argument
|
|
}
|
|
continue
|
|
}
|
|
out = append(out, a)
|
|
}
|
|
return append(out, "--cdp-endpoint", endpoint)
|
|
}
|
|
|
|
// browserRunHolder names the agent run for the browser lease: the worker intent
|
|
// when there is one (the key ask_operator uses too), else the task and agent, the
|
|
// chat session, or a per-run id.
|
|
func browserRunHolder(ri agent.RunInfo, agentKey string) (key, label string) {
|
|
switch {
|
|
case ri.TaskID != 0 && ri.IntentID != 0:
|
|
return fmt.Sprintf("t%d/i%d", ri.TaskID, ri.IntentID), fmt.Sprintf("task %d · intent %d (%s)", ri.TaskID, ri.IntentID, agentKey)
|
|
case ri.TaskID != 0:
|
|
return fmt.Sprintf("t%d/%s", ri.TaskID, agentKey), fmt.Sprintf("task %d (%s)", ri.TaskID, agentKey)
|
|
case ri.SessionID != "":
|
|
return "chat/" + ri.SessionID, fmt.Sprintf("chat (%s)", agentKey)
|
|
}
|
|
return "run/" + uuid.NewString(), agentKey
|
|
}
|
|
|
|
// browserProfileScope returns the isolated profile directory name for a run:
|
|
// per task ("task-<id>"), per chat session ("session-<sanitized>"), or a fresh
|
|
// ephemeral scope when neither is present. Different tasks and sessions never
|
|
// share cookies, storage, or history.
|
|
func browserProfileScope(ri agent.RunInfo) string {
|
|
switch {
|
|
case ri.TaskID != 0:
|
|
return fmt.Sprintf("task-%d", ri.TaskID)
|
|
case strings.TrimSpace(ri.SessionID) != "":
|
|
return "session-" + sanitizeProfileScope(ri.SessionID)
|
|
}
|
|
return "run-" + sanitizeProfileScope(uuid.NewString())
|
|
}
|
|
|
|
// sanitizeProfileScope restricts a profile scope segment to [A-Za-z0-9_-]
|
|
// (max 64 bytes) so untrusted session IDs can never traverse out of ProfileDir.
|
|
func sanitizeProfileScope(in string) string {
|
|
var b strings.Builder
|
|
for i := 0; i < len(in) && b.Len() < 64; i++ {
|
|
c := in[i]
|
|
if (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '-' || c == '_' {
|
|
b.WriteByte(c)
|
|
} else {
|
|
b.WriteByte('_')
|
|
}
|
|
}
|
|
out := strings.Trim(b.String(), "_-")
|
|
if out == "" {
|
|
return "default"
|
|
}
|
|
return out
|
|
}
|
|
|
|
// sharedBrowserTool wraps one browser MCP tool with the shared-browser gate:
|
|
// operator control, the one-run-at-a-time lease, and the CAPTCHA handoff.
|
|
type sharedBrowserTool struct {
|
|
actool.CoreTool
|
|
b *sharedBrowser
|
|
holder string
|
|
label string
|
|
}
|
|
|
|
func (t *sharedBrowserTool) Call(ctx context.Context, in json.RawMessage, tc *actool.ToolContext) (actool.Result, error) {
|
|
if agent.SandboxRequired() {
|
|
if err := sandboxCheckBrowserInput(ctx, t.Name(), in); err != nil {
|
|
return actool.Errorf(fmt.Sprintf("sandbox browser navigation blocked: %v", err)), nil
|
|
}
|
|
}
|
|
if t.b != nil {
|
|
if refusal := t.b.AgentGate(ctx, t.holder, t.label, t.Name()); refusal != "" {
|
|
return actool.Errorf(refusal), nil
|
|
}
|
|
}
|
|
return t.CoreTool.Call(ctx, in, tc)
|
|
}
|
|
|
|
// sandboxCheckBrowserInput extracts every URL argument from a browser MCP tool
|
|
// invocation and enforces the task's sandbox.EgressPolicy (deny by default;
|
|
// blocks non-scope IPs, IMDS, loopback, RFC1918, non-scope domains, and
|
|
// dangerous schemes like file:// or chrome://).
|
|
func sandboxCheckBrowserInput(ctx context.Context, toolName string, raw json.RawMessage) error {
|
|
info, _ := agent.SandboxRunInfoFromContext(ctx)
|
|
policy, err := sandbox.NewEgressPolicy(info.TaskID, info.ScopeDomains, info.ScopeCIDRs, nil)
|
|
if err != nil {
|
|
return fmt.Errorf("invalid task egress policy: %w", err)
|
|
}
|
|
urls := extractBrowserInputURLs(toolName, raw)
|
|
for _, u := range urls {
|
|
if err := policy.CheckURL(ctx, u); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func extractBrowserInputURLs(toolName string, raw json.RawMessage) []string {
|
|
var parsed any
|
|
if err := json.Unmarshal(raw, &parsed); err != nil {
|
|
return nil
|
|
}
|
|
var out []string
|
|
seen := map[string]bool{}
|
|
add := func(s string) {
|
|
s = strings.TrimSpace(s)
|
|
if s != "" && !seen[s] {
|
|
seen[s] = true
|
|
out = append(out, s)
|
|
}
|
|
}
|
|
navTool := strings.Contains(strings.ToLower(toolName), "navigat") ||
|
|
strings.Contains(strings.ToLower(toolName), "goto") ||
|
|
strings.Contains(strings.ToLower(toolName), "open")
|
|
var walk func(key string, v any)
|
|
walk = func(key string, v any) {
|
|
switch x := v.(type) {
|
|
case map[string]any:
|
|
for k, val := range x {
|
|
walk(strings.ToLower(k), val)
|
|
}
|
|
case []any:
|
|
for _, item := range x {
|
|
walk(key, item)
|
|
}
|
|
case string:
|
|
s := strings.TrimSpace(x)
|
|
if s == "" {
|
|
return
|
|
}
|
|
if key == "url" || key == "href" || key == "uri" || key == "target_url" || key == "target" {
|
|
add(s)
|
|
return
|
|
}
|
|
low := strings.ToLower(s)
|
|
if strings.HasPrefix(low, "http://") || strings.HasPrefix(low, "https://") ||
|
|
strings.HasPrefix(low, "ws://") || strings.HasPrefix(low, "wss://") ||
|
|
strings.HasPrefix(low, "file://") || strings.HasPrefix(low, "chrome://") ||
|
|
strings.HasPrefix(low, "javascript:") || (navTool && strings.Contains(s, "://")) {
|
|
add(s)
|
|
}
|
|
}
|
|
}
|
|
walk("", parsed)
|
|
return out
|
|
}
|
|
|
|
// AcceptsRawInput forwards the wrapped tool's opt-out of the harness schema check.
|
|
func (t *sharedBrowserTool) AcceptsRawInput() bool {
|
|
r, ok := t.CoreTool.(interface{ AcceptsRawInput() bool })
|
|
return ok && r.AcceptsRawInput()
|
|
}
|
|
|
|
// prepareSharedBrowserMCP starts (or reuses) the shared browser for the run's
|
|
// isolated task/session profile, issues a per-run authenticated CDP proxy token,
|
|
// and returns a copy of the MCP row pointed at that authenticated endpoint plus
|
|
// a revoke callback for cleanup. ok is false when the browser could not start.
|
|
func prepareSharedBrowserMCP(ctx context.Context, b *sharedBrowser, m *db.MCPServer, ri agent.RunInfo, holder string) (*db.MCPServer, bool, func()) {
|
|
args := jsonStrSlice(m.Args)
|
|
proxy, caCertPath := browserMCPProxy(args, jsonStrMap(m.Env))
|
|
scope := browserProfileScope(ri)
|
|
if err := b.Ensure(ctx, scope, proxy, caCertPath, holder); err != nil {
|
|
logSharedBrowserFallback(err)
|
|
return m, false, nil
|
|
}
|
|
endpoint, revoke, err := b.IssueMCPEndpoint(holder)
|
|
if err != nil {
|
|
logSharedBrowserFallback(err)
|
|
return m, false, nil
|
|
}
|
|
cp := *m
|
|
cp.Args = encodeJSON(sharedBrowserMCPArgs(args, endpoint))
|
|
return &cp, true, revoke
|
|
}
|
|
|
|
// logSharedBrowserFallback logs a failed shared-browser start once per distinct
|
|
// error, so a missing Chromium does not repeat on every agent run.
|
|
func logSharedBrowserFallback(err error) {
|
|
logExecOnce("[browser] shared browser unavailable, agents fall back to a private headless browser: %v", err)
|
|
}
|