From 865d79f77c5187ffb78477b6bbb84bc08e62168d Mon Sep 17 00:00:00 2001 From: Erik Tate Date: Wed, 16 Oct 2024 16:51:30 -0400 Subject: [PATCH] fixing TestOSCommandPrep test by using a test user other than root because of mismatched HomeDir values when calling user.Current() --- lib/srv/exec_linux_test.go | 30 +++++++++++++++++++++++++++--- 1 file changed, 27 insertions(+), 3 deletions(-) diff --git a/lib/srv/exec_linux_test.go b/lib/srv/exec_linux_test.go index c9738d730561..d380f2094c77 100644 --- a/lib/srv/exec_linux_test.go +++ b/lib/srv/exec_linux_test.go @@ -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" ) @@ -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", @@ -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" @@ -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) {