askpass.rs

  1mod encrypted_password;
  2
  3pub use encrypted_password::{EncryptedPassword, IKnowWhatIAmDoingAndIHaveReadTheDocs};
  4
  5use net::async_net::UnixListener;
  6use smol::lock::Mutex;
  7use util::fs::make_file_executable;
  8
  9use std::ffi::OsStr;
 10use std::ops::ControlFlow;
 11use std::sync::Arc;
 12use std::sync::OnceLock;
 13use std::time::Duration;
 14
 15use anyhow::{Context as _, Result};
 16use futures::channel::{mpsc, oneshot};
 17use futures::{
 18    AsyncBufReadExt as _, AsyncWriteExt as _, FutureExt as _, SinkExt, StreamExt, io::BufReader,
 19    select_biased,
 20};
 21use gpui::{AsyncApp, BackgroundExecutor, Task};
 22use smol::fs;
 23use util::{ResultExt as _, debug_panic, maybe, paths::PathExt, shell::ShellKind};
 24
 25/// Path to the program used for askpass
 26///
 27/// On Unix and remote servers, this defaults to the current executable
 28/// On Windows, this is set to the CLI variant of zed
 29static ASKPASS_PROGRAM: OnceLock<std::path::PathBuf> = OnceLock::new();
 30
 31#[derive(PartialEq, Eq)]
 32pub enum AskPassResult {
 33    CancelledByUser,
 34    Timedout,
 35}
 36
 37pub struct AskPassDelegate {
 38    tx: mpsc::UnboundedSender<(String, oneshot::Sender<EncryptedPassword>)>,
 39    executor: BackgroundExecutor,
 40    _task: Task<()>,
 41}
 42
 43impl AskPassDelegate {
 44    pub fn new(
 45        cx: &mut AsyncApp,
 46        password_prompt: impl Fn(String, oneshot::Sender<EncryptedPassword>, &mut AsyncApp)
 47        + Send
 48        + Sync
 49        + 'static,
 50    ) -> Self {
 51        let (tx, mut rx) = mpsc::unbounded::<(String, oneshot::Sender<_>)>();
 52        let task = cx.spawn(async move |cx: &mut AsyncApp| {
 53            while let Some((prompt, channel)) = rx.next().await {
 54                password_prompt(prompt, channel, cx);
 55            }
 56        });
 57        Self {
 58            tx,
 59            _task: task,
 60            executor: cx.background_executor().clone(),
 61        }
 62    }
 63
 64    pub fn ask_password(&mut self, prompt: String) -> Task<Option<EncryptedPassword>> {
 65        let mut this_tx = self.tx.clone();
 66        self.executor.spawn(async move {
 67            let (tx, rx) = oneshot::channel();
 68            this_tx.send((prompt, tx)).await.ok()?;
 69            rx.await.ok()
 70        })
 71    }
 72}
 73
 74pub struct AskPassSession {
 75    #[cfg(target_os = "windows")]
 76    secret: std::sync::Arc<OnceLock<EncryptedPassword>>,
 77    askpass_task: PasswordProxy,
 78    askpass_opened_rx: Option<oneshot::Receiver<()>>,
 79    askpass_kill_master_rx: Option<oneshot::Receiver<()>>,
 80    executor: BackgroundExecutor,
 81}
 82
 83#[cfg(not(target_os = "windows"))]
 84const ASKPASS_SCRIPT_NAME: &str = "askpass.sh";
 85#[cfg(target_os = "windows")]
 86const ASKPASS_SCRIPT_NAME: &str = "askpass.ps1";
 87
 88impl AskPassSession {
 89    /// This will create a new AskPassSession.
 90    /// You must retain this session until the master process exits.
 91    #[must_use]
 92    pub async fn new(executor: BackgroundExecutor, mut delegate: AskPassDelegate) -> Result<Self> {
 93        #[cfg(target_os = "windows")]
 94        let secret = std::sync::Arc::new(OnceLock::new());
 95        let (askpass_opened_tx, askpass_opened_rx) = oneshot::channel::<()>();
 96
 97        let askpass_opened_tx = Arc::new(Mutex::new(Some(askpass_opened_tx)));
 98
 99        let (askpass_kill_master_tx, askpass_kill_master_rx) = oneshot::channel::<()>();
100        let kill_tx = Arc::new(Mutex::new(Some(askpass_kill_master_tx)));
101
102        #[cfg(target_os = "windows")]
103        let askpass_secret = secret.clone();
104        let get_password = {
105            let executor = executor.clone();
106
107            move |prompt| {
108                let prompt = delegate.ask_password(prompt);
109                let kill_tx = kill_tx.clone();
110                let askpass_opened_tx = askpass_opened_tx.clone();
111                #[cfg(target_os = "windows")]
112                let askpass_secret = askpass_secret.clone();
113                executor.spawn(async move {
114                    if let Some(askpass_opened_tx) = askpass_opened_tx.lock().await.take() {
115                        askpass_opened_tx.send(()).ok();
116                    }
117                    if let Some(password) = prompt.await {
118                        #[cfg(target_os = "windows")]
119                        {
120                            _ = askpass_secret.set(password.clone());
121                        }
122                        ControlFlow::Continue(Ok(password))
123                    } else {
124                        if let Some(kill_tx) = kill_tx.lock().await.take() {
125                            kill_tx.send(()).log_err();
126                        }
127                        ControlFlow::Break(())
128                    }
129                })
130            }
131        };
132        let askpass_task = PasswordProxy::new(get_password, executor.clone()).await?;
133
134        Ok(Self {
135            #[cfg(target_os = "windows")]
136            secret,
137
138            askpass_task,
139            askpass_kill_master_rx: Some(askpass_kill_master_rx),
140            askpass_opened_rx: Some(askpass_opened_rx),
141            executor,
142        })
143    }
144
145    // This will run the askpass task forever, resolving as many authentication requests as needed.
146    // The caller is responsible for examining the result of their own commands and cancelling this
147    // future when this is no longer needed. Note that this can only be called once, but due to the
148    // drop order this takes an &mut, so you can `drop()` it after you're done with the master process.
149    pub async fn run(&mut self) -> AskPassResult {
150        // This is the default timeout setting used by VSCode.
151        let connection_timeout = Duration::from_secs(17);
152        let askpass_opened_rx = self.askpass_opened_rx.take().expect("Only call run once");
153        let askpass_kill_master_rx = self
154            .askpass_kill_master_rx
155            .take()
156            .expect("Only call run once");
157        let executor = self.executor.clone();
158
159        select_biased! {
160            _ = askpass_opened_rx.fuse() => {
161                // Note: this await can only resolve after we are dropped.
162                askpass_kill_master_rx.await.ok();
163                AskPassResult::CancelledByUser
164            }
165
166            _ = futures::FutureExt::fuse(executor.timer(connection_timeout)) => {
167                AskPassResult::Timedout
168            }
169        }
170    }
171
172    /// This will return the password that was last set by the askpass script.
173    #[cfg(target_os = "windows")]
174    pub fn get_password(&self) -> Option<EncryptedPassword> {
175        self.secret.get().cloned()
176    }
177
178    pub fn script_path(&self) -> impl AsRef<OsStr> {
179        self.askpass_task.script_path()
180    }
181}
182
183pub struct PasswordProxy {
184    _task: Task<()>,
185    #[cfg(not(target_os = "windows"))]
186    askpass_script_path: std::path::PathBuf,
187    #[cfg(target_os = "windows")]
188    askpass_helper: String,
189}
190
191impl PasswordProxy {
192    pub async fn new(
193        mut get_password: impl FnMut(String) -> Task<ControlFlow<(), Result<EncryptedPassword>>>
194        + 'static
195        + Send
196        + Sync,
197        executor: BackgroundExecutor,
198    ) -> Result<Self> {
199        let temp_dir = tempfile::Builder::new().prefix("zed-askpass").tempdir()?;
200        let askpass_socket = temp_dir.path().join("askpass.sock");
201        let askpass_script_path = temp_dir.path().join(ASKPASS_SCRIPT_NAME);
202        let current_exec =
203            std::env::current_exe().context("Failed to determine current zed executable path.")?;
204
205        // TODO: inferred from the use of powershell.exe in askpass_helper_script
206        let shell_kind = if cfg!(windows) {
207            ShellKind::PowerShell
208        } else {
209            ShellKind::Posix
210        };
211        let askpass_program = ASKPASS_PROGRAM.get_or_init(|| current_exec);
212        // Create an askpass script that communicates back to this process.
213        let askpass_script = generate_askpass_script(shell_kind, askpass_program, &askpass_socket)?;
214        let _task = executor.spawn(async move {
215            maybe!(async move {
216                let listener =
217                    UnixListener::bind(&askpass_socket).context("creating askpass socket")?;
218
219                while let Ok((mut stream, _)) = listener.accept().await {
220                    let mut buffer = Vec::new();
221                    let mut reader = BufReader::new(&mut stream);
222                    if reader.read_until(b'\0', &mut buffer).await.is_err() {
223                        buffer.clear();
224                    }
225                    let prompt = String::from_utf8_lossy(&buffer).into_owned();
226                    let password = get_password(prompt).await;
227                    match password {
228                        ControlFlow::Continue(password) => {
229                            if let Ok(password) = password
230                                && let Ok(decrypted) =
231                                    password.decrypt(IKnowWhatIAmDoingAndIHaveReadTheDocs)
232                            {
233                                stream.write_all(decrypted.as_bytes()).await.log_err();
234                            }
235                        }
236                        ControlFlow::Break(()) => {
237                            // note: we expect the caller to drop this task when it's done.
238                            // We need to keep the stream open until the caller is done to avoid
239                            // spurious errors from ssh.
240                            std::future::pending::<()>().await;
241                            drop(stream);
242                        }
243                    }
244                }
245                drop(temp_dir);
246                Result::<_, anyhow::Error>::Ok(())
247            })
248            .await
249            .log_err();
250        });
251
252        fs::write(&askpass_script_path, askpass_script)
253            .await
254            .with_context(|| format!("creating askpass script at {askpass_script_path:?}"))?;
255        make_file_executable(&askpass_script_path)
256            .await
257            .with_context(|| {
258                format!("marking askpass script executable at {askpass_script_path:?}")
259            })?;
260        // todo(shell): There might be no powershell on the system
261        #[cfg(target_os = "windows")]
262        let askpass_helper = format!(
263            "powershell.exe -ExecutionPolicy Bypass -File \"{}\"",
264            askpass_script_path.display()
265        );
266
267        Ok(Self {
268            _task,
269            #[cfg(not(target_os = "windows"))]
270            askpass_script_path,
271            #[cfg(target_os = "windows")]
272            askpass_helper,
273        })
274    }
275
276    pub fn script_path(&self) -> impl AsRef<OsStr> {
277        #[cfg(not(target_os = "windows"))]
278        {
279            &self.askpass_script_path
280        }
281        #[cfg(target_os = "windows")]
282        {
283            &self.askpass_helper
284        }
285    }
286}
287/// The main function for when Zed is running in netcat mode for use in askpass.
288/// Called from both the remote server binary and the zed binary in their respective main functions.
289pub fn main(socket: &str) {
290    use net::UnixStream;
291    use std::io::{self, Read, Write};
292    use std::process::exit;
293
294    let mut stream = match UnixStream::connect(socket) {
295        Ok(stream) => stream,
296        Err(err) => {
297            eprintln!("Error connecting to socket {}: {}", socket, err);
298            exit(1);
299        }
300    };
301
302    let mut buffer = Vec::new();
303    if let Err(err) = io::stdin().read_to_end(&mut buffer) {
304        eprintln!("Error reading from stdin: {}", err);
305        exit(1);
306    }
307
308    #[cfg(target_os = "windows")]
309    while buffer.last().is_some_and(|&b| b == b'\n' || b == b'\r') {
310        buffer.pop();
311    }
312    if buffer.last() != Some(&b'\0') {
313        buffer.push(b'\0');
314    }
315
316    if let Err(err) = stream.write_all(&buffer) {
317        eprintln!("Error writing to socket: {}", err);
318        exit(1);
319    }
320
321    let mut response = Vec::new();
322    if let Err(err) = stream.read_to_end(&mut response) {
323        eprintln!("Error reading from socket: {}", err);
324        exit(1);
325    }
326
327    if let Err(err) = io::stdout().write_all(&response) {
328        eprintln!("Error writing to stdout: {}", err);
329        exit(1);
330    }
331}
332
333pub fn set_askpass_program(path: std::path::PathBuf) {
334    if ASKPASS_PROGRAM.set(path).is_err() {
335        debug_panic!("askpass program has already been set");
336    }
337}
338
339#[inline]
340#[cfg(not(target_os = "windows"))]
341fn generate_askpass_script(
342    shell_kind: ShellKind,
343    askpass_program: &std::path::Path,
344    askpass_socket: &std::path::Path,
345) -> Result<String> {
346    let askpass_program = shell_kind.prepend_command_prefix(
347        askpass_program
348            .to_str()
349            .context("Askpass program is on a non-utf8 path")?,
350    );
351    let askpass_program = shell_kind
352        .try_quote_prefix_aware(&askpass_program)
353        .context("Failed to shell-escape Askpass program path")?;
354    let askpass_socket = askpass_socket
355        .try_shell_safe(shell_kind)
356        .context("Failed to shell-escape Askpass socket path")?;
357    let print_args = "printf '%s\\0' \"$@\"";
358    let shebang = "#!/bin/sh";
359    Ok(format!(
360        "{shebang}\n{print_args} | {askpass_program} --askpass={askpass_socket} 2> /dev/null \n",
361    ))
362}
363
364#[inline]
365#[cfg(target_os = "windows")]
366fn generate_askpass_script(
367    shell_kind: ShellKind,
368    askpass_program: &std::path::Path,
369    askpass_socket: &std::path::Path,
370) -> Result<String> {
371    let askpass_program = shell_kind.prepend_command_prefix(
372        askpass_program
373            .to_str()
374            .context("Askpass program is on a non-utf8 path")?,
375    );
376    let askpass_program = shell_kind
377        .try_quote_prefix_aware(&askpass_program)
378        .context("Failed to shell-escape Askpass program path")?;
379    let askpass_socket = askpass_socket
380        .try_shell_safe(shell_kind)
381        .context("Failed to shell-escape Askpass socket path")?;
382    Ok(format!(
383        r#"
384        $ErrorActionPreference = 'Stop';
385        ($args -join [char]0) | {askpass_program} --askpass={askpass_socket} 2> $null
386        "#,
387    ))
388}