ACP / MCP 完善

This commit is contained in:
2026-06-11 12:43:18 +08:00
parent 1415d3b43b
commit 0561e126cd
22 changed files with 786 additions and 219 deletions
+6 -31
View File
@@ -4,11 +4,11 @@ import (
"context"
"encoding/json"
"errors"
"fmt"
"io/fs"
"os"
"path/filepath"
"strings"
"github.com/yan1h/agent-coding-workflow/internal/acp/pathsafe"
)
// FsReadHandler handles fs/read_text_file (spec §5.4).
@@ -75,34 +75,9 @@ func sliceLines(s string, line, limit *int) string {
return strings.Join(lines[start:end], "\n")
}
// resolveSafePath duplicates the logic from internal/acp.ResolveSafePath to
// avoid an import cycle (handlers is a sub-package and acp imports handlers).
// resolveSafePath 委托共享实现 pathsafe.ResolveSafePath
// handlers 子包不能 import internal/acp 主包(acp 依赖 handlers,会循环),
// 故校验逻辑抽到 internal/acp/pathsafe 子包共用。
func resolveSafePath(cwd, requested string) (string, error) {
if !filepath.IsAbs(cwd) {
return "", fmt.Errorf("cwd must be absolute")
}
cleanCwd := filepath.Clean(cwd)
var abs string
if filepath.IsAbs(requested) {
abs = filepath.Clean(requested)
} else {
abs = filepath.Clean(filepath.Join(cleanCwd, requested))
}
if !hasPathPrefix(abs, cleanCwd) {
return "", fmt.Errorf("path outside worktree")
}
if real, err := filepath.EvalSymlinks(abs); err == nil {
if !hasPathPrefix(real, cleanCwd) {
return "", fmt.Errorf("path resolves outside worktree via symlink")
}
}
return abs, nil
}
func hasPathPrefix(abs, base string) bool {
if abs == base {
return true
}
sep := string(filepath.Separator)
return strings.HasPrefix(abs, base+sep)
return pathsafe.ResolveSafePath(cwd, requested)
}
@@ -45,3 +45,28 @@ func TestFsWrite_OutsideWorktree(t *testing.T) {
require.NotNil(t, res.Err)
assert.Equal(t, -32001, res.Err.Code)
}
// 父目录是 worktree 内指向外部的 symlink、目标文件不存在 → 必须被拒,
// 且外部目录不能出现新建文件(防 symlink 逃逸写出 worktree)。
func TestFsWrite_SymlinkDirEscape(t *testing.T) {
t.Parallel()
tmp := t.TempDir()
outside := t.TempDir()
link := filepath.Join(tmp, "link-dir")
if err := os.Symlink(outside, link); err != nil {
t.Skipf("symlink not supported on this platform: %v", err)
}
h := handlers.NewFsWriteHandler()
sess := handlers.SessionContext{CwdPath: tmp}
params := mustJSON(t, map[string]any{
"sessionId": "x", "path": filepath.Join(link, "escape.txt"), "content": "evil",
})
res := h.Handle(context.Background(), sess, params)
require.NotNil(t, res.Err)
assert.Equal(t, -32001, res.Err.Code)
_, statErr := os.Stat(filepath.Join(outside, "escape.txt"))
assert.True(t, os.IsNotExist(statErr), "外部目录不应被写入")
}