Skip to content

Commit c280bda

Browse files
committed
fix: Start SFTP sessions in user home (working directory)
This is a simple fix for #3620 by changing the working directory of `coder agent` at runtime. Since the agent doesn't write files to it's working directory, I can't think of any downsides to this method. It does not, however, exclude that we rewrite the SFTP implementation to use the modernized `RequestServer` sometime in the future. Opted to place this in agent init vs `cli/agent` because of portability of fix, tests don't usually use `cli/agent`. Fixes #3620
1 parent e8e095e commit c280bda

File tree

2 files changed

+17
-0
lines changed

2 files changed

+17
-0
lines changed

agent/agent.go

+11
Original file line numberDiff line numberDiff line change
@@ -378,6 +378,17 @@ func (a *agent) runStartupScript(ctx context.Context, script string) error {
378378
}
379379

380380
func (a *agent) init(ctx context.Context) {
381+
// Change current working directory to the users home
382+
// directory so that SFTP connections land there.
383+
// https://github.com/coder/coder/issues/3620
384+
u, err := user.Current()
385+
if err != nil {
386+
a.logger.Warn(ctx, "change working directory failed, unable to get current user", slog.Error(err))
387+
} else {
388+
err = os.Chdir(u.HomeDir)
389+
a.logger.Warn(ctx, "change working directory failed", slog.Error(err))
390+
}
391+
381392
a.logger.Info(ctx, "generating host key")
382393
// Clients' should ignore the host key when connecting.
383394
// The agent needs to authenticate with coderd to SSH,

agent/agent_test.go

+6
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import (
1010
"net/netip"
1111
"os"
1212
"os/exec"
13+
"os/user"
1314
"path/filepath"
1415
"runtime"
1516
"strconv"
@@ -212,12 +213,17 @@ func TestAgent(t *testing.T) {
212213

213214
t.Run("SFTP", func(t *testing.T) {
214215
t.Parallel()
216+
u, err := user.Current()
217+
require.NoError(t, err, "get current user")
215218
conn, _ := setupAgent(t, codersdk.WorkspaceAgentMetadata{}, 0)
216219
sshClient, err := conn.SSHClient()
217220
require.NoError(t, err)
218221
defer sshClient.Close()
219222
client, err := sftp.NewClient(sshClient)
220223
require.NoError(t, err)
224+
wd, err := client.Getwd()
225+
require.NoError(t, err, "get working directory")
226+
require.Equal(t, u.HomeDir, wd, "working directory should be home user home")
221227
tempFile := filepath.Join(t.TempDir(), "sftp")
222228
file, err := client.Create(tempFile)
223229
require.NoError(t, err)

0 commit comments

Comments
 (0)