fix: confine read_skill_file to the skill directory in the workspace agent

The first attempt checked containment in coderd with resolve-path and
then read the file in a second agent request, which raced with symlink
swaps, read the wrong file through in-skill directory symlinks, and
echoed outside targets in errors.

The agent's read-file endpoint now accepts an optional root parameter.
With root, it opens the relative path with os.OpenInRoot, which follows
symlinks only while they stay beneath root and walks the path in one
kernel operation. The SDK adds ReadFileInRoot, and LoadSkillFile reads
supporting files through it instead of resolving paths in coderd.
Agents without root support reject the parameter, so reads fail closed.
This commit is contained in:
Michael Suchacz committed 2026-10-28 20:22:48 +00:00
1 parent 01037053e0
commit 132c7bed66
7 files changed
+266 -213

No files matched your search

+61 -11
View File
@@ -65,6 +65,7 @@ func (api *API) HandleReadFile(rw http.ResponseWriter, r *http.Request) {
query := r.URL.Query()
parser := httpapi.NewQueryParamParser().RequiredNotEmpty("path")
path := parser.String(query, "", "path")
root := parser.String(query, "", "root")
offset := parser.PositiveInt64(query, 0, "offset")
limit := parser.PositiveInt64(query, 0, "limit")
parser.ErrorExcessParams(query)
@@ -76,7 +77,15 @@ func (api *API) HandleReadFile(rw http.ResponseWriter, r *http.Request) {
return
}
status, err := api.streamFile(ctx, rw, path, offset, limit)
var (
status HTTPResponseCode
err error
)
if root == "" {
status, err = api.streamFile(ctx, rw, path, offset, limit)
} else {
status, err = api.streamFileInRoot(ctx, rw, root, path, offset, limit)
}
if err != nil {
httpapi.Write(ctx, rw, status, codersdk.Response{
Message: err.Error(),
@@ -86,25 +95,66 @@ func (api *API) HandleReadFile(rw http.ResponseWriter, r *http.Request) {
}
func (api *API) streamFile(ctx context.Context, rw http.ResponseWriter, path string, offset, limit int64) (HTTPResponseCode, error) {
logger := api.logger.With(agentchat.Fields(ctx)...)
if !filepath.IsAbs(path) {
return http.StatusBadRequest, xerrors.Errorf("file path must be absolute: %q", path)
}
f, err := api.filesystem.Open(path)
if err != nil {
status := http.StatusInternalServerError
switch {
case errors.Is(err, os.ErrNotExist):
status = http.StatusNotFound
case errors.Is(err, os.ErrPermission):
status = http.StatusForbidden
}
return status, err
return openErrorStatus(err, http.StatusInternalServerError), err
}
defer f.Close()
return api.streamOpenFile(ctx, rw, f, path, offset, limit)
}
// streamFileInRoot streams path, a local path relative to root, and
// refuses any path whose walk, through symlinks included, leaves root.
// It uses os.Root on the OS filesystem rather than api.filesystem
// because afero has no traversal that stays beneath a directory, and
// os.Root checks containment and opens the file in one kernel walk.
func (api *API) streamFileInRoot(ctx context.Context, rw http.ResponseWriter, root, path string, offset, limit int64) (HTTPResponseCode, error) {
if !filepath.IsAbs(root) {
return http.StatusBadRequest, xerrors.Errorf("root must be absolute: %q", root)
}
if !filepath.IsLocal(path) {
return http.StatusBadRequest, xerrors.Errorf("file path must be relative to root: %q", path)
}
// The error names only root and path, never a symlink target, so
// a refusal does not reveal paths outside root.
f, err := os.OpenInRoot(root, path)
if err != nil {
return openErrorStatus(err, http.StatusBadRequest), err
}
defer f.Close()
return api.streamOpenFile(ctx, rw, f, path, offset, limit)
}
// openErrorStatus maps a file open error to an HTTP status, using
// fallback for errors other than not-exist and permission.
func openErrorStatus(err error, fallback HTTPResponseCode) HTTPResponseCode {
switch {
case errors.Is(err, os.ErrNotExist):
return http.StatusNotFound
case errors.Is(err, os.ErrPermission):
return http.StatusForbidden
default:
return fallback
}
}
// openFile is the part of an opened file that streamOpenFile needs,
// satisfied by both afero.File and *os.File.
type openFile interface {
io.ReaderAt
Stat() (os.FileInfo, error)
}
func (api *API) streamOpenFile(ctx context.Context, rw http.ResponseWriter, f openFile, path string, offset, limit int64) (HTTPResponseCode, error) {
logger := api.logger.With(agentchat.Fields(ctx)...)
stat, err := f.Stat()
if err != nil {
return http.StatusInternalServerError, err
+110
View File
@@ -8,6 +8,7 @@ import (
"io"
"net/http"
"net/http/httptest"
"net/url"
"os"
"path/filepath"
"runtime"
@@ -289,6 +290,115 @@ func TestReadFile(t *testing.T) {
}
}
func TestReadFileInRoot(t *testing.T) {
t.Parallel()
if runtime.GOOS == "windows" {
t.Skip("symlinks are not reliably supported on Windows")
}
base := t.TempDir()
logger := slogtest.Make(t, &slogtest.Options{IgnoreErrors: true}).Leveled(slog.LevelDebug)
osFs := afero.NewOsFs()
api := agentfiles.NewAPI(logger, osFs, nil)
const outsideBytes = "outside-secret-bytes"
outsideDir := filepath.Join(base, "outside")
outsideFile := filepath.Join(outsideDir, "secret.txt")
realSkills := filepath.Join(base, "real-skills")
root := filepath.Join(realSkills, "my-skill")
siblingDir := filepath.Join(realSkills, "other-skill")
linkedSkills := filepath.Join(base, "skills")
for _, dir := range []string{outsideDir, filepath.Join(root, "roles", "sub"), siblingDir} {
require.NoError(t, os.MkdirAll(dir, 0o755))
}
for name, content := range map[string]string{
outsideFile: outsideBytes,
filepath.Join(root, "notes.md"): "notes",
filepath.Join(root, "roles", "reviewer.md"): "reviewer",
filepath.Join(root, "reviewer.md"): "decoy",
filepath.Join(siblingDir, "other.md"): "sibling",
} {
require.NoError(t, os.WriteFile(name, []byte(content), 0o600))
}
for link, target := range map[string]string{
linkedSkills: realSkills,
filepath.Join(root, "rel-link.md"): "notes.md",
filepath.Join(root, "deep"): filepath.Join("roles", "sub"),
filepath.Join(root, "roles", "sub", "up.md"): filepath.Join("..", "reviewer.md"),
filepath.Join(root, "abs-inside.md"): filepath.Join(root, "notes.md"),
filepath.Join(root, "abs-outside.md"): outsideFile,
filepath.Join(root, "rel-escape.md"): filepath.Join("..", "..", "outside", "secret.txt"),
filepath.Join(root, "outdir"): filepath.Join("..", "..", "outside"),
filepath.Join(root, "sibling.md"): filepath.Join("..", "other-skill", "other.md"),
filepath.Join(root, "loop.md"): "loop.md",
filepath.Join(root, "roles", "sub", "escape-up.md"): filepath.Join("..", "..", "..", "..", "outside", "secret.txt"),
} {
require.NoError(t, os.Symlink(target, link))
}
tests := []struct {
name string
root string
path string
bytes string
errCode int
error string
}{
{name: "RegularFile", root: root, path: "notes.md", bytes: "notes"},
{name: "NestedFile", root: root, path: "roles/reviewer.md", bytes: "reviewer"},
{name: "RelativeSymlinkInside", root: root, path: "rel-link.md", bytes: "notes"},
// deep -> roles/sub and up.md -> ../reviewer.md resolve against
// the real parent, roles/sub, so the read is roles/reviewer.md and
// not the decoy at the skill root.
{name: "DirectorySymlinkThenDotDot", root: root, path: "deep/up.md", bytes: "reviewer"},
{name: "RootUnderSymlinkedAncestor", root: filepath.Join(linkedSkills, "my-skill"), path: "rel-link.md", bytes: "notes"},
{name: "AbsoluteSymlinkInside", root: root, path: "abs-inside.md", errCode: http.StatusBadRequest, error: "abs-inside.md"},
{name: "AbsoluteSymlinkOutside", root: root, path: "abs-outside.md", errCode: http.StatusBadRequest, error: "abs-outside.md"},
{name: "RelativeSymlinkEscapes", root: root, path: "rel-escape.md", errCode: http.StatusBadRequest, error: "rel-escape.md"},
{name: "NestedRelativeSymlinkEscapes", root: root, path: "deep/escape-up.md", errCode: http.StatusBadRequest, error: "escape-up.md"},
{name: "DirectorySymlinkEscapes", root: root, path: "outdir/secret.txt", errCode: http.StatusBadRequest, error: "outdir/secret.txt"},
{name: "SiblingSkill", root: root, path: "sibling.md", errCode: http.StatusBadRequest, error: "sibling.md"},
{name: "SymlinkLoop", root: root, path: "loop.md", errCode: http.StatusBadRequest, error: "loop.md"},
{name: "AbsolutePath", root: root, path: outsideFile, errCode: http.StatusBadRequest, error: "file path must be relative to root"},
{name: "DotDotPath", root: root, path: "../../outside/secret.txt", errCode: http.StatusBadRequest, error: "file path must be relative to root"},
{name: "RelativeRoot", root: "real-skills/my-skill", path: "notes.md", errCode: http.StatusBadRequest, error: "root must be absolute"},
{name: "NonExistent", root: root, path: "missing.md", errCode: http.StatusNotFound, error: "no such file"},
{name: "IsDir", root: root, path: "roles", errCode: http.StatusBadRequest, error: "not a file"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
ctx := testutil.Context(t, testutil.WaitShort)
query := url.Values{"root": {tt.root}, "path": {tt.path}}
w := httptest.NewRecorder()
r := httptest.NewRequestWithContext(ctx, http.MethodGet, "/read-file?"+query.Encode(), nil)
api.Routes().ServeHTTP(w, r)
body := w.Body.String()
require.NotContains(t, body, outsideBytes)
if tt.errCode == 0 {
require.Equal(t, http.StatusOK, w.Code, body)
require.Equal(t, tt.bytes, body)
return
}
require.Equal(t, tt.errCode, w.Code, body)
got := &codersdk.Error{}
require.NoError(t, json.Unmarshal([]byte(body), got))
require.ErrorContains(t, got, tt.error)
// A refusal names only the requested path, never a symlink
// target.
if tt.path != outsideFile {
require.NotContains(t, body, outsideDir)
require.NotContains(t, body, siblingDir)
}
})
}
}
func TestWriteFile(t *testing.T) {
t.Parallel()
+4 -42
View File
@@ -259,8 +259,8 @@ func bestEffortSkillFiles(
// LoadSkillFile reads a supporting file from a skill's directory.
// The relativePath is validated to prevent directory traversal and
// access to hidden files, and the file must resolve, through any
// symlinks, to a path inside the resolved skill directory.
// access to hidden files, and the workspace agent refuses a path that
// leaves the skill directory through a symlink.
func LoadSkillFile(
ctx context.Context,
conn workspacesdk.AgentConn,
@@ -271,28 +271,8 @@ func LoadSkillFile(
return "", err
}
fullPath := path.Join(skill.Dir, relativePath)
resolvedDir, err := conn.ResolvePath(ctx, skill.Dir)
if err != nil {
return "", xerrors.Errorf("resolve skill directory: %w", err)
}
resolvedPath, err := conn.ResolvePath(ctx, fullPath)
if err != nil {
return "", xerrors.Errorf("resolve skill file path: %w", err)
}
// The resolved target is not echoed so a symlink cannot be used to
// probe paths outside the skill directory.
if !isWithinSkillDir(resolvedDir, resolvedPath) {
return "", xerrors.Errorf(
"path %q resolves outside the skill directory", relativePath,
)
}
// Read the resolved path so the bytes come from the path that
// passed the containment check.
reader, _, err := conn.ReadFile(
ctx, resolvedPath, 0, maxSkillFileBytes+1,
reader, _, err := conn.ReadFileInRoot(
ctx, skill.Dir, relativePath, 0, maxSkillFileBytes+1,
)
if err != nil {
return "", xerrors.Errorf(
@@ -314,24 +294,6 @@ func LoadSkillFile(
return string(raw), nil
}
// isWithinSkillDir reports whether target is strictly inside dir. Both
// are paths the workspace agent resolved, so they are OS-native: a path
// that does not start with "/" is a Windows path and its backslashes are
// compared as forward slashes.
func isWithinSkillDir(dir, target string) bool {
dir = slashSkillPath(dir)
target = slashSkillPath(target)
prefix := strings.TrimSuffix(dir, "/") + "/"
return target != dir && strings.HasPrefix(target, prefix)
}
func slashSkillPath(p string) string {
if !strings.HasPrefix(p, "/") {
p = strings.ReplaceAll(p, `\`, "/")
}
return path.Clean(p)
}
// validateSkillFilePath rejects paths that could escape the skill
// directory or access hidden files. Only forward-relative,
// non-hidden paths are allowed.
+49 -155
View File
@@ -4,7 +4,6 @@ import (
"context"
"encoding/json"
"io"
"path"
"strings"
"testing"
"unicode/utf8"
@@ -49,14 +48,6 @@ func responseDir(t *testing.T, resp fantasy.ToolResponse) string {
return payload.Dir
}
// expectResolvePathIdentity makes the workspace report every path as
// already resolved, as it does when no symlinks are involved.
func expectResolvePathIdentity(conn *agentconnmock.MockAgentConn) {
conn.EXPECT().ResolvePath(gomock.Any(), gomock.Any()).DoAndReturn(
func(_ context.Context, p string) (string, error) { return p, nil },
).AnyTimes()
}
func TestFormatResolvedSkillIndex(t *testing.T) {
t.Parallel()
@@ -178,10 +169,10 @@ func TestLoadSkillFile(t *testing.T) {
Dir: "/work/.agents/skills/my-skill",
}
expectResolvePathIdentity(conn)
conn.EXPECT().ReadFile(
conn.EXPECT().ReadFileInRoot(
gomock.Any(),
"/work/.agents/skills/my-skill/roles/reviewer.md",
"/work/.agents/skills/my-skill",
"roles/reviewer.md",
int64(0),
int64(512*1024+1),
).Return(
@@ -283,10 +274,10 @@ func TestLoadSkillFile(t *testing.T) {
// Build a file that exceeds maxSkillFileBytes (512KB).
bigContent := strings.Repeat("x", 512*1024+100)
expectResolvePathIdentity(conn)
conn.EXPECT().ReadFile(
conn.EXPECT().ReadFileInRoot(
gomock.Any(),
"/work/.agents/skills/my-skill/large.txt",
"/work/.agents/skills/my-skill",
"large.txt",
int64(0),
int64(512*1024+1),
).Return(
@@ -303,129 +294,29 @@ func TestLoadSkillFile(t *testing.T) {
"content should be truncated to maxSkillFileBytes")
})
t.Run("ResolvedPathContainment", func(t *testing.T) {
t.Run("AgentRefusalReturned", func(t *testing.T) {
t.Parallel()
const (
posixDir = "/work/.agents/skills/my-skill"
windowsDir = `C:\Users\coder\.agents\skills\my-skill`
ctrl := gomock.NewController(t)
conn := agentconnmock.NewMockAgentConn(ctrl)
skill := chattool.SkillMeta{
Name: "my-skill",
Dir: "/work/.agents/skills/my-skill",
}
conn.EXPECT().ReadFileInRoot(
gomock.Any(),
"/work/.agents/skills/my-skill",
"refs.md",
int64(0),
int64(512*1024+1),
).Return(nil, "", xerrors.New("openat refs.md: path escapes from parent"))
_, err := chattool.LoadSkillFile(
context.Background(), conn, skill, "refs.md",
)
errResolve := xerrors.New("agent unreachable")
tests := []struct {
name string
dir string
relPath string
resolvedDir string
dirErr error
resolvedFile string
fileErr error
// wantRead is the path read from the workspace; empty means
// the file must not be read.
wantRead string
wantErr string
}{
{
name: "SymlinkEscapeRefused",
dir: posixDir,
relPath: "refs.md",
resolvedDir: posixDir,
resolvedFile: "/etc/passwd",
wantErr: "outside the skill directory",
},
{
name: "SiblingSkillPrefixRefused",
dir: posixDir,
relPath: "x.md",
resolvedDir: posixDir,
resolvedFile: "/work/.agents/skills/my-skill-other/x.md",
wantErr: "outside the skill directory",
},
{
name: "InSkillSymlinkReadsTarget",
dir: posixDir,
relPath: "latest.md",
resolvedDir: posixDir,
resolvedFile: posixDir + "/notes.md",
wantRead: posixDir + "/notes.md",
},
{
name: "SymlinkedAncestorAllowed",
dir: "/home/coder/.coder/skills/my-skill",
relPath: "roles/r.md",
resolvedDir: "/home/coder/real-skills/my-skill",
resolvedFile: "/home/coder/real-skills/my-skill/roles/r.md",
wantRead: "/home/coder/real-skills/my-skill/roles/r.md",
},
{
name: "ResolveDirectoryError",
dir: posixDir,
relPath: "notes.md",
dirErr: errResolve,
wantErr: "resolve skill directory",
},
{
name: "ResolveFileError",
dir: posixDir,
relPath: "notes.md",
resolvedDir: posixDir,
fileErr: errResolve,
wantErr: "resolve skill file path",
},
{
name: "WindowsInsideAllowed",
dir: windowsDir,
relPath: "roles/r.md",
resolvedDir: windowsDir,
resolvedFile: windowsDir + `\roles\r.md`,
wantRead: windowsDir + `\roles\r.md`,
},
{
name: "WindowsOutsideRefused",
dir: windowsDir,
relPath: "roles/r.md",
resolvedDir: windowsDir,
resolvedFile: `C:\Windows\win.ini`,
wantErr: "outside the skill directory",
},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
ctrl := gomock.NewController(t)
conn := agentconnmock.NewMockAgentConn(ctrl)
conn.EXPECT().ResolvePath(gomock.Any(), tc.dir).
Return(tc.resolvedDir, tc.dirErr)
if tc.dirErr == nil {
conn.EXPECT().ResolvePath(gomock.Any(), path.Join(tc.dir, tc.relPath)).
Return(tc.resolvedFile, tc.fileErr)
}
if tc.wantRead != "" {
conn.EXPECT().ReadFile(
gomock.Any(), tc.wantRead, int64(0), int64(512*1024+1),
).Return(io.NopCloser(strings.NewReader("in-skill content")), "text/markdown", nil)
}
content, err := chattool.LoadSkillFile(
context.Background(), conn,
chattool.SkillMeta{Name: "my-skill", Dir: tc.dir},
tc.relPath,
)
if tc.wantErr != "" {
require.ErrorContains(t, err, tc.wantErr)
if tc.resolvedFile != "" {
assert.NotContains(t, err.Error(), tc.resolvedFile,
"the error must not reveal the symlink target")
}
return
}
require.NoError(t, err)
assert.Equal(t, "in-skill content", content)
})
}
require.ErrorContains(t, err, "path escapes from parent")
})
}
@@ -921,10 +812,10 @@ func TestReadSkillFileTool(t *testing.T) {
Dir: "/work/.agents/skills/my-skill",
}}
expectResolvePathIdentity(conn)
conn.EXPECT().ReadFile(
conn.EXPECT().ReadFileInRoot(
gomock.Any(),
"/work/.agents/skills/my-skill/roles/reviewer.md",
"/work/.agents/skills/my-skill",
"roles/reviewer.md",
int64(0),
int64(512*1024+1),
).Return(
@@ -1008,13 +899,13 @@ func TestReadSkillFileTool(t *testing.T) {
ctrl := gomock.NewController(t)
conn := agentconnmock.NewMockAgentConn(ctrl)
expectResolvePathIdentity(conn)
conn.EXPECT().ReadFile(
conn.EXPECT().ReadFileInRoot(
gomock.Any(),
"/work/.agents/skills/manual/scripts/run.sh",
"/work/.agents/skills/manual",
"scripts/run.sh",
int64(0),
int64(512*1024+1),
).DoAndReturn(func(context.Context, string, int64, int64) (io.ReadCloser, string, error) {
).DoAndReturn(func(context.Context, string, string, int64, int64) (io.ReadCloser, string, error) {
return io.NopCloser(strings.NewReader("echo manual")), "text/plain", nil
}).Times(2)
@@ -1068,10 +959,10 @@ func TestReadSkillFileTool(t *testing.T) {
const content = "---\nname: example\ndescription: example\ndisable-model-invocation: true\n---\nCodeword.\n"
ctrl := gomock.NewController(t)
conn := agentconnmock.NewMockAgentConn(ctrl)
expectResolvePathIdentity(conn)
conn.EXPECT().ReadFile(
conn.EXPECT().ReadFileInRoot(
gomock.Any(),
"/work/.agents/skills/auto-helper/example-skill.md",
"/work/.agents/skills/auto-helper",
"example-skill.md",
int64(0),
int64(512*1024+1),
).Return(io.NopCloser(strings.NewReader(content)), "text/markdown", nil)
@@ -1103,13 +994,13 @@ func TestReadSkillFileTool(t *testing.T) {
ctrl := gomock.NewController(t)
conn := agentconnmock.NewMockAgentConn(ctrl)
expectResolvePathIdentity(conn)
conn.EXPECT().ReadFile(
conn.EXPECT().ReadFileInRoot(
gomock.Any(),
"/work/.agents/skills/manual/scripts/run.sh",
"/work/.agents/skills/manual",
"scripts/run.sh",
int64(0),
int64(512*1024+1),
).DoAndReturn(func(context.Context, string, int64, int64) (io.ReadCloser, string, error) {
).DoAndReturn(func(context.Context, string, string, int64, int64) (io.ReadCloser, string, error) {
return io.NopCloser(strings.NewReader("echo manual")), "text/plain", nil
})
@@ -1151,15 +1042,18 @@ func TestReadSkillFileTool(t *testing.T) {
assert.Contains(t, resp.Content, "not supported for personal skills")
})
t.Run("SymlinkEscapeRejected", func(t *testing.T) {
t.Run("AgentRefusalIsToolError", func(t *testing.T) {
t.Parallel()
ctrl := gomock.NewController(t)
conn := agentconnmock.NewMockAgentConn(ctrl)
conn.EXPECT().ResolvePath(gomock.Any(), "/work/.agents/skills/my-skill").
Return("/work/.agents/skills/my-skill", nil)
conn.EXPECT().ResolvePath(gomock.Any(), "/work/.agents/skills/my-skill/refs.md").
Return("/etc/passwd", nil)
conn.EXPECT().ReadFileInRoot(
gomock.Any(),
"/work/.agents/skills/my-skill",
"refs.md",
int64(0),
int64(512*1024+1),
).Return(nil, "", xerrors.New("openat refs.md: path escapes from parent"))
skills := []chattool.SkillMeta{{
Name: "my-skill",
@@ -1179,7 +1073,7 @@ func TestReadSkillFileTool(t *testing.T) {
})
require.NoError(t, err)
assert.True(t, resp.IsError)
assert.Contains(t, resp.Content, "outside the skill directory")
assert.Contains(t, resp.Content, "path escapes from parent")
})
t.Run("TraversalRejected", func(t *testing.T) {
+24 -3
View File
@@ -127,6 +127,7 @@ type AgentConn interface {
LS(ctx context.Context, path string, req LSRequest) (LSResponse, error)
ResolvePath(ctx context.Context, path string) (string, error)
ReadFile(ctx context.Context, path string, offset, limit int64) (io.ReadCloser, string, error)
ReadFileInRoot(ctx context.Context, root, path string, offset, limit int64) (io.ReadCloser, string, error)
ReadFileLines(ctx context.Context, path string, offset, limit int64, limits ReadFileLinesLimits) (ReadFileLinesResponse, error)
WriteFile(ctx context.Context, path string, reader io.Reader) error
UploadChatFile(ctx context.Context, req UploadChatFileRequest) (AgentUploadChatFileResponse, error)
@@ -1244,12 +1245,32 @@ func (c *agentConn) ReadFile(ctx context.Context, path string, offset, limit int
ctx, span := tracing.StartSpan(ctx)
defer span.End()
//nolint:bodyclose // we want to return the body so the caller can stream.
res, err := c.apiRequest(ctx, http.MethodGet, agentAPIPath("/api/v0/read-file", neturl.Values{
return c.readFileRequest(ctx, "", path, offset, limit)
}
// ReadFileInRoot reads from a file at path, relative to the absolute
// directory root, returning a file reader and the mime type. The agent
// refuses a path that leaves root, through symlinks included. Agents
// that predate root support reject the request.
func (c *agentConn) ReadFileInRoot(ctx context.Context, root, path string, offset, limit int64) (io.ReadCloser, string, error) {
ctx, span := tracing.StartSpan(ctx)
defer span.End()
return c.readFileRequest(ctx, root, path, offset, limit)
}
func (c *agentConn) readFileRequest(ctx context.Context, root, path string, offset, limit int64) (io.ReadCloser, string, error) {
query := neturl.Values{
"path": []string{path},
"offset": []string{strconv.FormatInt(offset, 10)},
"limit": []string{strconv.FormatInt(limit, 10)},
}), nil)
}
if root != "" {
query.Set("root", root)
}
//nolint:bodyclose // we want to return the body so the caller can stream.
res, err := c.apiRequest(ctx, http.MethodGet, agentAPIPath("/api/v0/read-file", query), nil)
if err != nil {
return nil, "", xerrors.Errorf("do request: %w", err)
}
@@ -508,6 +508,22 @@ func (mr *MockAgentConnMockRecorder) ReadFile(ctx, path, offset, limit any) *gom
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ReadFile", reflect.TypeOf((*MockAgentConn)(nil).ReadFile), ctx, path, offset, limit)
}
// ReadFileInRoot mocks base method.
func (m *MockAgentConn) ReadFileInRoot(ctx context.Context, root, path string, offset, limit int64) (io.ReadCloser, string, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "ReadFileInRoot", ctx, root, path, offset, limit)
ret0, _ := ret[0].(io.ReadCloser)
ret1, _ := ret[1].(string)
ret2, _ := ret[2].(error)
return ret0, ret1, ret2
}
// ReadFileInRoot indicates an expected call of ReadFileInRoot.
func (mr *MockAgentConnMockRecorder) ReadFileInRoot(ctx, root, path, offset, limit any) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ReadFileInRoot", reflect.TypeOf((*MockAgentConn)(nil).ReadFileInRoot), ctx, root, path, offset, limit)
}
// ReadFileLines mocks base method.
func (m *MockAgentConn) ReadFileLines(ctx context.Context, path string, offset, limit int64, limits workspacesdk.ReadFileLinesLimits) (workspacesdk.ReadFileLinesResponse, error) {
m.ctrl.T.Helper()
+2 -2
View File
@@ -158,8 +158,8 @@ A skill with its frontmatter missing, unparsable, not kebab-case, or not matchin
`read_skill_file` rejects absolute paths, paths containing `..`, and references to hidden files.
All paths are resolved relative to the skill directory.
It also rejects a path that resolves through a symlink to a file outside the skill directory.
Symlinks that stay inside the skill directory still work.
It also rejects a path that leaves the skill directory through a symlink.
Relative symlinks that stay inside the skill directory still work, but absolute symlinks are rejected.
## Personal skills