Skip to content

Commit

Permalink
fixing TestOSCommandPrep test by using a test user other than root
Browse files Browse the repository at this point in the history
because of mismatched HomeDir values when calling user.Current()
  • Loading branch information
eriktate committed Oct 16, 2024
1 parent 66351ed commit 865d79f
Showing 1 changed file with 27 additions and 3 deletions.
30 changes: 27 additions & 3 deletions lib/srv/exec_linux_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,11 +26,13 @@ import (
"os"
"os/exec"
"os/user"
"path/filepath"
"strconv"
"syscall"
"testing"
"time"

"github.com/gravitational/teleport/lib/utils/host"
"github.com/gravitational/trace"
"github.com/stretchr/testify/require"
)
Expand All @@ -39,14 +41,32 @@ func TestOSCommandPrep(t *testing.T) {
srv := newMockServer(t)
scx := newExecServerContext(t, srv)

usr, err := user.Current()
tempHome := t.TempDir()
require.NoError(t, os.Chmod(filepath.Dir(tempHome), 0777))

username := "test-os-command-prep"
scx.Identity.Login = username
_, err := host.UserAdd(username, nil, host.UserOpts{
Home: tempHome,
})
require.NoError(t, err)
t.Cleanup(func() {
_, err := host.UserDel(username)
require.NoError(t, err)
})

usr, err := user.Lookup(username)
require.NoError(t, err)

uid, err := strconv.Atoi(usr.Uid)
require.NoError(t, err)

require.NoError(t, os.Chown(tempHome, uid, -1))
expectedEnv := []string{
"LANG=en_US.UTF-8",
getDefaultEnvPath(strconv.Itoa(os.Geteuid()), defaultLoginDefsPath),
getDefaultEnvPath(usr.Uid, defaultLoginDefsPath),
fmt.Sprintf("HOME=%s", usr.HomeDir),
fmt.Sprintf("USER=%s", usr.Username),
fmt.Sprintf("USER=%s", username),
"SHELL=/bin/sh",
"SSH_CLIENT=10.0.0.5 4817 3022",
"SSH_CONNECTION=10.0.0.5 4817 127.0.0.1 3022",
Expand Down Expand Up @@ -105,6 +125,7 @@ func TestOSCommandPrep(t *testing.T) {

// Missing home directory - HOME should still be set to the given
// home dir, but the command should set it's CWD to root instead.
changeHomeDir(t, username, "/wrong/place")
usr.HomeDir = "/wrong/place"
root := string(os.PathSeparator)
expectedEnv[2] = "HOME=/wrong/place"
Expand All @@ -113,6 +134,9 @@ func TestOSCommandPrep(t *testing.T) {

require.Equal(t, root, cmd.Dir)
require.Equal(t, expectedEnv, cmd.Env)

// change homedir back so user deletion doesn't fail
changeHomeDir(t, username, tempHome)
}

func TestConfigureCommand(t *testing.T) {
Expand Down

0 comments on commit 865d79f

Please sign in to comment.