Files
ARTEX-chixuweihu/server/mcpstdio.go
T
ji ruo d786de90af feat(traffic,sandbox): add TUN/netstack transparent gateway, egress controls, CAP_NET_RAW hardening, and i18n fixes
- Implement full-traffic transparent gateway (cmd/artex-gateway, traffic/netstack.go, traffic/transparent.go) using Linux TUN + gVisor netstack deferred TCP handshakes (eliminating nmap/nc false-positive open ports), real ICMPv4 Echo proxying, UDP/DNS interception, and per-container upstream proxy overrides.
- Add egress blacklist + asset-intercept sync, non-HTTP flow/DNS SQLite persistence and APIs, and /system/proxy & /function/traffic TCP/UDP/DNS UI panels.
- Fix sandbox Playwright MCP browser loopback --proxy-server rewrite and NODE_EXTRA_CA_CERTS override in server/mcpstdio.go.
- Strip all SUID/SGID binaries in Dockerfile.sandbox, grant minimal cap_net_raw+ep to nmap/nping/ping with ARTEX_SANDBOX_ALLOW_NET_RAW toggle, and enforce IPv4/IPv6 anti-spoofing in iptables and netstack.
- Remove hardcoded Chinese "(全局)" from GET /api/proxy/routes, localize ContainerRoutesTab / NonHTTPTrafficPanel labels, and expose reactive locale/isEn from useLiveTranslation for React Compiler compatibility.
2026-12-02 02:51:36 +08:00

511 lines
13 KiB
Go

