(1) "user's cached auth is not used" – It's probably per tty (
man 5 sudoers, see timestamp_type) and the sudo vim FILENAME has probably provided a separate tty (man 5 sudoers, use_pty). (2) In a heredoc stdin is from the heredoc, hence "… not from a terminal" printed by the vim run by sudo visudo. </dev/tty sudo visudo >/dev/tty 2>&1 may be helpful. More so, if you manage to redirect to the original tty. (3) "the temp file still belongs to root" – In sudo -e the editor runs as the invoking user; try something like sudo -u USERNAME sudo -e "$1" (note: I have not tested).