Files
ARTEX/sandbox/docker_scope_test.go
Henglie 9751c14870 fix(sandbox): refresh task egress scope mid-run on operator approval
Engine.withTaskSandbox and agent.withWebFetch captured a static
SandboxRunInfo and EgressPolicy snapshot once at the start of each
intent or planning round. When an operator approved a task_scope entry
(such as an agent-added root_domain) while an intent or planning round
was already running, ExecInSandbox kept sending the initial empty
allowlist to artex-runner so artex-egress-proxy was never recreated,
and WebFetch, sharedBrowserTool, custom HTTP tools, and enrich
remained stuck on the stale policy.

Attach a live scope resolver in withTaskSandbox and retestSandboxContext
and resolve SandboxRunInfo on each ExecInSandbox, SandboxEgressPolicy,
WebFetch, and sharedBrowserTool invocation so approvals and revocations
take effect immediately without restarting the task.
2026-12-05 00:08:11 +08:00

144 lines
4.7 KiB
Go

package sandbox
import (
"context"
"encoding/json"
"fmt"
"net"
"net/http"
"net/http/httptest"
"net/netip"
"strings"
"sync"
"testing"
)
func TestDockerBackendRecreatesProxyWhenScopeApproved(t *testing.T) {
ctx := context.Background()
root := t.TempDir()
b := NewDockerBackend(DockerConfig{WorkspaceRoot: root, AuditRoot: root})
labels := map[string]string{LabelManagedBy: ManagedByRunner, LabelTask: "6"}
var mu sync.Mutex
var proxyEnvs [][]string
var proxyDeletes int
var workerCreates int
proxySeq := 0
fake := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.Method + " " + r.URL.Path {
case "GET /networks/artex-task-6":
_ = json.NewEncoder(w).Encode(map[string]any{"Internal": true, "Labels": labels})
case "GET /networks/egress-net":
_, _ = w.Write([]byte("{}"))
case "DELETE /containers/artex-egress-6":
mu.Lock()
proxyDeletes++
mu.Unlock()
w.WriteHeader(http.StatusNoContent)
case "DELETE /containers/artex-worker-6":
w.WriteHeader(http.StatusNotFound)
case "POST /networks/egress-net/connect":
w.WriteHeader(http.StatusNoContent)
case "POST /containers/create":
name := r.URL.Query().Get("name")
switch name {
case "artex-egress-6":
var spec struct {
Env []string `json:"Env"`
}
_ = json.NewDecoder(r.Body).Decode(&spec)
mu.Lock()
proxySeq++
id := fmt.Sprintf("proxy-%d", proxySeq)
proxyEnvs = append(proxyEnvs, spec.Env)
mu.Unlock()
_ = json.NewEncoder(w).Encode(map[string]string{"Id": id})
case "artex-worker-6":
mu.Lock()
workerCreates++
mu.Unlock()
_ = json.NewEncoder(w).Encode(map[string]string{"Id": "worker-1"})
default:
http.NotFound(w, r)
}
case "POST /containers/proxy-1/start", "POST /containers/proxy-2/start", "POST /containers/proxy-3/start", "POST /containers/worker-1/start":
w.WriteHeader(http.StatusNoContent)
case "POST /containers/worker-1/exec":
_ = json.NewEncoder(w).Encode(map[string]string{"Id": "exec-1"})
case "POST /exec/exec-1/start":
w.WriteHeader(http.StatusOK)
case "GET /exec/exec-1/json":
_, _ = w.Write([]byte(`{"ExitCode":0,"Running":false}`))
default:
http.NotFound(w, r)
}
}))
t.Cleanup(fake.Close)
transport := b.http.Transport.(*http.Transport)
transport.DialContext = func(ctx context.Context, _, _ string) (net.Conn, error) {
var d net.Dialer
return d.DialContext(ctx, "tcp", fake.Listener.Addr().String())
}
t.Cleanup(transport.CloseIdleConnections)
envVal := func(env []string, key string) string {
prefix := key + "="
for _, kv := range env {
if v, ok := strings.CutPrefix(kv, prefix); ok {
return v
}
}
return ""
}
// 1. Initial exec before approval: proxy starts with empty ARTEX_SCOPE_DOMAINS.
if _, err := b.Exec(ctx, "6", ExecRequest{Argv: []string{"true"}, TimeoutMS: 1000}); err != nil {
t.Fatalf("Exec #1: %v", err)
}
// 2. Scope approved (root_domain xxx.com): proxy is deleted and recreated with ARTEX_SCOPE_DOMAINS=xxx.com.
if _, err := b.Exec(ctx, "6", ExecRequest{Argv: []string{"true"}, TimeoutMS: 1000, ScopeDomains: []string{"xxx.com"}}); err != nil {
t.Fatalf("Exec #2: %v", err)
}
// 3. Scope revoked: proxy is deleted and recreated with empty ARTEX_SCOPE_DOMAINS.
if _, err := b.Exec(ctx, "6", ExecRequest{Argv: []string{"true"}, TimeoutMS: 1000}); err != nil {
t.Fatalf("Exec #3: %v", err)
}
mu.Lock()
defer mu.Unlock()
if workerCreates != 1 {
t.Fatalf("workerCreates = %d, want 1 (proxy should update without recreating worker)", workerCreates)
}
if proxyDeletes != 3 || len(proxyEnvs) != 3 {
t.Fatalf("proxyDeletes=%d len(proxyEnvs)=%d, want 3/3", proxyDeletes, len(proxyEnvs))
}
if got := envVal(proxyEnvs[0], "ARTEX_SCOPE_DOMAINS"); got != "" {
t.Fatalf("initial ARTEX_SCOPE_DOMAINS = %q, want empty", got)
}
approvedDomains := envVal(proxyEnvs[1], "ARTEX_SCOPE_DOMAINS")
if approvedDomains != "xxx.com" {
t.Fatalf("approved ARTEX_SCOPE_DOMAINS = %q, want xxx.com", approvedDomains)
}
if got := envVal(proxyEnvs[2], "ARTEX_SCOPE_DOMAINS"); got != "" {
t.Fatalf("revoked ARTEX_SCOPE_DOMAINS = %q, want empty", got)
}
// Verify artex-egress-proxy's policy builder accepts xxx.com from that env var and denies other domains.
pol, err := NewEgressPolicy("6", ParseCSV(approvedDomains), nil, nil)
if err != nil {
t.Fatalf("NewEgressPolicy: %v", err)
}
pol.Resolver = func(context.Context, string) ([]netip.Addr, error) {
return []netip.Addr{netip.MustParseAddr("203.0.113.10")}, nil
}
if _, err := pol.ResolveAndCheck(ctx, "xxx.com"); err != nil {
t.Fatalf("recreated proxy policy should allow xxx.com: %v", err)
}
if _, err := pol.ResolveAndCheck(ctx, "evil.invalid"); err == nil {
t.Fatalf("recreated proxy policy unexpectedly allowed evil.invalid")
}
}