mirror of
https://github.com/coder/coder.git
synced 2026-09-21 20:51:01 +08:00
agentssh's CommandEnv, sftpHandler, and agentproc each resolved the session working directory on their own and had drifted: sftpHandler used the configured directory without checking it exists and bypassed the injected EnvInfoer, while the others stat-checked and fell back to home. Home and shell lookups could also skip the EnvInfoer seam through the exported usershell.HomeDir and Get. Resolve through a single usershell.ResolveWorkingDirectory and confine host home and shell lookups to usershell, so SSH sessions, the process API, and tests can no longer diverge and the injected environment is always honored. This also fixes SFTP landing in a configured directory that no longer exists. Refs coder/coder#26099
37 lines
901 B
Go
37 lines
901 B
Go
//go:build !windows && !darwin
|
|
// +build !windows,!darwin
|
|
|
|
package usershell
|
|
|
|
import (
|
|
"os"
|
|
"strings"
|
|
|
|
"golang.org/x/xerrors"
|
|
)
|
|
|
|
// get resolves the user's shell from /etc/passwd, falling back to
|
|
// $SHELL. It backs SystemEnvInfo.Shell. Callers resolve the shell
|
|
// through an EnvInfoer.
|
|
func get(username string) (string, error) {
|
|
contents, err := os.ReadFile("/etc/passwd")
|
|
if err != nil {
|
|
return "", xerrors.Errorf("read /etc/passwd: %w", err)
|
|
}
|
|
lines := strings.Split(string(contents), "\n")
|
|
for _, line := range lines {
|
|
if !strings.HasPrefix(line, username+":") {
|
|
continue
|
|
}
|
|
parts := strings.Split(line, ":")
|
|
if len(parts) < 7 {
|
|
return "", xerrors.Errorf("malformed user entry: %q", line)
|
|
}
|
|
return parts[6], nil
|
|
}
|
|
if s := os.Getenv("SHELL"); s != "" {
|
|
return s, nil
|
|
}
|
|
return "", xerrors.Errorf("shell for user %q not found in /etc/passwd or $SHELL", username)
|
|
}
|