mirror of
https://github.com/RuoJi6/ARTEX.git
synced 2026-12-02 12:01:50 +08:00
- 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
491 lines
14 KiB
Go
491 lines
14 KiB
Go
package sandbox
|
|
|
|
import (
|
|
"bufio"
|
|
"bytes"
|
|
"context"
|
|
"encoding/binary"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"net"
|
|
"net/http"
|
|
"net/url"
|
|
"strings"
|
|
"sync"
|
|
"time"
|
|
)
|
|
|
|
const dockerAPIVersion = "/v1.43"
|
|
|
|
// dockerClient is a minimal, zero-dependency Docker Engine HTTP client supporting
|
|
// both Unix domain sockets (unix:///var/run/docker.sock) and TCP endpoints
|
|
// (http://docker-socket-proxy:2375 or tcp://host:2375).
|
|
type dockerClient struct {
|
|
scheme string // "unix" or "tcp"
|
|
address string // socket path or host:port
|
|
http *http.Client
|
|
}
|
|
|
|
func newDockerClient(dockerHost string) (*dockerClient, error) {
|
|
raw := strings.TrimSpace(dockerHost)
|
|
if raw == "" {
|
|
raw = "unix:///var/run/docker.sock"
|
|
}
|
|
dc := &dockerClient{}
|
|
switch {
|
|
case strings.HasPrefix(raw, "unix://"):
|
|
dc.scheme = "unix"
|
|
dc.address = strings.TrimPrefix(raw, "unix://")
|
|
case strings.HasPrefix(raw, "tcp://"):
|
|
dc.scheme = "tcp"
|
|
dc.address = strings.TrimPrefix(raw, "tcp://")
|
|
case strings.HasPrefix(raw, "http://"):
|
|
u, err := url.Parse(raw)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("invalid docker host %q: %w", raw, err)
|
|
}
|
|
dc.scheme = "tcp"
|
|
dc.address = u.Host
|
|
default:
|
|
return nil, fmt.Errorf("unsupported docker host scheme: %q", raw)
|
|
}
|
|
tr := &http.Transport{
|
|
DialContext: func(ctx context.Context, _, _ string) (net.Conn, error) {
|
|
var d net.Dialer
|
|
if dc.scheme == "unix" {
|
|
return d.DialContext(ctx, "unix", dc.address)
|
|
}
|
|
return d.DialContext(ctx, "tcp", dc.address)
|
|
},
|
|
MaxIdleConns: 16,
|
|
IdleConnTimeout: 60 * time.Second,
|
|
DisableCompression: true,
|
|
ResponseHeaderTimeout: 30 * time.Second,
|
|
}
|
|
dc.http = &http.Client{Transport: tr}
|
|
return dc, nil
|
|
}
|
|
|
|
func (c *dockerClient) dialRaw(ctx context.Context) (net.Conn, error) {
|
|
var d net.Dialer
|
|
if c.scheme == "unix" {
|
|
return d.DialContext(ctx, "unix", c.address)
|
|
}
|
|
return d.DialContext(ctx, "tcp", c.address)
|
|
}
|
|
|
|
func (c *dockerClient) doJSON(ctx context.Context, method, path string, reqBody, out any) (int, []byte, error) {
|
|
var bodyReader io.Reader
|
|
if reqBody != nil {
|
|
b, err := json.Marshal(reqBody)
|
|
if err != nil {
|
|
return 0, nil, err
|
|
}
|
|
bodyReader = bytes.NewReader(b)
|
|
}
|
|
req, err := http.NewRequestWithContext(ctx, method, "http://docker"+dockerAPIVersion+path, bodyReader)
|
|
if err != nil {
|
|
return 0, nil, err
|
|
}
|
|
if reqBody != nil {
|
|
req.Header.Set("Content-Type", "application/json")
|
|
}
|
|
resp, err := c.http.Do(req)
|
|
if err != nil {
|
|
return 0, nil, err
|
|
}
|
|
defer resp.Body.Close()
|
|
data, err := io.ReadAll(io.LimitReader(resp.Body, 4<<20))
|
|
if err != nil {
|
|
return resp.StatusCode, nil, err
|
|
}
|
|
if resp.StatusCode >= 400 {
|
|
var derr struct {
|
|
Message string `json:"message"`
|
|
}
|
|
_ = json.Unmarshal(data, &derr)
|
|
msg := strings.TrimSpace(derr.Message)
|
|
if msg == "" {
|
|
msg = strings.TrimSpace(string(data))
|
|
}
|
|
return resp.StatusCode, data, &dockerAPIError{Status: resp.StatusCode, Message: msg}
|
|
}
|
|
if out != nil && len(data) > 0 {
|
|
if err := json.Unmarshal(data, out); err != nil {
|
|
return resp.StatusCode, data, err
|
|
}
|
|
}
|
|
return resp.StatusCode, data, nil
|
|
}
|
|
|
|
type dockerAPIError struct {
|
|
Status int
|
|
Message string
|
|
}
|
|
|
|
func (e *dockerAPIError) Error() string {
|
|
return fmt.Sprintf("docker api %d: %s", e.Status, e.Message)
|
|
}
|
|
|
|
func isDockerNotFound(err error) bool {
|
|
var de *dockerAPIError
|
|
return errors.As(err, &de) && de.Status == http.StatusNotFound
|
|
}
|
|
|
|
func isDockerNotModified(err error) bool {
|
|
var de *dockerAPIError
|
|
return errors.As(err, &de) && de.Status == http.StatusNotModified
|
|
}
|
|
|
|
func (c *dockerClient) Ping(ctx context.Context) error {
|
|
_, _, err := c.doJSON(ctx, http.MethodGet, "/_ping", nil, nil)
|
|
return err
|
|
}
|
|
|
|
// dockerNetworkInspect holds the subset of network fields we inspect.
|
|
type dockerNetworkInspect struct {
|
|
ID string `json:"Id"`
|
|
Name string `json:"Name"`
|
|
IPAM struct {
|
|
Config []struct {
|
|
Subnet string `json:"Subnet"`
|
|
Gateway string `json:"Gateway"`
|
|
} `json:"Config"`
|
|
} `json:"IPAM"`
|
|
}
|
|
|
|
func (c *dockerClient) InspectNetwork(ctx context.Context, name string) (*dockerNetworkInspect, error) {
|
|
var out dockerNetworkInspect
|
|
_, _, err := c.doJSON(ctx, http.MethodGet, "/networks/"+url.PathEscape(name), nil, &out)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return &out, nil
|
|
}
|
|
|
|
// EnsureNetwork ensures the isolated sandbox bridge network exists with ICC disabled.
|
|
func (c *dockerClient) EnsureNetwork(ctx context.Context, name string) (*dockerNetworkInspect, error) {
|
|
if info, err := c.InspectNetwork(ctx, name); err == nil {
|
|
return info, nil
|
|
} else if !isDockerNotFound(err) {
|
|
return nil, err
|
|
}
|
|
payload := map[string]any{
|
|
"Name": name,
|
|
"CheckDuplicate": true,
|
|
"Driver": "bridge",
|
|
"Options": map[string]string{
|
|
"com.docker.network.bridge.enable_icc": "false",
|
|
},
|
|
"Labels": map[string]string{
|
|
"artex.managed": "true",
|
|
},
|
|
}
|
|
if _, _, err := c.doJSON(ctx, http.MethodPost, "/networks/create", payload, nil); err != nil {
|
|
if info, err2 := c.InspectNetwork(ctx, name); err2 == nil {
|
|
return info, nil
|
|
}
|
|
return nil, err
|
|
}
|
|
return c.InspectNetwork(ctx, name)
|
|
}
|
|
|
|
type dockerContainerInspect struct {
|
|
ID string `json:"Id"`
|
|
Name string `json:"Name"`
|
|
Created string `json:"Created"`
|
|
State struct {
|
|
Status string `json:"Status"`
|
|
Running bool `json:"Running"`
|
|
Paused bool `json:"Paused"`
|
|
StartedAt string `json:"StartedAt"`
|
|
ExitCode int `json:"ExitCode"`
|
|
} `json:"State"`
|
|
Config struct {
|
|
Image string `json:"Image"`
|
|
Labels map[string]string `json:"Labels"`
|
|
} `json:"Config"`
|
|
HostConfig struct {
|
|
Runtime string `json:"Runtime"`
|
|
NetworkMode string `json:"NetworkMode"`
|
|
Memory int64 `json:"Memory"`
|
|
} `json:"HostConfig"`
|
|
}
|
|
|
|
func (c *dockerClient) InspectContainer(ctx context.Context, idOrName string) (*dockerContainerInspect, error) {
|
|
var out dockerContainerInspect
|
|
_, _, err := c.doJSON(ctx, http.MethodGet, "/containers/"+url.PathEscape(idOrName)+"/json", nil, &out)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return &out, nil
|
|
}
|
|
|
|
type dockerContainerListItem struct {
|
|
ID string `json:"Id"`
|
|
Names []string `json:"Names"`
|
|
Image string `json:"Image"`
|
|
State string `json:"State"`
|
|
Status string `json:"Status"`
|
|
Created int64 `json:"Created"`
|
|
Labels map[string]string `json:"Labels"`
|
|
}
|
|
|
|
func (c *dockerClient) ListContainersByLabel(ctx context.Context, labels map[string]string) ([]dockerContainerListItem, error) {
|
|
labelList := make([]string, 0, len(labels))
|
|
for k, v := range labels {
|
|
if v == "" {
|
|
labelList = append(labelList, k)
|
|
} else {
|
|
labelList = append(labelList, k+"="+v)
|
|
}
|
|
}
|
|
filtersJSON, _ := json.Marshal(map[string][]string{"label": labelList})
|
|
path := "/containers/json?all=true&filters=" + url.QueryEscape(string(filtersJSON))
|
|
var out []dockerContainerListItem
|
|
_, _, err := c.doJSON(ctx, http.MethodGet, path, nil, &out)
|
|
return out, err
|
|
}
|
|
|
|
func (c *dockerClient) CreateContainer(ctx context.Context, name string, spec map[string]any) (string, error) {
|
|
var resp struct {
|
|
ID string `json:"Id"`
|
|
}
|
|
_, _, err := c.doJSON(ctx, http.MethodPost, "/containers/create?name="+url.QueryEscape(name), spec, &resp)
|
|
return resp.ID, err
|
|
}
|
|
|
|
func (c *dockerClient) StartContainer(ctx context.Context, idOrName string) error {
|
|
_, _, err := c.doJSON(ctx, http.MethodPost, "/containers/"+url.PathEscape(idOrName)+"/start", nil, nil)
|
|
if isDockerNotModified(err) {
|
|
return nil
|
|
}
|
|
return err
|
|
}
|
|
|
|
func (c *dockerClient) StopContainer(ctx context.Context, idOrName string, timeoutSec int) error {
|
|
if timeoutSec <= 0 {
|
|
timeoutSec = 5
|
|
}
|
|
path := fmt.Sprintf("/containers/%s/stop?t=%d", url.PathEscape(idOrName), timeoutSec)
|
|
_, _, err := c.doJSON(ctx, http.MethodPost, path, nil, nil)
|
|
if isDockerNotModified(err) || isDockerNotFound(err) {
|
|
return nil
|
|
}
|
|
return err
|
|
}
|
|
|
|
func (c *dockerClient) RemoveContainer(ctx context.Context, idOrName string) error {
|
|
path := "/containers/" + url.PathEscape(idOrName) + "?force=true&v=true"
|
|
_, _, err := c.doJSON(ctx, http.MethodDelete, path, nil, nil)
|
|
if isDockerNotFound(err) {
|
|
return nil
|
|
}
|
|
return err
|
|
}
|
|
|
|
type dockerStats struct {
|
|
CPUPercent float64
|
|
MemUsageBytes uint64
|
|
MemLimitBytes uint64
|
|
PidsCurrent uint64
|
|
}
|
|
|
|
func (c *dockerClient) ContainerStats(ctx context.Context, idOrName string) (dockerStats, error) {
|
|
var raw struct {
|
|
CPUStats struct {
|
|
CPUUsage struct {
|
|
TotalUsage uint64 `json:"total_usage"`
|
|
} `json:"cpu_usage"`
|
|
SystemCPUUsage uint64 `json:"system_cpu_usage"`
|
|
OnlineCPUs uint32 `json:"online_cpus"`
|
|
} `json:"cpu_stats"`
|
|
PreCPUStats struct {
|
|
CPUUsage struct {
|
|
TotalUsage uint64 `json:"total_usage"`
|
|
} `json:"cpu_usage"`
|
|
SystemCPUUsage uint64 `json:"system_cpu_usage"`
|
|
} `json:"precpu_stats"`
|
|
MemoryStats struct {
|
|
Usage uint64 `json:"usage"`
|
|
Limit uint64 `json:"limit"`
|
|
Stats map[string]uint64 `json:"stats"`
|
|
} `json:"memory_stats"`
|
|
PidsStats struct {
|
|
Current uint64 `json:"current"`
|
|
} `json:"pids_stats"`
|
|
}
|
|
_, _, err := c.doJSON(ctx, http.MethodGet, "/containers/"+url.PathEscape(idOrName)+"/stats?stream=false", nil, &raw)
|
|
if err != nil {
|
|
return dockerStats{}, err
|
|
}
|
|
cpuDelta := float64(0)
|
|
if raw.CPUStats.CPUUsage.TotalUsage > raw.PreCPUStats.CPUUsage.TotalUsage {
|
|
cpuDelta = float64(raw.CPUStats.CPUUsage.TotalUsage - raw.PreCPUStats.CPUUsage.TotalUsage)
|
|
}
|
|
sysDelta := float64(0)
|
|
if raw.CPUStats.SystemCPUUsage > raw.PreCPUStats.SystemCPUUsage {
|
|
sysDelta = float64(raw.CPUStats.SystemCPUUsage - raw.PreCPUStats.SystemCPUUsage)
|
|
}
|
|
cpus := float64(raw.CPUStats.OnlineCPUs)
|
|
if cpus == 0 {
|
|
cpus = 1
|
|
}
|
|
cpuPct := 0.0
|
|
if sysDelta > 0 && cpuDelta > 0 {
|
|
cpuPct = (cpuDelta / sysDelta) * cpus * 100.0
|
|
}
|
|
memUsage := raw.MemoryStats.Usage
|
|
if inactive := raw.MemoryStats.Stats["inactive_file"]; inactive > 0 && memUsage > inactive {
|
|
memUsage -= inactive
|
|
}
|
|
return dockerStats{
|
|
CPUPercent: cpuPct,
|
|
MemUsageBytes: memUsage,
|
|
MemLimitBytes: raw.MemoryStats.Limit,
|
|
PidsCurrent: raw.PidsStats.Current,
|
|
}, nil
|
|
}
|
|
|
|
type dockerExecCreateReq struct {
|
|
AttachStdin bool `json:"AttachStdin"`
|
|
AttachStdout bool `json:"AttachStdout"`
|
|
AttachStderr bool `json:"AttachStderr"`
|
|
Tty bool `json:"Tty"`
|
|
Env []string `json:"Env,omitempty"`
|
|
Cmd []string `json:"Cmd"`
|
|
WorkingDir string `json:"WorkingDir,omitempty"`
|
|
User string `json:"User,omitempty"`
|
|
}
|
|
|
|
func (c *dockerClient) ExecCreate(ctx context.Context, containerID string, req dockerExecCreateReq) (string, error) {
|
|
var resp struct {
|
|
ID string `json:"Id"`
|
|
}
|
|
_, _, err := c.doJSON(ctx, http.MethodPost, "/containers/"+url.PathEscape(containerID)+"/exec", req, &resp)
|
|
return resp.ID, err
|
|
}
|
|
|
|
type dockerExecInspect struct {
|
|
ID string `json:"ID"`
|
|
Running bool `json:"Running"`
|
|
ExitCode int `json:"ExitCode"`
|
|
Pid int `json:"Pid"`
|
|
}
|
|
|
|
func (c *dockerClient) ExecInspect(ctx context.Context, execID string) (dockerExecInspect, error) {
|
|
var out dockerExecInspect
|
|
_, _, err := c.doJSON(ctx, http.MethodGet, "/exec/"+url.PathEscape(execID)+"/json", nil, &out)
|
|
return out, err
|
|
}
|
|
|
|
// ExecStartStream hijacks a raw HTTP/1.1 connection to POST /exec/<id>/start
|
|
// and demultiplexes Docker's 8-byte framed stdout/stderr stream while keeping
|
|
// the connection writable for stdin.
|
|
func (c *dockerClient) ExecStartStream(ctx context.Context, execID string) (*hijackedExec, error) {
|
|
conn, err := c.dialRaw(ctx)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
body := `{"Detach":false,"Tty":false}`
|
|
reqStr := fmt.Sprintf(
|
|
"POST %s/exec/%s/start HTTP/1.1\r\nHost: docker\r\nConnection: Upgrade\r\nUpgrade: tcp\r\nContent-Type: application/json\r\nContent-Length: %d\r\n\r\n%s",
|
|
dockerAPIVersion, url.PathEscape(execID), len(body), body,
|
|
)
|
|
if _, err := io.WriteString(conn, reqStr); err != nil {
|
|
conn.Close()
|
|
return nil, err
|
|
}
|
|
br := bufio.NewReaderSize(conn, 64*1024)
|
|
resp, err := http.ReadResponse(br, &http.Request{Method: http.MethodPost})
|
|
if err != nil {
|
|
conn.Close()
|
|
return nil, err
|
|
}
|
|
if resp.StatusCode != http.StatusSwitchingProtocols && resp.StatusCode != http.StatusOK {
|
|
errBody, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))
|
|
conn.Close()
|
|
return nil, fmt.Errorf("docker exec start failed (%d): %s", resp.StatusCode, strings.TrimSpace(string(errBody)))
|
|
}
|
|
|
|
stdoutR, stdoutW := io.Pipe()
|
|
stderrR, stderrW := io.Pipe()
|
|
done := make(chan error, 1)
|
|
|
|
go func() {
|
|
err := demuxDockerStream(br, stdoutW, stderrW)
|
|
_ = stdoutW.Close()
|
|
_ = stderrW.Close()
|
|
done <- err
|
|
}()
|
|
|
|
return &hijackedExec{
|
|
conn: conn,
|
|
stdout: stdoutR,
|
|
stderr: stderrR,
|
|
done: done,
|
|
}, nil
|
|
}
|
|
|
|
type hijackedExec struct {
|
|
conn net.Conn
|
|
stdout io.ReadCloser
|
|
stderr io.ReadCloser
|
|
done chan error
|
|
closeOnce sync.Once
|
|
}
|
|
|
|
func (h *hijackedExec) Write(p []byte) (int, error) {
|
|
return h.conn.Write(p)
|
|
}
|
|
|
|
func (h *hijackedExec) CloseWrite() error {
|
|
if cw, ok := h.conn.(interface{ CloseWrite() error }); ok {
|
|
return cw.CloseWrite()
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (h *hijackedExec) Close() error {
|
|
var err error
|
|
h.closeOnce.Do(func() {
|
|
err = h.conn.Close()
|
|
})
|
|
return err
|
|
}
|
|
|
|
// demuxDockerStream parses Docker's non-TTY multiplexed stream protocol:
|
|
// each frame has an 8-byte header [streamType, 0, 0, 0, len(uint32 BE)].
|
|
func demuxDockerStream(r io.Reader, stdout, stderr io.Writer) error {
|
|
var hdr [8]byte
|
|
for {
|
|
_, err := io.ReadFull(r, hdr[:])
|
|
if err != nil {
|
|
if errors.Is(err, io.EOF) || errors.Is(err, io.ErrUnexpectedEOF) {
|
|
return nil
|
|
}
|
|
return err
|
|
}
|
|
n := int64(binary.BigEndian.Uint32(hdr[4:8]))
|
|
var dst io.Writer
|
|
switch hdr[0] {
|
|
case 1:
|
|
dst = stdout
|
|
case 2:
|
|
dst = stderr
|
|
default:
|
|
dst = io.Discard
|
|
}
|
|
if n > 0 {
|
|
if _, err := io.CopyN(dst, r, n); err != nil {
|
|
if errors.Is(err, io.EOF) {
|
|
return nil
|
|
}
|
|
return err
|
|
}
|
|
}
|
|
}
|
|
}
|