Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions agent/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ func (a *agent) apiHandler() http.Handler {
r.Post("/api/v0/list-directory", a.HandleLS)
r.Get("/api/v0/read-file", a.HandleReadFile)
r.Post("/api/v0/write-file", a.HandleWriteFile)
r.Post("/api/v0/edit-file", a.HandleEditFile)
r.Get("/debug/logs", a.HandleHTTPDebugLogs)
r.Get("/debug/magicsock", a.HandleHTTPDebugMagicsock)
r.Get("/debug/magicsock/debug-logging/{state}", a.HandleHTTPMagicsockDebugLoggingState)
Expand Down
95 changes: 95 additions & 0 deletions agent/files.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,15 @@ import (
"strconv"
"syscall"

"github.com/icholy/replace"
"github.com/spf13/afero"
"golang.org/x/text/transform"
"golang.org/x/xerrors"

"cdr.dev/slog"
"github.com/coder/coder/v2/coderd/httpapi"
"github.com/coder/coder/v2/codersdk"
"github.com/coder/coder/v2/codersdk/workspacesdk"
)

type HTTPResponseCode = int
Expand Down Expand Up @@ -165,3 +169,94 @@ func (a *agent) writeFile(ctx context.Context, r *http.Request, path string) (HT

return 0, nil
}

func (a *agent) HandleEditFile(rw http.ResponseWriter, r *http.Request) {
ctx := r.Context()

query := r.URL.Query()
parser := httpapi.NewQueryParamParser().RequiredNotEmpty("path")
path := parser.String(query, "", "path")
parser.ErrorExcessParams(query)
if len(parser.Errors) > 0 {
httpapi.Write(ctx, rw, http.StatusBadRequest, codersdk.Response{
Message: "Query parameters have invalid values.",
Validations: parser.Errors,
})
return
}

var edits workspacesdk.FileEditRequest
if !httpapi.Read(ctx, rw, r, &edits) {
return
}

status, err := a.editFile(r.Context(), path, edits.Edits)
if err != nil {
httpapi.Write(ctx, rw, status, codersdk.Response{
Message: err.Error(),
})
return
}

httpapi.Write(ctx, rw, http.StatusOK, codersdk.Response{
Message: fmt.Sprintf("Successfully edited %q", path),
})
}

func (a *agent) editFile(ctx context.Context, path string, edits []workspacesdk.FileEdit) (int, error) {
if !filepath.IsAbs(path) {
return http.StatusBadRequest, xerrors.Errorf("file path must be absolute: %q", path)
}

if len(edits) == 0 {
return http.StatusBadRequest, xerrors.New("must specify at least one edit")
}

f, err := a.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
}
defer f.Close()

stat, err := f.Stat()
if err != nil {
return http.StatusInternalServerError, err
}

if stat.IsDir() {
return http.StatusBadRequest, xerrors.Errorf("open %s: not a file", path)
}

transforms := make([]transform.Transformer, len(edits))
for i, edit := range edits {
transforms[i] = replace.String(edit.Search, edit.Replace)
}

tmpfile, err := afero.TempFile(a.filesystem, "", filepath.Base(path))
if err != nil {
return http.StatusInternalServerError, err
}
defer tmpfile.Close()

_, err = io.Copy(tmpfile, replace.Chain(f, transforms...))
if err != nil {
if rerr := a.filesystem.Remove(tmpfile.Name()); rerr != nil {
a.logger.Warn(ctx, "unable to clean up temp file", slog.Error(rerr))
}
return http.StatusInternalServerError, xerrors.Errorf("edit %s: %w", path, err)
}

err = a.filesystem.Rename(tmpfile.Name(), path)
if err != nil {
return http.StatusInternalServerError, err
}

return 0, nil
}
183 changes: 183 additions & 0 deletions agent/files_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,13 @@ import (

"github.com/spf13/afero"
"github.com/stretchr/testify/require"
"golang.org/x/xerrors"

"github.com/coder/coder/v2/agent"
"github.com/coder/coder/v2/agent/agenttest"
"github.com/coder/coder/v2/coderd/coderdtest"
"github.com/coder/coder/v2/codersdk/agentsdk"
"github.com/coder/coder/v2/codersdk/workspacesdk"
"github.com/coder/coder/v2/testutil"
)

Expand Down Expand Up @@ -91,6 +93,13 @@ func (fs *testFs) MkdirAll(name string, mode os.FileMode) error {
return fs.Fs.MkdirAll(name, mode)
}

