Skip to content

Commit add4696

Browse files
committed
cvd_refresh_groups: Use getpwuid(getuid()) instead of getlogin_r
cvd_refresh_groups was using getlogin_r to determine the username for initgroups. However, when running under sudo -u <user>, getlogin_r still returns the original login user of the terminal, not the target user of sudo. The test scripts used by our Kokoro and GitHub actions workflows create a test user and use `sudo -u` to run commands as that test user. This caused initgroups to be called with the wrong user, refreshing the process groups to those of the original user (which typically lack cvdnetwork group), leading to assemble_cvd failing with "Operation not permitted" when trying to set group ownership of directories. Using getpwuid(getuid()) correctly resolves the username of the running user based on the real UID, which is preserved under sudo. Assisted-by: Jetski <jetski@google.com> Bug: b/510930737
1 parent a070843 commit add4696

1 file changed

Lines changed: 7 additions & 5 deletions

File tree

base/cvd/cuttlefish/host/commands/refresh_groups/cvd_refresh_groups.cc

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -14,8 +14,9 @@
1414
// limitations under the License.
1515

1616
#include <grp.h>
17-
#include <limits.h>
17+
#include <pwd.h>
1818
#include <stdio.h>
19+
#include <sys/types.h>
1920
#include <unistd.h>
2021

2122
/**
@@ -40,12 +41,13 @@ int main(int argc, char** argv) {
4041
"Usage: cvd_refresh_groups <file> <argv[0]> [argv<N> ...]\n");
4142
return 1;
4243
}
43-
char user[LOGIN_NAME_MAX];
44-
if (getlogin_r(user, sizeof(user))) {
45-
perror("getlogin_r failed");
44+
uid_t uid = getuid();
45+
struct passwd* pw = getpwuid(uid);
46+
if (!pw) {
47+
perror("getpwuid failed");
4648
return 1;
4749
}
48-
if (initgroups(user, getgid())) {
50+
if (initgroups(pw->pw_name, getgid())) {
4951
perror("initgroups failed");
5052
return 1;
5153
}

0 commit comments

Comments
 (0)