Nix: Nix commands behave unexpectedly under sudo on multi-user macOS (due to HOME being preserved)

Created on 9 Jan 2021  Â·  2Comments  Â·  Source: NixOS/nix

Describe the bug

The default configuration of /etc/sudoers on macOS includes

Defaults        env_keep += "HOME MAIL"

This means that the HOME env var will not be set by sudo unless the -H or -i flags are given.

The result of this is commands like sudo nix-channel --update will update the user's channels instead of root's channels, sudo nix-env -q will list all packages from the user's profile instead of the default profile, and sudo nix-env -i … will install into the user's profile instead of the default profile.

Given that we're probably getting rid of single-user install on macOS (see https://github.com/NixOS/nix/pull/4289), having multi-user have good UX out of the box is important, especially since nearly all of the documentation assumes Linux where the default /etc/sudoers does not preserve HOME.

I think the right thing to do here is to update all the code that looks for paths relative to $HOME and have them read the users's home dir instead. This already appears to be the behavior if I clear HOME (e.g. sudo HOME= nix-channel --list gives me the right output). If there is some valid use-case for respecting the HOME var outside of sudo, Nix could optionally do this only when e.g. SUDO_USER is set (or, more conservatively, when HOME is set to the home dir of SUDO_USER).

Steps To Reproduce

  1. sudo nix-env -q on macOS, or sudo --preserve-env=HOME nix-env -q on any platform.

Expected behavior

It should behave identically to sudo -H nix-env -q.

nix-env --version output

nix-env (Nix) 2.3.8

bug

Most helpful comment

getHome uses getpwuid_r to get the effective user home directory if HOME is unset. I think this works consistently everywhere. Maybe we should just not look at a HOME at all?

All 2 comments

getHome uses getpwuid_r to get the effective user home directory if HOME is unset. I think this works consistently everywhere. Maybe we should just not look at a HOME at all?

I don’t know if there’s any use-case for explicitly setting HOME to a separate path in order to have Nix operate on that dir, but I kind of doubt it. Just not looking at HOME at all seems like the right call.

Was this page helpful?
0 / 5 - 0 ratings