Skip to content

Commit

Permalink
Allow sudofn injection into connection (#227)
Browse files Browse the repository at this point in the history
- allow connection objects to have a sudofn injected
- if sudofn is set, then Connect won't try to detect it

Signed-off-by: James Nesbitt <jnesbitt@mirantis.com>
  • Loading branch information
james-nesbitt authored Nov 8, 2024
1 parent dc14b8a commit b571b8a
Showing 1 changed file with 13 additions and 5 deletions.
18 changes: 13 additions & 5 deletions connection.go
Original file line number Diff line number Diff line change
Expand Up @@ -241,11 +241,19 @@ func (c *Connection) Connect() error {
c.OSVersion = &o
}

c.configureSudo()
if c.sudofunc == nil {
c.discoverSudo()
}

return nil
}

// SetSudofn inject a sudofn into the connection before Connect()
// @NOTE this will avoid sudo detection if done before Connect()
func (c *Connection) SetSudofn(f func(string) string) {
c.sudofunc = f
}

func sudoNoop(cmd string) string {
return cmd
}
Expand Down Expand Up @@ -287,21 +295,21 @@ func sudoWindows(cmd string) string {
return cmd
}

func (c *Connection) configureSudo() {
func (c *Connection) discoverSudo() {
if !c.IsWindows() {
if c.Exec(`[ "$(id -u)" = 0 ]`) == nil {
// user is already root
c.sudofunc = sudoNoop
c.SetSudofn(sudoNoop)
return
}
if c.Exec(`sudo -n -l`) == nil {
// user has passwordless sudo
c.sudofunc = sudoSudo
c.SetSudofn(sudoSudo)
return
}
if c.Exec(`doas -n -- "${SHELL-sh}" -c true`) == nil {
// user has passwordless doas
c.sudofunc = sudoDoas
c.SetSudofn(sudoDoas)
}
return
}
Expand Down

0 comments on commit b571b8a

Please sign in to comment.