Subject: bug#68074: eshell sudo/doas does not work for aliases

From: Alfonso Sanchez-Beato <[email-masked]>
Date: Wed, 27 Dec 2023 21:12:26 +0000 (UTC)

sudo/doas does not give the expected permissions when using an eshell alias:

When no alias has been defined:

~ $ which cp
eshell/cp is a native-compiled Lisp function in ‘em-unix.el’.
~ $ touch test
~ $ cp test /boot/efi/
Opening output file: Permission denied, /boot/efi/test
~ $ sudo cp test /boot/efi/
~ $ echo $?
0

But after defining the alias:

~ $ alias cp '*cp $*'
~ $ which cp
cp is an alias, defined as "*cp $*"
~ $ sudo cp test /boot/efi/
/usr/bin/cp: cannot stat '/boot/efi/test': Permission denied

I have attached a patch with a possible fix.
From 25e12e5912e2ef5bcab359eca5a10e973cb35937 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Alfonso=20S=C3=A1nchez-Beato?=
 <[email-masked]>
Date: Wed, 27 Dec 2023 21:50:29 +0100
Subject: [PATCH] * lisp/eshell/em-alias.el (eshell-maybe-replace-by-alias):
 Fix using tramp with alias.

Previously calls that involved using tramp with an alias where not working as
expected because the default-directory set in em-tramp.el was forgotten after
eshell-replace-command was thrown in eshell-maybe-replace-by-alias.
---
 lisp/eshell/em-alias.el | 13 +++++++++----
 1 file changed, 9 insertions(+), 4 deletions(-)

diff --git a/lisp/eshell/em-alias.el b/lisp/eshell/em-alias.el
index 841982c3425..7fff920ed7b 100644
--- a/lisp/eshell/em-alias.el
+++ b/lisp/eshell/em-alias.el
@@ -222,12 +222,17 @@ This is useful after manually editing the contents of the file."
 	       (member command eshell-prevent-alias-expansion))
     (let ((alias (eshell-lookup-alias command)))
       (if alias
-	  (throw 'eshell-replace-command
-		 `(let ((eshell-command-name ',eshell-last-command-name)
+          (let ((vars `((eshell-command-name ',eshell-last-command-name)
                         (eshell-command-arguments ',eshell-last-arguments)
                         (eshell-prevent-alias-expansion
-                         ',(cons command eshell-prevent-alias-expansion)))
-                    ,(eshell-parse-command (nth 1 alias))))))))
+                         ',(cons command eshell-prevent-alias-expansion)))))
+            ;; Set default-directory as it might have been set by sudo/doas, unless
+            ;; we want to change it permanently.
+            (if (not (string-prefix-p (car (split-string (nth 1 alias) " ")) "cd"))
+                (push `(default-directory ',default-directory) vars))
+	    (throw 'eshell-replace-command
+		   `(let ,vars
+                      ,(eshell-parse-command (nth 1 alias)))))))))
 
 (defun eshell-alias-completions (name)
   "Find all possible completions for NAME.
-- 
2.34.1