Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Avoid unnecessary user switching #15

Merged
merged 1 commit into from
Jan 26, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 9 additions & 4 deletions ensureuserisroot.go → checkuser.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,14 +21,19 @@ import (
"os/user"
)

func ensureUserIsRoot() error {
user, err := user.Current()
func checkUser(username string) error {
cur, err := user.Current()
if err != nil {
return err
}

if user.Uid != "0" {
return fmt.Errorf("must be run as root")
other, err := user.Lookup(username)
if err != nil {
return err
}

if cur.Uid != other.Uid {
return fmt.Errorf("must be run as %s", username)
}

return nil
Expand Down
7 changes: 6 additions & 1 deletion instance.go
Original file line number Diff line number Diff line change
Expand Up @@ -385,7 +385,12 @@ func (i *Instance) ExecuteAsManager() error {
// This command only functions if the calling program is running as root.
// It returns any error encountered.
func (i *Instance) ExecuteAsUser(execUser string) error {
if err := ensureUserIsRoot(); err != nil {
// no need to switch users if we're already who we want to be
if err := checkUser(execUser); err == nil {
return nil
}

if err := checkUser("root"); err != nil {
return err
}

Expand Down
Loading