func (fs *testFs) Rename(oldName, newName string) error {
if err := fs.intercept("rename", newName); err != nil {
return err
}
return fs.Fs.Rename(oldName, newName)
}

func TestReadFile(t *testing.T) {
t.Parallel()

Expand Down Expand Up @@ -376,3 +385,177 @@ func TestWriteFile(t *testing.T) {
})
}
}

func TestEditFile(t *testing.T) {
t.Parallel()

tmpdir := os.TempDir()
noPermsFilePath := filepath.Join(tmpdir, "no-perms-file")
failRenameFilePath := filepath.Join(tmpdir, "fail-rename")
//nolint:dogsled
conn, _, _, fs, _ := setupAgent(t, agentsdk.Manifest{}, 0, func(_ *agenttest.Client, opts *agent.Options) {
opts.Filesystem = newTestFs(opts.Filesystem, func(call, file string) error {
if file == noPermsFilePath {
return os.ErrPermission
} else if file == failRenameFilePath && call == "rename" {
return xerrors.New("rename failed")
}
return nil
})
})

dirPath := filepath.Join(tmpdir, "directory")
err := fs.MkdirAll(dirPath, 0o755)
require.NoError(t, err)

tests := []struct {
name string
path string
contents string
edits []workspacesdk.FileEdit
expected string
errCode int
error string
}{
{
name: "NoPath",
errCode: http.StatusBadRequest,
error: "\"path\" is required",
},
{
name: "RelativePath",
path: "./relative",
errCode: http.StatusBadRequest,
error: "file path must be absolute",
},
{
name: "RelativePath",
path: "also-relative",
errCode: http.StatusBadRequest,
error: "file path must be absolute",
},
{
name: "NoEdits",
path: filepath.Join(tmpdir, "no-edits"),
contents: "foo bar",
errCode: http.StatusBadRequest,
error: "must specify at least one edit",
},
{
name: "NonExistent",
path: filepath.Join(tmpdir, "does-not-exist"),
edits: []workspacesdk.FileEdit{
{
Search: "foo",
Replace: "bar",
},
},
errCode: http.StatusNotFound,
error: "file does not exist",
},
{
name: "IsDir",
path: dirPath,
edits: []workspacesdk.FileEdit{
{
Search: "foo",
Replace: "bar",
},
},
errCode: http.StatusBadRequest,
error: "not a file",
},
{
name: "NoPermissions",
path: noPermsFilePath,
edits: []workspacesdk.FileEdit{
{
Search: "foo",
Replace: "bar",
},
},
errCode: http.StatusForbidden,
error: "permission denied",
},
{
name: "FailRename",
path: failRenameFilePath,
contents: "foo bar",
edits: []workspacesdk.FileEdit{
{
Search: "foo",
Replace: "bar",
},
},
errCode: http.StatusInternalServerError,
error: "rename failed",
},
{
name: "Edit1",
path: filepath.Join(tmpdir, "edit1"),
contents: "foo bar",
edits: []workspacesdk.FileEdit{
{
Search: "foo",
Replace: "bar",
},
},
expected: "bar bar",
},
{
name: "EditEdit", // Edits affect previous edits.
path: filepath.Join(tmpdir, "edit-edit"),
contents: "foo bar",
edits: []workspacesdk.FileEdit{
{
Search: "foo",
Replace: "bar",
},
{
Search: "bar",
Replace: "qux",
},
},
expected: "qux qux",
},
{
name: "Multiline",
path: filepath.Join(tmpdir, "multiline"),
contents: "foo\nbar\nbaz\nqux",
edits: []workspacesdk.FileEdit{
{
Search: "bar\nbaz",
Replace: "frob",
},
},
expected: "foo\nfrob\nqux",
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()

ctx, cancel := context.WithTimeout(context.Background(), testutil.WaitLong)
defer cancel()

if tt.contents != "" {
err := afero.WriteFile(fs, tt.path, []byte(tt.contents), 0o644)
require.NoError(t, err)
}

err := conn.EditFile(ctx, tt.path, workspacesdk.FileEditRequest{Edits: tt.edits})
if tt.errCode != 0 {
require.Error(t, err)
cerr := coderdtest.SDKError(t, err)
require.Contains(t, cerr.Error(), tt.error)
require.Equal(t, tt.errCode, cerr.StatusCode())
} else {
require.NoError(t, err)
b, err := afero.ReadFile(fs, tt.path)
require.NoError(t, err)
require.Equal(t, tt.expected, string(b))
}
})
}
}
Loading
Loading