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

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

This commit switches to our fork of `pkg/sftp` which includes a Server
option for changing the current working directory.

Attempt to upstream: https://github.com/pkg/sftp/pull/528

Supercedes and closes #4420

Fixes #3620

* Update fork
This commit is contained in:
Mathias Fredriksson
2022-10-21 09:54:06 -05:00
committed by GitHub
parent 940201313f
commit 173b7a2c83
4 changed files with 30 additions and 5 deletions
+12 -1
View File
@@ -448,7 +448,18 @@ func (a *agent) init(ctx context.Context) {
"sftp": func(session ssh.Session) {
session.DisablePTYEmulation()
server, err := sftp.NewServer(session)
var opts []sftp.ServerOption
// 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, "get sftp working directory failed, unable to get current user", slog.Error(err))
} else {
opts = append(opts, sftp.WithServerWorkingDirectory(u.HomeDir))
}
server, err := sftp.NewServer(session, opts...)
if err != nil {
a.logger.Debug(session.Context(), "initialize sftp server", slog.Error(err))
return
+10
View File
@@ -10,6 +10,7 @@ import (
"net/netip"
"os"
"os/exec"
"os/user"
"path/filepath"
"runtime"
"strconv"
@@ -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)