NixOS / nixpkgs

Nix Packages collection & NixOS
MIT License
18.04k stars 14.09k forks source link

`sudo systemctl edit` uses GNU `nano` #276778

Closed becknik closed 10 months ago

becknik commented 10 months ago

Describe the bug

When trying to use the sudo systemctl edit --runtime <nixos-upgrade>.service the default editor (Neovim/ nvim in my case) set in configuration.nix and the EDITOR environment variable (also nvim) is ignored. This seems to only apply to the system systemd edit command, the user-space without sudo detects the default editor. However, my user-space uses home-manger & nixvim to manage my Neovim setup, so I don't think it's representative enough to be seen as reference...

When using sudo -E systemctl edit --runtime nixos-upgrade.service however, my default editor is recognized correctly. This also applies when using sudo -s, and then systemctl edit --runtime nixos-upgrade.service.

Steps To Reproduce

Steps to reproduce the behavior:

  1. Have the following settings related to sudo & Neovim enabled in the configurations.nix:
  security = {
    sudo = {
      enable = true;
      execWheelOnly = true;
      extraConfig =
        "Defaults timestamp_type=global\n"  # share sudo-session between terminals
        + "Defaults timestamp_timeout=15\n" # sudo timeout from 10 to 15 minutes
        + "Defaults pwfeedback\n"           # display stars when typing character
        + "Defaults insults";
    };
    please.enable = true;
  };
  programs.neovim = {
    # Enable neovim for root account, besides of nixvim for home-manager user
    enable = true;
    defaultEditor = true;
    viAlias = true;
    vimAlias = true;
  };
  1. Open up a shell and sudo systemctl edit --runtime nixos-upgrade.service
  2. Find yourself in GNU nano (which isn't even explicitly installed)

Expected behavior

The systemd service editor shows up in my nvim environemnt

Additional context

Home-managed shell config (pretty messy, sorry):

```nix { config, pkgs, ... }: { programs = { # zsh & bash integration are enabled by default hstr.enable = true; # Whether to enable Bash And Zsh shell history suggest box fzf.enable = true; bash = { enable = true; #enableVteIntegration = true; # implied by gnome }; zsh = { enable = true; #dotDir = "~/.config/zsh"; # Where zsh config files are placed; randomly creates new folders in $HOME or elsewhere envExtra = "export KEYTIMEOUT=5" # Esc key in vi mode is 0.4s by default, this sets it to 0.05s ; enableAutosuggestions = true; #enableVteIntegration = true; # implied by gnome syntaxHighlighting.enable = true; /*zsh-abbr = { # TODO zsh-abbr isn't working... enable = true; abbreviations = { # Alias which expansion after entering, like the ones in fish nrbs = "sudo nixos-rebuild --flake \"${config.home.homeDirectory}/devel/own/dotfiles.nix#dnix\" switch"; nrbt = "sudo nixos-rebuild --flake \"${config.home.homeDirectory}/devel/own/dotfiles.nix#dnix\" test"; }; };*/ historySubstringSearch.enable = true; autocd = true; # Automatically cds into a path entered = setopt autocd history = { extended = true; # Write the history file in the ":start:elapsed;command" format ignoreAllDups = true; # Delete old recorded entry if new entry is a duplicate ignoreDups = true; # Don't record an entry that was just recorded again #path = "${config.programs.zsh.dotDir}/.zhistroy"; save = 10000; # Amount of lines to save share = true; # Share history between all sessions. ignorePatterns = [ "alias" "cd" "gcsm" "ls" "la" ]; ignoreSpace = true; # Share history between all sessions. }; localVariables = { # variable definitions on top of .zshrc # Further oh-my-zsh Settings DISABLE_AUTO_TITLE = true; # automatic setting of terminal title ENABLE_CORRECTION = false; # command auto corrections COMPLETION_WAITING_DOTS = true; }; #initExtraFirst = ""; # Placed on top of .zshrc #initExtraBeforeCompInit = ''''; initExtra = # further history setup "setopt HIST_EXPIRE_DUPS_FIRST\n" # Expire duplicate entries first when trimming history. + "setopt HIST_FIND_NO_DUPS\n" # Do not display a line previously found. + "bindkey -v\n" # vim keybindings + "bindkey '^H' backward-kill-word\n" # Enables Ctrl + Del to delete a full word # vi-style navigation in menu completion + "bindkey -M menuselect 'h' vi-backward-char\n" + "bindkey -M menuselect 'k' vi-up-line-or-history\n" + "bindkey -M menuselect 'l' vi-forward-char\n" + "bindkey -M menuselect 'j' vi-down-line-or-history\n" # vi-style history navigation + "bindkey '^k' up-history\n" + "bindkey '^j' down-history\n" # bash-like history search + "bindkey '^r' history-incremental-search-backward\n" # enable bash-like feature i cant explain rn... + "unsetopt flow_control\n" + "bindkey '^q' push-line\n" # auto-complete with Ctrl + Space + "bindkey '^ ' autosuggest-accept\n" # https://github.com/ohmyzsh/ohmyzsh/tree/master/plugins/git-escape-magic + "autoload -Uz git-escape-magic\n" + "git-escape-magic\n" # bonsai + "cbonsai --multiplier 5 -m 'It takes strength to resist the dark side. Only the weak embrace it.' -p" ; oh-my-zsh = { enable = true; theme = "bullet-train"; plugins = [ "systemd" #"timer" "common-aliases" "bgnotify" "copyfile" "copypath" #"dirhistory" "alias-finder" #"catimg" #"chucknorris" #"aws" "docker" "fzf" "git" "git-auto-fetch" "git-escape-magic" "gitignore" #"rust" #"mvn" #"pyenv" #"python" #"gradle" #"hitchhiker" #"httpie" #"jsontools" #"kubectl" #"nmap" #"npm" #"microk8s" #"man" #"encode64" #"extract" "fancy-ctrl-z" #"rand-quote" "ripgrep" #"ruby" #"rsync" #"scala" "singlechar" #"ssh-agent" #"thefuck" # should conflict with the Esc^2 from sudo plugin #"transfer" # file sharing, but idk if usefull fo rme... #"urltools" "vscode" "wd" #"web-search" "zbell" "zsh-interactive-cd" "direnv" ]; custom = "${config.home.homeDirectory}/.config/oh-my-zsh/custom"; extraConfig = # oh-my-zsh extra settings for plugins # $1=exit_status, $2=command, $3=elapsed_time ''bgnotify_bell=false; bgnotify_threshold=10; function bgnotify_formatted { [ $1 -eq 0 ] && title="Holy Smokes, Batman!" || title="Holy Graf Zeppelin!" bgnotify "$title -- after $3 s" "$2"; } TIMER_PRECISION=2; TIMER_FORMAT="[%d]"; TIMER_THRESHOLD=.5; '' + # oh-my-zsh extra settings for themes: # Not set: perl nvm hg ''BULLETTRAIN_PROMPT_ORDER=("time" "status" "context" "custom" "dir" "ruby" "virtualenv" "aws" "go" "elixir" "git" "cmd_exec_time"); BULLETTRAIN_PROMPT_SEPARATE_LINE=true; BULLETTRAIN_PROMPT_ADD_NEWLINE=false; BULLETTRAIN_STATUS_EXIT_SHOW=true; BULLETTRAIN_IS_SSH_CLIENT=true; BULLETTRAIN_PROMPT_SEPARATE_LINE=true; #BULLETTRAIN_GIT_COLORIZE_DIRTY=true; '' ; }; shellAliases = { fu = "sudo"; sduo = "sudo"; nrbs = "sudo nixos-rebuild --flake \"${config.home.homeDirectory}/devel/own/dotfiles.nix#dnix\" switch"; nrbt = "sudo nixos-rebuild --flake \"${config.home.homeDirectory}/devel/own/dotfiles.nix#dnix\" test"; ngc = "sudo nix-collect-garbage"; ngckeep = "sudo nix-collect-garbage --delete-older-than"; ngcd = "sudo nix-collect-garbage -d"; ngcdu = "nix-collect-garbage -d"; }; #completionInit # "Oh-My-Zsh/Prezto calls compinit during initialization, calling it twice causes slight start up slowdown" #defaultKeymap = "viins"; # viins vicmd # ?? }; }; home.packages = [ pkgs.libnotify ]; # For bg-notify zsh plugin } ```

Notify maintainers

Systemd: @flokli @kloenk sudo: @delroth

Metadata

$ nix-info -m
 - system: `"x86_64-linux"`
 - host os: `Linux 6.6.7-xanmod1, NixOS, 23.11 (Tapir), 23.11.20231221.0b3d618`
 - multi-user?: `no`
 - sandbox: `yes`
 - version: `nix-env (Nix) 2.18.1`
 - channels(jnnk): `""`
 - channels(root): `""`
 - nixpkgs: `not found`

Add a :+1: reaction to issues you find important.

eclairevoyant commented 10 months ago

That's how sudo works, it doesn't preserve envvars unless told to.

eclairevoyant commented 10 months ago

The behaviour you see is also consistent with the manpages, see https://www.mankier.com/1/systemctl#Environment-%24SYSTEMD_EDITOR:

If neither $SYSTEMD_EDITOR nor $EDITOR nor $VISUAL are present or if it is set to an empty string or if their execution failed, systemctl will try to execute well known editors in this order: editor(1), nano(1), vim(1), vi(1).

becknik commented 10 months ago

Okay then, thanks for your (fast) answer. I'm not that familiar with sudo.

This StackExchange answer to a user with the same question has a solution. Can't we just append Defaults:root,%wheel env_keep += "EDITOR" to /etc/sudoers to enable the pass-through of the default editor?

I (as a fairly new NixOS/ Linux user) think this is something the configuration should take care of implicitly when setting a default editor. It should include cases where sudo is a prepended - it's just more convenient and surely won't break anything to expose this one domain-specific environment variable. Seems like there similar cases with the following:

$ sudo cat /etc/sudoers
# ...
# Keep terminfo database for root and %wheel.
Defaults:root,%wheel env_keep+=TERMINFO_DIRS
Defaults:root,%wheel env_keep+=TERMINFO

What do you think?

eclairevoyant commented 10 months ago

This is definitely not something that should be done by default. Even opting in is somewhat questionable IMO, as just about anything can set envvars...

becknik commented 10 months ago

Okay, then I'll close this issue. Thanks again