Skip to content

fix: Start SFTP sessions in user home (working directory) #4420

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 3 commits into from
Closed
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
13 changes: 13 additions & 0 deletions agent/agent.go
Original file line number Diff line number Diff line change
Expand Up @@ -378,6 +378,19 @@ func (a *agent) runStartupScript(ctx context.Context, script string) error {
}

func (a *agent) init(ctx context.Context) {
// Change current working directory to the users home
// directory so that SFTP connections land there.
// https://github.com/coder/coder/issues/3620
u, err := user.Current()
if err != nil {
a.logger.Warn(ctx, "change working directory failed, unable to get current user", slog.Error(err))
} else {
err = os.Chdir(u.HomeDir)
if err != nil {
a.logger.Warn(ctx, "change working directory failed", slog.Error(err))
}
}

a.logger.Info(ctx, "generating host key")
// Clients' should ignore the host key when connecting.
// The agent needs to authenticate with coderd to SSH,
Expand Down
10 changes: 10 additions & 0 deletions agent/agent_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import (
"net/netip"
"os"
"os/exec"
"os/user"
"path/filepath"
"runtime"
"strconv"
Expand Down Expand Up @@ -212,12 +213,21 @@ func TestAgent(t *testing.T) {

t.Run("SFTP", func(t *testing.T) {
t.Parallel()
u, err := user.Current()
require.NoError(t, err, "get current user")
home := u.HomeDir
if runtime.GOOS == "windows" {
home = "/" + strings.ReplaceAll(home, "\\", "/")
}
conn, _ := setupAgent(t, codersdk.WorkspaceAgentMetadata{}, 0)
sshClient, err := conn.SSHClient()
require.NoError(t, err)
defer sshClient.Close()
client, err := sftp.NewClient(sshClient)
require.NoError(t, err)
wd, err := client.Getwd()
require.NoError(t, err, "get working directory")
require.Equal(t, home, wd, "working directory should be home user home")
tempFile := filepath.Join(t.TempDir(), "sftp")
file, err := client.Create(tempFile)
require.NoError(t, err)
Expand Down