From 12acd710bec64660e6d4c27ec08d2248d8eb26cb Mon Sep 17 00:00:00 2001 From: Klemens Nanni Date: Tue, 12 Nov 2024 02:36:28 +0300 Subject: [PATCH] Omit privileged setgroups(2) call to test set[ug]id(2) to same user Every user may change its user/group ID to the current one. With an ugly hack, skip the superuser-only part of chuser() to exercise this rest of the code path in regular tests. --- cmd/yggdrasil/chuser_unix.go | 8 +++++--- cmd/yggdrasil/chuser_unix_test.go | 10 +++------- 2 files changed, 8 insertions(+), 10 deletions(-) diff --git a/cmd/yggdrasil/chuser_unix.go b/cmd/yggdrasil/chuser_unix.go index fc3e5c2c..02a56d61 100644 --- a/cmd/yggdrasil/chuser_unix.go +++ b/cmd/yggdrasil/chuser_unix.go @@ -12,7 +12,7 @@ import ( "golang.org/x/sys/unix" ) -func chuser(input string) error { +func chuser(input string, skipSetgroupsForTests ...any) error { givenUser, givenGroup, _ := strings.Cut(input, ":") var ( @@ -43,8 +43,10 @@ func chuser(input string) error { gid, _ = strconv.Atoi(usr.Gid) } - if err := unix.Setgroups([]int{gid}); err != nil { - return fmt.Errorf("setgroups: %d: %v", gid, err) + if len(skipSetgroupsForTests) == 0 { + if err := unix.Setgroups([]int{gid}); err != nil { + return fmt.Errorf("setgroups: %d: %v", gid, err) + } } if err := unix.Setgid(gid); err != nil { return fmt.Errorf("setgid: %d: %v", gid, err) diff --git a/cmd/yggdrasil/chuser_unix_test.go b/cmd/yggdrasil/chuser_unix_test.go index ad2e3517..814d988e 100644 --- a/cmd/yggdrasil/chuser_unix_test.go +++ b/cmd/yggdrasil/chuser_unix_test.go @@ -44,18 +44,14 @@ func TestInvalidUserid (t *testing.T) { } } -// Change to the current user by ID. -func TestCurrentUserid (t *testing.T) { +// Change to the current user by username and group ID. +func TestCurrentUser (t *testing.T) { usr, err := user.Current() if err != nil { t.Fatal(err) } - if usr.Uid != "0" { - t.Skip("setgroups(2): Only the superuser may set new groups.") - } - - if err = chuser(usr.Uid); err != nil { + if err = chuser(usr.Username + ":" + usr.Gid, true /* skipSetGroupsForTests */); err != nil { t.Fatal(err) } }