Files
ARTEX-chixuweihu/internal/sandbox/path.go
T
ji ruo 9c43e694a3 feat(sandbox): isolate worker/chat execution in Docker containers with lifecycle UI
- Add Docker sandbox manager, non-root sandbox image, compose isolation, and host firewall script (#217)
- Route Bash, custom commands/scripts, stdio MCP, chat sessions, MainAgent chat, and task-scoped reporter screenshots into sandbox containers with per-task browser concurrency gate
- Enforce proxy SSRF guard against loopback, metadata, internal services, and admin port
- Add dedicated /system/sandbox management page, /chat session sandbox control, and task detail sandbox popover with progressive stats loading
2026-12-01 21:13:21 +08:00

225 lines
6.3 KiB
Go

package sandbox
import (
"errors"
"fmt"
"io"
"os"
"path/filepath"
"strings"
)
// ResolveConfined maps candidate (which may be relative to root, relative to
// defaultSubdir, or rooted at ContainerWorkDir "/workspace") to an absolute
// path inside root, verifying that neither lexical traversal ("..") nor any
// existing symlink component escapes root.
func ResolveConfined(root, defaultSubdir, candidate string) (string, bool) {
rootClean := filepath.Clean(root)
if rootClean == "" || rootClean == "." {
return "", false
}
rootReal, err := evalDeepest(rootClean)
if err != nil {
return "", false
}
raw := strings.TrimSpace(candidate)
var joined string
switch {
case raw == "" || raw == ".":
if defaultSubdir != "" {
joined = filepath.Join(rootClean, defaultSubdir)
} else {
joined = rootClean
}
case raw == ContainerWorkDir || strings.HasPrefix(raw, ContainerWorkDir+"/"):
rel := strings.TrimPrefix(raw, ContainerWorkDir)
rel = strings.TrimPrefix(rel, "/")
joined = filepath.Join(rootClean, filepath.FromSlash(rel))
case filepath.IsAbs(raw):
cleaned := filepath.Clean(raw)
if !isWithin(rootClean, cleaned) && !isWithin(rootReal, cleaned) {
return "", false
}
joined = cleaned
default:
if defaultSubdir != "" {
joined = filepath.Join(rootClean, defaultSubdir, filepath.FromSlash(raw))
} else {
joined = filepath.Join(rootClean, filepath.FromSlash(raw))
}
}
joined = filepath.Clean(joined)
if !isWithin(rootClean, joined) && !isWithin(rootReal, joined) {
return "", false
}
resolved, err := evalDeepest(joined)
if err != nil {
return "", false
}
if !isWithin(rootReal, resolved) {
return "", false
}
return resolved, true
}
// CheckPathWithinRoot verifies an already-resolved host path stays within root
// after resolving symlinks (blocking symlink escape attacks from sandbox containers).
func CheckPathWithinRoot(root, candidate string) (string, bool) {
rootClean := filepath.Clean(root)
rootReal, err := evalDeepest(rootClean)
if err != nil {
return "", false
}
resolved, err := evalDeepest(filepath.Clean(candidate))
if err != nil {
return "", false
}
if !isWithin(rootReal, resolved) {
return "", false
}
return resolved, true
}
// HostToContainerPath maps a host path under targetRoot to its container-visible
// "/workspace/..." path. Returns ContainerWorkDir if hostPath equals targetRoot.
func HostToContainerPath(targetRoot, hostPath string) string {
rootClean := filepath.Clean(targetRoot)
hostClean := filepath.Clean(hostPath)
rel, err := filepath.Rel(rootClean, hostClean)
if err != nil || rel == "." || strings.HasPrefix(rel, "..") {
return ContainerWorkDir
}
return ContainerWorkDir + "/" + filepath.ToSlash(rel)
}
// MapDataPathToHost translates a path inside artex's local DataDir to the
// corresponding host filesystem path for Docker bind mounts.
func (c Config) MapDataPathToHost(localPath string) string {
localClean := filepath.Clean(localPath)
dataClean := filepath.Clean(c.DataDir)
hostClean := filepath.Clean(c.HostDataDir)
if dataClean == hostClean {
return localClean
}
if localClean == dataClean {
return hostClean
}
rel, err := filepath.Rel(dataClean, localClean)
if err != nil || strings.HasPrefix(rel, "..") {
return localClean
}
return filepath.Join(hostClean, rel)
}
// LocalRootFor returns the local filesystem directory backing a Target inside DataDir.
func (c Config) LocalRootFor(t Target) string {
switch t.Scope {
case ScopeTask:
return filepath.Join(c.DataDir, "tasks", t.OwnerID)
case ScopeSession:
return filepath.Join(c.DataDir, "sessions", t.OwnerID)
case ScopeEphemeral:
return filepath.Join(c.DataDir, "ephemeral", sanitizeToken(t.OwnerID))
default:
return filepath.Join(c.DataDir, "ephemeral", sanitizeToken(t.OwnerID))
}
}
// CopyRegularFileSafe copies a regular file (refusing symlinks, sockets, FIFOs,
// and directories) from srcPath (confined to srcRoot) into dstDir under dstRoot,
// choosing a unique non-clobbering filename. Returns the relative path inside dstRoot.
func CopyRegularFileSafe(srcRoot, srcPath, dstRoot, dstSubdir string) (string, error) {
resolvedSrc, ok := ResolveConfined(srcRoot, "", srcPath)
if !ok {
return "", errors.New("source path escapes allowed root")
}
lfi, err := os.Lstat(resolvedSrc)
if err != nil {
return "", err
}
if !lfi.Mode().IsRegular() {
return "", fmt.Errorf("refusing non-regular file: %s", filepath.Base(resolvedSrc))
}
dstDir := filepath.Join(filepath.Clean(dstRoot), dstSubdir)
if err := os.MkdirAll(dstDir, 0o777); err != nil {
return "", err
}
if _, ok := CheckPathWithinRoot(dstRoot, dstDir); !ok {
return "", errors.New("destination escapes allowed root")
}
base := filepath.Base(resolvedSrc)
ext := filepath.Ext(base)
stem := strings.TrimSuffix(base, ext)
dstPath := filepath.Join(dstDir, base)
for i := 1; ; i++ {
if _, err := os.Lstat(dstPath); os.IsNotExist(err) {
break
}
dstPath = filepath.Join(dstDir, fmt.Sprintf("%s-%d%s", stem, i, ext))
}
in, err := os.Open(resolvedSrc)
if err != nil {
return "", err
}
defer in.Close()
out, err := os.OpenFile(dstPath, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0o666)
if err != nil {
return "", err
}
if _, err := io.Copy(out, in); err != nil {
out.Close()
_ = os.Remove(dstPath)
return "", err
}
if err := out.Close(); err != nil {
_ = os.Remove(dstPath)
return "", err
}
rel, err := filepath.Rel(filepath.Clean(dstRoot), dstPath)
if err != nil {
return "", err
}
return filepath.ToSlash(rel), nil
}
// evalDeepest resolves symlinks for the deepest existing ancestor of p and
// re-attaches any non-existent trailing path components.
func evalDeepest(p string) (string, error) {
p = filepath.Clean(p)
if real, err := filepath.EvalSymlinks(p); err == nil {
return real, nil
}
var tail []string
cur := p
for {
parent := filepath.Dir(cur)
if parent == cur {
return p, nil
}
tail = append([]string{filepath.Base(cur)}, tail...)
cur = parent
if real, err := filepath.EvalSymlinks(cur); err == nil {
parts := append([]string{real}, tail...)
return filepath.Clean(filepath.Join(parts...)), nil
}
}
}
func isWithin(root, candidate string) bool {
if candidate == root {
return true
}
sep := string(os.PathSeparator)
if strings.HasSuffix(root, sep) {
return strings.HasPrefix(candidate, root)
}
return strings.HasPrefix(candidate, root+sep)
}