feat(agent): set additional login vars, LOGNAME and SHELL (#16874)

This change stes additional env vars. This is useful for programs that
assume their presence (for instance, Zed remote relies on SHELL).

See `man login`.
This commit is contained in:
Mathias Fredriksson
2025-03-11 12:18:57 +02:00
committed by GitHub
parent 86b61ef1d8
commit 3005cb4594
2 changed files with 51 additions and 0 deletions

View File

@ -51,6 +51,7 @@ import (
"github.com/coder/coder/v2/agent/agentssh"
"github.com/coder/coder/v2/agent/agenttest"
"github.com/coder/coder/v2/agent/proto"
"github.com/coder/coder/v2/agent/usershell"
"github.com/coder/coder/v2/codersdk"
"github.com/coder/coder/v2/codersdk/agentsdk"
"github.com/coder/coder/v2/codersdk/workspacesdk"
@ -1193,6 +1194,53 @@ func TestAgent_SSHConnectionEnvVars(t *testing.T) {
}
}
func TestAgent_SSHConnectionLoginVars(t *testing.T) {
t.Parallel()
envInfo := usershell.SystemEnvInfo{}
u, err := envInfo.User()
require.NoError(t, err, "get current user")
shell, err := envInfo.Shell(u.Username)
require.NoError(t, err, "get current shell")
tests := []struct {
key string
want string
}{
{
key: "USER",
want: u.Username,
},
{
key: "LOGNAME",
want: u.Username,
},
{
key: "HOME",
want: u.HomeDir,
},
{
key: "SHELL",
want: shell,
},
}
for _, tt := range tests {
tt := tt
t.Run(tt.key, func(t *testing.T) {
t.Parallel()
session := setupSSHSession(t, agentsdk.Manifest{}, codersdk.ServiceBannerConfig{}, nil)
command := "sh -c 'echo $" + tt.key + "'"
if runtime.GOOS == "windows" {
command = "cmd.exe /c echo %" + tt.key + "%"
}
output, err := session.Output(command)
require.NoError(t, err)
require.Equal(t, tt.want, strings.TrimSpace(string(output)))
})
}
}
func TestAgent_Metadata(t *testing.T) {
t.Parallel()

View File

@ -900,7 +900,10 @@ func (s *Server) CreateCommand(ctx context.Context, script string, env []string,
cmd.Dir = homedir
}
cmd.Env = append(ei.Environ(), env...)
// Set login variables (see `man login`).
cmd.Env = append(cmd.Env, fmt.Sprintf("USER=%s", username))
cmd.Env = append(cmd.Env, fmt.Sprintf("LOGNAME=%s", username))
cmd.Env = append(cmd.Env, fmt.Sprintf("SHELL=%s", shell))
// Set SSH connection environment variables (these are also set by OpenSSH
// and thus expected to be present by SSH clients). Since the agent does