Skip to content

Commit

Permalink
fix: cmd failure if user is not sudoer (#1663)
Browse files Browse the repository at this point in the history
Signed-off-by: slayerjain <shubhamkjain@outlook.com>
  • Loading branch information
slayerjain committed Mar 7, 2024
1 parent faa19e7 commit ec380c0
Showing 1 changed file with 3 additions and 40 deletions.
43 changes: 3 additions & 40 deletions pkg/hooks/launch.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package hooks

import (
"bytes"
"context"
"errors"
"fmt"
Expand Down Expand Up @@ -476,12 +475,12 @@ func (h *Hook) processDockerEnv(appCmd, appContainer, appNetwork string, buildDe
func (h *Hook) runApp(appCmd string, isUnitTestIntegration bool) error {
// Create a new command with your appCmd'
username := os.Getenv("SUDO_USER")
var cmd *exec.Cmd
cmd := exec.Command("sh", "-c", appCmd)
if username != "" {
// print all environment variables
h.logger.Debug("env inherited from the cmd", zap.Any("env", os.Environ()))
// Run the command as the user who invoked sudo to preserve the user environment variables and PATH
cmd = exec.Command("sudo", "-E", "-u", os.Getenv("SUDO_USER"), "env", "PATH="+os.Getenv("PATH"), "sh", "-c", appCmd)
} else {
cmd = exec.Command("sh", "-c", appCmd)
}
cmd.SysProcAttr = &syscall.SysProcAttr{
Setpgid: true,
Expand All @@ -492,42 +491,6 @@ func (h *Hook) runApp(appCmd string, isUnitTestIntegration bool) error {
cmd.Stderr = os.Stderr
h.userAppCmd = cmd

// Run the app as the user who invoked sudo
if username != "" {
uidCmd := exec.Command("id", "-u", username)
gidCmd := exec.Command("id", "-g", username)

var uidOut, gidOut bytes.Buffer
uidCmd.Stdout = &uidOut
gidCmd.Stdout = &gidOut

err := uidCmd.Run()
if err != nil {
return err
}

err = gidCmd.Run()
if err != nil {
return err
}

uidStr := strings.TrimSpace(uidOut.String())
gidStr := strings.TrimSpace(gidOut.String())

uid, err := strconv.ParseUint(uidStr, 10, 32)
if err != nil {
return err
}

gid, err := strconv.ParseUint(gidStr, 10, 32)
if err != nil {
return err
}

// Switch the user
cmd.SysProcAttr.Credential = &syscall.Credential{Uid: uint32(uid), Gid: uint32(gid)}
}

h.logger.Debug("", zap.Any("executing cmd", cmd.String()))

err := cmd.Run()
Expand Down

0 comments on commit ec380c0

Please sign in to comment.