package server
import (
"bufio"
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net"
"net/url"
"os"
"os/exec"
"sort"
"strings"
"sync"
"github.com/Autumn-27/artex/internal/sandbox"
"github.com/Autumn-27/norma/llm"
"github.com/Autumn-27/norma/mcp"
"github.com/Autumn-27/norma/permission"
actool "github.com/Autumn-27/norma/tool"
)
type stdioRPCRequest struct {
JSONRPC string `json:"jsonrpc"`
ID int `json:"id,omitempty"`
Method string `json:"method"`
Params any `json:"params,omitempty"`
}
type stdioRPCResponse struct {
JSONRPC string `json:"jsonrpc"`
ID int `json:"id"`
Result json.RawMessage `json:"result"`
Error *stdioRPCError `json:"error"`
}
type stdioRPCError struct {
Code int `json:"code"`
Message string `json:"message"`
}
func (e *stdioRPCError) Error() string {
return fmt.Sprintf("mcp rpc error %d: %s", e.Code, e.Message)
}
type stdioRemoteTool struct {
Name string `json:"name"`
Description string `json:"description"`
InputSchema map[string]any `json:"inputSchema"`
}
// tailBuffer keeps the last limit bytes written to it so child-process stderr
// can surface actionable diagnostics without unbounded memory growth.
type tailBuffer struct {
mu sync.Mutex
limit int
buf []byte
}
func newTailBuffer(limit int) *tailBuffer {
return &tailBuffer{limit: limit}
}
func (t *tailBuffer) Write(p []byte) (int, error) {
t.mu.Lock()
defer t.mu.Unlock()
if len(p) >= t.limit {
t.buf = append(t.buf[:0], p[len(p)-t.limit:]...)
return len(p), nil
}
if excess := len(t.buf) + len(p) - t.limit; excess > 0 {
copy(t.buf, t.buf[excess:])
t.buf = t.buf[:len(t.buf)-excess]
}
t.buf = append(t.buf, p...)
return len(p), nil
}
func (t *tailBuffer) String() string {
t.mu.Lock()
defer t.mu.Unlock()
return strings.TrimSpace(string(t.buf))
}
// stdioMCPClient speaks JSON-RPC 2.0 over newline-delimited stdio to a child
// MCP server spawned in an explicit working directory (so file-writing tools
// such as Playwright's browser_take_screenshot resolve relative paths inside
// the active agent session/workspace rather than the server binary's CWD).
type stdioMCPClient struct {
server string
w io.Writer
mu sync.Mutex
nextID int
pending map[int]chan stdioRPCResponse
closeCh chan struct{}
once sync.Once
cmd *exec.Cmd
stream *sandbox.StreamSession
stdin io.Closer
stderr *tailBuffer
releaseSlot func()
closeOnce sync.Once
}
const maxSandboxBrowserMCPPerTarget = 2
var (
sandboxBrowserSlotsMu sync.Mutex
sandboxBrowserSlots = map[string]chan struct{}{}
)
func acquireSandboxBrowserSlot(ctx context.Context, targetKey string) (func(), error) {
sandboxBrowserSlotsMu.Lock()
ch, ok := sandboxBrowserSlots[targetKey]
if !ok {
ch = make(chan struct{}, maxSandboxBrowserMCPPerTarget)
sandboxBrowserSlots[targetKey] = ch
}
sandboxBrowserSlotsMu.Unlock()
select {
case ch <- struct{}{}:
var once sync.Once
return func() {
once.Do(func() { <-ch })
}, nil
case <-ctx.Done():
return nil, ctx.Err()
}
}
func newStdioMCPClient(ctx context.Context, server, workDir, command string, env map[string]string, args ...string) (*stdioMCPClient, error) {
if mgr := sandbox.Default(); mgr != nil && mgr.Enabled() {
if target, ok := sandbox.TargetFrom(ctx); ok {
return newSandboxStdioMCPClient(ctx, mgr, target, server, workDir, command, env, args...)
}
}
cmd := exec.Command(command, args...)
if strings.TrimSpace(workDir) != "" {
cmd.Dir = workDir
}
if len(env) > 0 {
cmd.Env = os.Environ()
for k, v := range env {
cmd.Env = append(cmd.Env, k+"="+v)
}
}
stdin, err := cmd.StdinPipe()
if err != nil {
return nil, err
}
stdout, err := cmd.StdoutPipe()
if err != nil {
return nil, err
}
stderr := newTailBuffer(4096)
cmd.Stderr = stderr
if err := cmd.Start(); err != nil {
return nil, err
}
c := &stdioMCPClient{
server: server,
w: stdin,
pending: map[int]chan stdioRPCResponse{},
closeCh: make(chan struct{}),
cmd: cmd,
stdin: stdin,
stderr: stderr,
}
go c.readLoop(stdout)
if err := c.initialize(ctx); err != nil {
_ = c.Close()
return nil, err
}
return c, nil
}
func newSandboxStdioMCPClient(ctx context.Context, mgr *sandbox.Manager, target sandbox.Target, server, workDir, command string, env map[string]string, args ...string) (*stdioMCPClient, error) {
var releaseSlot func()
if server == browserMCPName && target.Scope == sandbox.ScopeTask {
rel, err := acquireSandboxBrowserSlot(ctx, target.Key())
if err != nil {
return nil, fmt.Errorf("wait browser sandbox slot for %s: %w", target.Key(), err)
}
releaseSlot = rel
}
containerWorkDir := sandbox.ContainerWorkDir
if strings.TrimSpace(workDir) != "" {
containerWorkDir = sandbox.HostToContainerPath(mgr.Config().LocalRootFor(target), workDir)
}
sandboxProxyURL := ""
if mgr != nil {
sandboxProxyURL = stripURLCredentials(mgr.Config().ProxyURL)
}
adaptedArgs := adaptSandboxMCPArgs(args, sandboxProxyURL)
envSlice := buildSandboxMCPEnv(mgr, env)
stream, err := mgr.ExecStream(ctx, target, sandbox.ExecSpec{
Cmd: append([]string{command}, adaptedArgs...),
WorkDir: containerWorkDir,
Env: envSlice,
})
if err != nil {
if releaseSlot != nil {
releaseSlot()
}
return nil, err
}
stderr := newTailBuffer(4096)
go func() { _, _ = io.Copy(stderr, stream.Stderr) }()
c := &stdioMCPClient{
server: server,
w: stream.Stdin,
pending: map[int]chan stdioRPCResponse{},
closeCh: make(chan struct{}),
stream: stream,
stdin: stream.Stdin,
stderr: stderr,
releaseSlot: releaseSlot,
}
go c.readLoop(stream.Stdout)
if err := c.initialize(ctx); err != nil {
_ = c.Close()
return nil, err
}
return c, nil
}
// adaptSandboxMCPArgs rewrites loopback --proxy-server flags (such as
// http://127.0.0.1:8788 persisted for local mode by syncBrowserMCPProxy) to the
// sandbox-reachable recording proxy URL (e.g. http://172.30.0.2:8788).
// Chromium rejects inline credentials in --proxy-server, so sandboxProxyURL must
// be credential-free; Layer-1 container source IP provides attribution.
func adaptSandboxMCPArgs(args []string, sandboxProxyURL string) []string {
out := make([]string, 0, len(args))
for i := 0; i < len(args); i++ {
arg := args[i]
if arg == "--proxy-server" && i+1 < len(args) {
val := args[i+1]
i++
if isLoopbackProxyTarget(val) {
if sandboxProxyURL != "" {
out = append(out, "--proxy-server", sandboxProxyURL)
}
continue
}
out = append(out, "--proxy-server", val)
continue
}
if strings.HasPrefix(arg, "--proxy-server=") {
val := strings.TrimPrefix(arg, "--proxy-server=")
if isLoopbackProxyTarget(val) {
if sandboxProxyURL != "" {
out = append(out, "--proxy-server="+sandboxProxyURL)
}
continue
}
out = append(out, arg)
continue
}
out = append(out, arg)
}
return out
}
func isLoopbackProxyTarget(raw string) bool {
raw = strings.TrimSpace(raw)
if raw == "" {
return false
}
if !strings.Contains(raw, "://") {
raw = "http://" + raw
}
u, err := url.Parse(raw)
if err != nil {
return false
}
h := strings.ToLower(strings.Trim(strings.TrimSpace(u.Hostname()), "[]"))
if h == "localhost" || h == "0.0.0.0" || h == "::" {
return true
}
if ip := net.ParseIP(h); ip != nil && (ip.IsLoopback() || ip.IsUnspecified()) {
return true
}
return false
}
func stripURLCredentials(raw string) string {
raw = strings.TrimSpace(raw)
if raw == "" {
return ""
}
u, err := url.Parse(raw)
if err != nil {
return raw
}
u.User = nil
return u.String()
}
// buildSandboxMCPEnv merges MCP-configured env vars with sandbox proxy/CA env
// vars so host-side CA paths (like /app/data/traffic/_ca/mitmproxy-ca-cert.pem)
// never clobber the in-container mounted CA path (/etc/artex/ca.crt).
func buildSandboxMCPEnv(mgr *sandbox.Manager, userEnv map[string]string) []string {
merged := make(map[string]string, len(userEnv)+12)
hostCA := ""
if mgr != nil {
hostCA = strings.TrimSpace(mgr.Config().CACertPath)
}
for k, v := range userEnv {
if isHostCAPathOverride(k, v, hostCA) {
continue
}
merged[k] = v
}
if mgr != nil {
for _, kv := range mgr.ProxyEnv(true) {
if k, v, ok := strings.Cut(kv, "="); ok {
merged[k] = v
}
}
}
keys := make([]string, 0, len(merged))
for k := range merged {
keys = append(keys, k)
}
sort.Strings(keys)
out := make([]string, 0, len(keys))
for _, k := range keys {
out = append(out, k+"="+merged[k])
}
return out
}
func isHostCAPathOverride(key, val, hostCA string) bool {
switch key {
case "NODE_EXTRA_CA_CERTS", "SSL_CERT_FILE", "CURL_CA_BUNDLE", "REQUESTS_CA_BUNDLE", "GIT_SSL_CAINFO":
v := strings.TrimSpace(val)
if v == "" {
return true
}
if hostCA != "" && v == hostCA {
return true
}
// Persisted control-plane paths do not exist inside sandbox containers.
if strings.HasPrefix(v, "/app/data/") || strings.Contains(v, "mitmproxy-ca-cert.pem") {
return true
}
}
return false
}
func (c *stdioMCPClient) readLoop(r io.Reader) {
br := bufio.NewReaderSize(r, 64*1024)
for {
line, err := br.ReadBytes('\n')
line = bytes.TrimSpace(line)
if len(line) > 0 {
var resp stdioRPCResponse
if json.Unmarshal(line, &resp) == nil && resp.ID != 0 {
c.mu.Lock()
ch := c.pending[resp.ID]
delete(c.pending, resp.ID)
c.mu.Unlock()
if ch != nil {
ch <- resp
}
}
}
if err != nil {
if !errors.Is(err, io.EOF) {
break
}
break
}
}
c.once.Do(func() { close(c.closeCh) })
}
func (c *stdioMCPClient) writeLocked(v any) error {
data, err := json.Marshal(v)
if err != nil {
return err
}
data = append(data, '\n')
_, err = c.w.Write(data)
return err
}
func (c *stdioMCPClient) notify(method string, params any) error {
c.mu.Lock()
defer c.mu.Unlock()
return c.writeLocked(stdioRPCRequest{JSONRPC: "2.0", Method: method, Params: params})
}
func (c *stdioMCPClient) call(ctx context.Context, method string, params any) (json.RawMessage, error) {
c.mu.Lock()
c.nextID++
id := c.nextID
ch := make(chan stdioRPCResponse, 1)
c.pending[id] = ch
err := c.writeLocked(stdioRPCRequest{JSONRPC: "2.0", ID: id, Method: method, Params: params})
c.mu.Unlock()
if err != nil {
return nil, err
}
select {
case <-ctx.Done():
return nil, ctx.Err()
case <-c.closeCh:
if msg := c.stderr.String(); msg != "" {
return nil, fmt.Errorf("mcp: connection closed (%s)", msg)
}
return nil, fmt.Errorf("mcp: connection closed")
case resp := <-ch:
if resp.Error != nil {
return nil, resp.Error
}
return resp.Result, nil
}
}
func (c *stdioMCPClient) initialize(ctx context.Context) error {
_, err := c.call(ctx, "initialize", map[string]any{
"protocolVersion": "2024-11-05",
"capabilities": map[string]any{},
"clientInfo": map[string]any{"name": "norma", "version": "0.2"},
})
if err != nil {
return err
}
return c.notify("notifications/initialized", map[string]any{})
}
func (c *stdioMCPClient) Tools(ctx context.Context) ([]actool.CoreTool, error) {
raw, err := c.call(ctx, "tools/list", map[string]any{})
if err != nil {
return nil, err
}
var res struct {
Tools []stdioRemoteTool `json:"tools"`
}
if err := json.Unmarshal(raw, &res); err != nil {
return nil, err
}
out := make([]actool.CoreTool, 0, len(res.Tools))
for _, rt := range res.Tools {
out = append(out, c.wrap(rt))
}
return out, nil
}
func (c *stdioMCPClient) wrap(rt stdioRemoteTool) actool.CoreTool {
schema := rt.InputSchema
if schema == nil {
schema = map[string]any{"type": "object"}
}
full := mcp.ToolName(c.server, rt.Name)
return actool.Build(actool.Spec{
Name: full,
Description: rt.Description,
Schema: schema,
Permissions: func(context.Context, json.RawMessage, permission.Context) permission.Decision {
return permission.AskUser("call MCP tool " + full + "?")
},
Run: func(ctx context.Context, in json.RawMessage, tc *actool.ToolContext) (actool.Result, error) {
var args any
if len(in) > 0 {
_ = json.Unmarshal(in, &args)
}
raw, err := c.call(ctx, "tools/call", map[string]any{"name": rt.Name, "arguments": args})
if err != nil {
return actool.Errorf("Error: " + err.Error()), nil
}
var res struct {
Content []struct {
Type string `json:"type"`
Text string `json:"text"`
} `json:"content"`
IsError bool `json:"isError"`
}
if err := json.Unmarshal(raw, &res); err != nil {
return actool.Errorf("Error: bad MCP response: " + err.Error()), nil
}
var text string
for _, blk := range res.Content {
text += blk.Text
}
return actool.Result{Content: []llm.ContentBlock{llm.TextBlock(actool.Capture(tc, text))}, IsError: res.IsError}, nil
},
})
}
func (c *stdioMCPClient) Close() error {
c.closeOnce.Do(func() {
if c.stdin != nil {
_ = c.stdin.Close()
}
if c.stream != nil {
_ = c.stream.Close()
}
if c.cmd != nil && c.cmd.Process != nil {
_ = c.cmd.Process.Kill()
_ = c.cmd.Wait()
}
if c.releaseSlot != nil {
c.releaseSlot()
}
})
return nil
}