askpass.rs

  1use std::path::{Path, PathBuf};
  2use std::time::Duration;
  3
  4#[cfg(unix)]
  5use anyhow::Context as _;
  6use futures::channel::{mpsc, oneshot};
  7#[cfg(unix)]
  8use futures::{AsyncBufReadExt as _, io::BufReader};
  9#[cfg(unix)]
 10use futures::{AsyncWriteExt as _, FutureExt as _, select_biased};
 11use futures::{SinkExt, StreamExt};
 12use gpui::{AsyncApp, BackgroundExecutor, Task};
 13#[cfg(unix)]
 14use smol::fs;
 15#[cfg(unix)]
 16use smol::{fs::unix::PermissionsExt as _, net::unix::UnixListener};
 17#[cfg(unix)]
 18use util::ResultExt as _;
 19
 20#[derive(PartialEq, Eq)]
 21pub enum AskPassResult {
 22    CancelledByUser,
 23    Timedout,
 24}
 25
 26pub struct AskPassDelegate {
 27    tx: mpsc::UnboundedSender<(String, oneshot::Sender<String>)>,
 28    _task: Task<()>,
 29}
 30
 31impl AskPassDelegate {
 32    pub fn new(
 33        cx: &mut AsyncApp,
 34        password_prompt: impl Fn(String, oneshot::Sender<String>, &mut AsyncApp) + Send + Sync + 'static,
 35    ) -> Self {
 36        let (tx, mut rx) = mpsc::unbounded::<(String, oneshot::Sender<String>)>();
 37        let task = cx.spawn(async move |cx: &mut AsyncApp| {
 38            while let Some((prompt, channel)) = rx.next().await {
 39                password_prompt(prompt, channel, cx);
 40            }
 41        });
 42        Self { tx, _task: task }
 43    }
 44
 45    pub async fn ask_password(&mut self, prompt: String) -> anyhow::Result<String> {
 46        let (tx, rx) = oneshot::channel();
 47        self.tx.send((prompt, tx)).await?;
 48        Ok(rx.await?)
 49    }
 50}
 51
 52#[cfg(unix)]
 53pub struct AskPassSession {
 54    script_path: PathBuf,
 55    _askpass_task: Task<()>,
 56    askpass_opened_rx: Option<oneshot::Receiver<()>>,
 57    askpass_kill_master_rx: Option<oneshot::Receiver<()>>,
 58}
 59
 60#[cfg(unix)]
 61impl AskPassSession {
 62    /// This will create a new AskPassSession.
 63    /// You must retain this session until the master process exits.
 64    #[must_use]
 65    pub async fn new(
 66        executor: &BackgroundExecutor,
 67        mut delegate: AskPassDelegate,
 68    ) -> anyhow::Result<Self> {
 69        let temp_dir = tempfile::Builder::new().prefix("zed-askpass").tempdir()?;
 70        let askpass_socket = temp_dir.path().join("askpass.sock");
 71        let askpass_script_path = temp_dir.path().join("askpass.sh");
 72        let (askpass_opened_tx, askpass_opened_rx) = oneshot::channel::<()>();
 73        let listener =
 74            UnixListener::bind(&askpass_socket).context("failed to create askpass socket")?;
 75
 76        let (askpass_kill_master_tx, askpass_kill_master_rx) = oneshot::channel::<()>();
 77        let mut kill_tx = Some(askpass_kill_master_tx);
 78
 79        let askpass_task = executor.spawn(async move {
 80            let mut askpass_opened_tx = Some(askpass_opened_tx);
 81
 82            while let Ok((mut stream, _)) = listener.accept().await {
 83                if let Some(askpass_opened_tx) = askpass_opened_tx.take() {
 84                    askpass_opened_tx.send(()).ok();
 85                }
 86                let mut buffer = Vec::new();
 87                let mut reader = BufReader::new(&mut stream);
 88                if reader.read_until(b'\0', &mut buffer).await.is_err() {
 89                    buffer.clear();
 90                }
 91                let prompt = String::from_utf8_lossy(&buffer);
 92                if let Some(password) = delegate
 93                    .ask_password(prompt.to_string())
 94                    .await
 95                    .context("failed to get askpass password")
 96                    .log_err()
 97                {
 98                    stream.write_all(password.as_bytes()).await.log_err();
 99                } else {
100                    if let Some(kill_tx) = kill_tx.take() {
101                        kill_tx.send(()).log_err();
102                    }
103                    // note: we expect the caller to drop this task when it's done.
104                    // We need to keep the stream open until the caller is done to avoid
105                    // spurious errors from ssh.
106                    std::future::pending::<()>().await;
107                    drop(stream);
108                }
109            }
110            drop(temp_dir)
111        });
112
113        anyhow::ensure!(
114            which::which("nc").is_ok(),
115            "Cannot find `nc` command (netcat), which is required to connect over SSH."
116        );
117
118        // Create an askpass script that communicates back to this process.
119        let askpass_script = format!(
120            "{shebang}\n{print_args} | {nc} -U {askpass_socket} 2> /dev/null \n",
121            // on macOS `brew install netcat` provides the GNU netcat implementation
122            // which does not support -U.
123            nc = if cfg!(target_os = "macos") {
124                "/usr/bin/nc"
125            } else {
126                "nc"
127            },
128            askpass_socket = askpass_socket.display(),
129            print_args = "printf '%s\\0' \"$@\"",
130            shebang = "#!/bin/sh",
131        );
132        fs::write(&askpass_script_path, askpass_script).await?;
133        fs::set_permissions(&askpass_script_path, std::fs::Permissions::from_mode(0o755)).await?;
134
135        Ok(Self {
136            script_path: askpass_script_path,
137            _askpass_task: askpass_task,
138            askpass_kill_master_rx: Some(askpass_kill_master_rx),
139            askpass_opened_rx: Some(askpass_opened_rx),
140        })
141    }
142
143    pub fn script_path(&self) -> &Path {
144        &self.script_path
145    }
146
147    // This will run the askpass task forever, resolving as many authentication requests as needed.
148    // The caller is responsible for examining the result of their own commands and cancelling this
149    // future when this is no longer needed. Note that this can only be called once, but due to the
150    // drop order this takes an &mut, so you can `drop()` it after you're done with the master process.
151    pub async fn run(&mut self) -> AskPassResult {
152        let connection_timeout = Duration::from_secs(10);
153        let askpass_opened_rx = self.askpass_opened_rx.take().expect("Only call run once");
154        let askpass_kill_master_rx = self
155            .askpass_kill_master_rx
156            .take()
157            .expect("Only call run once");
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                return AskPassResult::CancelledByUser
164            }
165
166            _ = futures::FutureExt::fuse(smol::Timer::after(connection_timeout)) => {
167                return AskPassResult::Timedout
168            }
169        }
170    }
171}
172
173#[cfg(not(unix))]
174pub struct AskPassSession {
175    path: PathBuf,
176}
177
178#[cfg(not(unix))]
179impl AskPassSession {
180    pub async fn new(_: &BackgroundExecutor, _: AskPassDelegate) -> anyhow::Result<Self> {
181        Ok(Self {
182            path: PathBuf::new(),
183        })
184    }
185
186    pub fn script_path(&self) -> &Path {
187        &self.path
188    }
189
190    pub async fn run(&mut self) -> AskPassResult {
191        futures::FutureExt::fuse(smol::Timer::after(Duration::from_secs(20))).await;
192        AskPassResult::Timedout
193    }
194}