From 464df6adf34fbeca3100919ec798d214acdd3ff4 Mon Sep 17 00:00:00 2001 From: mustard Date: Tue, 22 Mar 2022 17:14:56 +0000 Subject: [PATCH] [supervisor] add sudo permission to custom images --- components/supervisor/pkg/supervisor/user.go | 37 ++++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/components/supervisor/pkg/supervisor/user.go b/components/supervisor/pkg/supervisor/user.go index 21a9f9c85226e8..087b7a9296be23 100644 --- a/components/supervisor/pkg/supervisor/user.go +++ b/components/supervisor/pkg/supervisor/user.go @@ -5,8 +5,12 @@ package supervisor import ( + "fmt" + "io/ioutil" + "os" "os/exec" "os/user" + "regexp" "strconv" "strings" @@ -42,6 +46,9 @@ func AddGitpodUserIfNotExists() error { return err } } + if err := addSudoer(gitpodGroupName); err != nil { + log.WithError(err).Error("add gitpod sudoers") + } targetUser := &user.User{ Uid: strconv.Itoa(gitpodUID), @@ -169,6 +176,36 @@ func addUser(opts *user.User) error { return nil } +// addSudoer check and add group to /etc/sudoers +func addSudoer(group string) error { + if group == "" { + return xerrors.Errorf("group name should not be empty") + } + sudoersPath := "/etc/sudoers" + finfo, err := os.Stat(sudoersPath) + if err != nil { + return err + } + b, err := ioutil.ReadFile(sudoersPath) + if err != nil { + return err + } + gitpodSudoer := []byte(fmt.Sprintf("%%%s ALL=NOPASSWD:ALL", group)) + // Line starts with "%gitpod ..." + re := regexp.MustCompile(fmt.Sprintf("(?m)^%%%s\\s+.*?$", group)) + if len(re.FindStringIndex(string(b))) > 0 { + nb := re.ReplaceAll(b, gitpodSudoer) + return os.WriteFile(sudoersPath, nb, finfo.Mode().Perm()) + } + file, err := os.OpenFile(sudoersPath, os.O_APPEND|os.O_WRONLY, os.ModeAppend) + if err != nil { + return err + } + defer file.Close() + _, err = file.Write(append([]byte("\n"), gitpodSudoer...)) + return err +} + func determineCmdFlavour(args []string) bool { var flags []string for _, a := range args {