ARTEX/db/retarget.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

169 lines
5.2 KiB
Go

package db
import (
"context"
"encoding/json"
"fmt"
"net/url"
"regexp"
"strings"
)
// RetargetResult summarizes the rows updated when retargeting a task to a new
// instance base URL.
type RetargetResult struct {
TaskID int64 `json:"task_id"`
OldHost string `json:"old_host"`
NewHost string `json:"new_host"`
NewBaseURL string `json:"new_base_url"`
GoalsUpdated int `json:"goals_updated"`
ConstraintsUpdated int `json:"constraints_updated"`
ScopesUpdated int `json:"scopes_updated"`
UpdatedGoal string `json:"updated_goal"`
}
func replaceHostCaseInsensitive(text, oldHost, newHost string) (string, bool) {
if oldHost == "" || newHost == "" || strings.EqualFold(oldHost, newHost) {
return text, false
}
re := regexp.MustCompile(`(?i)` + regexp.QuoteMeta(oldHost))
if !re.MatchString(text) {
return text, false
}
return re.ReplaceAllString(text, newHost), true
}
// RetargetTask updates tasks.goal, explorations.goal, open goal node payloads,
// task_constraints, and task_scope from oldHost to newBaseURL in a single
// transaction (no schema migration).
func (d *DB) RetargetTask(ctx context.Context, taskID int64, oldHost, newBaseURL string) (*RetargetResult, error) {
u, err := url.Parse(strings.TrimSpace(newBaseURL))
if err != nil || u.Hostname() == "" {
return nil, fmt.Errorf("invalid new base URL %q", newBaseURL)
}
oldH := strings.ToLower(strings.TrimSuffix(strings.TrimSpace(oldHost), "."))
newH := strings.ToLower(strings.TrimSuffix(strings.TrimSpace(u.Hostname()), "."))
if oldH == "" {
return nil, fmt.Errorf("old_host is required")
}
tx, err := d.BeginTx(ctx, nil)
if err != nil {
return nil, err
}
defer tx.Rollback()
var expID int64
var curGoal string
if err := tx.QueryRowContext(ctx, `SELECT exploration_id, goal FROM tasks WHERE id=$1 AND deleted_at IS NULL FOR UPDATE`, taskID).Scan(&expID, &curGoal); err != nil {
return nil, err
}
newGoal, replaced := replaceHostCaseInsensitive(curGoal, oldH, newH)
if !replaced && !strings.Contains(strings.ToLower(curGoal), newH) {
newGoal = strings.TrimSpace(curGoal) + " [Target: " + strings.TrimSpace(newBaseURL) + "]"
}
if _, err := tx.ExecContext(ctx, `UPDATE tasks SET goal=$1 WHERE id=$2`, newGoal, taskID); err != nil {
return nil, err
}
if _, err := tx.ExecContext(ctx, `UPDATE explorations SET goal=$1 WHERE id=$2`, newGoal, expID); err != nil {
return nil, err
}
res := &RetargetResult{
TaskID: taskID,
OldHost: oldH,
NewHost: newH,
NewBaseURL: strings.TrimSpace(newBaseURL),
UpdatedGoal: newGoal,
}
// Update open goal nodes.
rows, err := tx.QueryContext(ctx, `SELECT id, payload FROM exploration_nodes WHERE exploration_id=$1 AND kind=$2 AND state='open'`, expID, KindGoal)
if err != nil {
return nil, err
}
type goalUpd struct {
id int64
payload string
}
var goalUpds []goalUpd
for rows.Next() {
var id int64
var raw []byte
if err := rows.Scan(&id, &raw); err != nil {
rows.Close()
return nil, err
}
var p map[string]any
if json.Unmarshal(raw, &p) == nil {
if txt, _ := p["text"].(string); txt != "" {
if updated, ok := replaceHostCaseInsensitive(txt, oldH, newH); ok {
p["text"] = updated
b, _ := json.Marshal(p)
goalUpds = append(goalUpds, goalUpd{id: id, payload: string(b)})
}
}
}
}
rows.Close()
for _, gu := range goalUpds {
if _, err := tx.ExecContext(ctx, `UPDATE exploration_nodes SET payload=$1 WHERE id=$2`, gu.payload, gu.id); err != nil {
return nil, err
}
res.GoalsUpdated++
}
// Update task_constraints referencing oldH.
cRows, err := tx.QueryContext(ctx, `SELECT id, text FROM task_constraints WHERE exploration_id=$1`, expID)
if err != nil {
return nil, err
}
type cUpd struct {
id int64
text string
}
var cUpds []cUpd
for cRows.Next() {
var id int64
var txt string
if err := cRows.Scan(&id, &txt); err != nil {
cRows.Close()
return nil, err
}
if updated, ok := replaceHostCaseInsensitive(txt, oldH, newH); ok {
cUpds = append(cUpds, cUpd{id: id, text: updated})
}
}
cRows.Close()
for _, cu := range cUpds {
if _, err := tx.ExecContext(ctx, `UPDATE task_constraints SET text=$1 WHERE id=$2`, cu.text, cu.id); err != nil {
return nil, err
}
res.ConstraintsUpdated++
}
// Replace task_scope entries matching oldH with newH. A host scope row keeps
// its host in the domain column (value is only for icp/keyword rows), and the
// coverage queries match on domain.
delRes, err := tx.ExecContext(ctx, `DELETE FROM task_scope WHERE task_id=$1 AND kind IN ('root_domain','subdomain') AND LOWER(domain)=$2`, taskID, oldH)
if err != nil {
return nil, err
}
if n, _ := delRes.RowsAffected(); n > 0 {
res.ScopesUpdated += int(n)
}
if _, err := tx.ExecContext(ctx, `
INSERT INTO task_scope(task_id, kind, domain, source, reason, expanded, approved_by_operator)
VALUES ($1, 'subdomain', $2, 'manual', 'retargeted to new instance', FALSE, TRUE)
ON CONFLICT (task_id, kind, COALESCE(domain,''), COALESCE(net::text,''), COALESCE(company_id,0), COALESCE(value,''))
DO UPDATE SET approved_by_operator = TRUE, source = 'manual', expanded = FALSE`, taskID, newH); err != nil {
return nil, err
}
res.ScopesUpdated++
if err := tx.Commit(); err != nil {
return nil, err
}
return res, nil
}