From 0cbdae412405a9cccf7209931e7f882c19cf1a26 Mon Sep 17 00:00:00 2001 From: Thiago Kenji Okada Date: Sun, 13 Jul 2025 14:42:20 +0100 Subject: [PATCH] nixos-rebuild-ng: error if --upgrade/--upgrade-all is called without --sudo/root --- .../nixos-rebuild-ng/src/nixos_rebuild/nix.py | 6 +++++ .../ni/nixos-rebuild-ng/src/tests/test_nix.py | 23 +++++++++++++++---- 2 files changed, 24 insertions(+), 5 deletions(-) diff --git a/pkgs/by-name/ni/nixos-rebuild-ng/src/nixos_rebuild/nix.py b/pkgs/by-name/ni/nixos-rebuild-ng/src/nixos_rebuild/nix.py index ed989e1b4e24..9a2d6a131580 100644 --- a/pkgs/by-name/ni/nixos-rebuild-ng/src/nixos_rebuild/nix.py +++ b/pkgs/by-name/ni/nixos-rebuild-ng/src/nixos_rebuild/nix.py @@ -699,6 +699,12 @@ def upgrade_channels(all_channels: bool = False, sudo: bool = False) -> None: It will either upgrade just the `nixos` channel (including any channel that has a `.update-on-nixos-rebuild` file) or all. """ + if not sudo and os.geteuid() != 0: + raise NixOSRebuildError( + "if you pass the '--upgrade' or '--upgrade-all' flag, you must " + "also pass '--sudo' or run the command as root (e.g., with sudo)" + ) + for channel_path in Path("/nix/var/nix/profiles/per-user/root/channels/").glob("*"): if channel_path.is_dir() and ( all_channels diff --git a/pkgs/by-name/ni/nixos-rebuild-ng/src/tests/test_nix.py b/pkgs/by-name/ni/nixos-rebuild-ng/src/tests/test_nix.py index 8078cd2b36c0..9833aade3b99 100644 --- a/pkgs/by-name/ni/nixos-rebuild-ng/src/tests/test_nix.py +++ b/pkgs/by-name/ni/nixos-rebuild-ng/src/tests/test_nix.py @@ -836,15 +836,28 @@ def test_switch_to_configuration_with_systemd_run( ], ) @patch("pathlib.Path.is_dir", autospec=True, return_value=True) -def test_upgrade_channels(mock_is_dir: Mock, mock_glob: Mock) -> None: - with patch(get_qualified_name(n.run_wrapper, n), autospec=True) as mock_run: - n.upgrade_channels(all_channels=False, sudo=True) +@patch("os.geteuid", autospec=True, return_value=1000) +@patch(get_qualified_name(n.run_wrapper, n), autospec=True) +def test_upgrade_channels( + mock_run: Mock, + mock_geteuid: Mock, + mock_is_dir: Mock, + mock_glob: Mock, +) -> None: + with pytest.raises(m.NixOSRebuildError) as e: + n.upgrade_channels(all_channels=False, sudo=False) + assert str(e.value) == ( + "error: if you pass the '--upgrade' or '--upgrade-all' flag, you must " + "also pass '--sudo' or run the command as root (e.g., with sudo)" + ) + + n.upgrade_channels(all_channels=False, sudo=True) mock_run.assert_called_once_with( ["nix-channel", "--update", "nixos"], check=False, sudo=True ) - with patch(get_qualified_name(n.run_wrapper, n), autospec=True) as mock_run: - n.upgrade_channels(all_channels=True, sudo=False) + mock_geteuid.return_value = 0 + n.upgrade_channels(all_channels=True, sudo=False) mock_run.assert_has_calls( [ call(["nix-channel", "--update", "nixos"], check=False, sudo=False),