1use std::fmt;
9use std::io::{self, IsTerminal as _, Read as _};
10use std::process::{Child, Command, ExitStatus, Stdio};
11use std::str::FromStr;
12use std::sync::mpsc;
13use std::thread;
14use std::time::{Duration, Instant};
15
16use serde::{Deserialize, Serialize};
17use tr064::SecretString;
18
19pub const ENV_PASSWORD_COMMAND: &str = "FRITZ_PASSWORD_COMMAND";
21
22pub const TIMEOUT: Duration = Duration::from_secs(30);
24
25#[derive(Debug, thiserror::Error)]
27pub enum Error {
28 #[error("the password command is empty")]
30 Empty,
31 #[error("the password command is not a JSON list of strings")]
33 Invalid,
34 #[error("cannot run the password command `{0}`")]
36 Run(String, #[source] io::Error),
37 #[error("the password command `{0}` failed with {1}")]
39 Failed(String, ExitStatus),
40 #[error("the password command `{0}` did not finish within {1:?}")]
42 Timeout(String, Duration),
43 #[error("the password command `{0}` printed no password")]
45 NoOutput(String),
46 #[error("the password command `{0}` printed no valid UTF-8")]
48 NotUtf8(String),
49}
50
51#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
53#[serde(try_from = "Vec<String>", into = "Vec<String>")]
54pub struct PasswordCommand(Vec<String>);
55
56impl fmt::Debug for PasswordCommand {
57 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
59 f.debug_tuple("PasswordCommand")
60 .field(&self.name())
61 .finish()
62 }
63}
64
65impl TryFrom<Vec<String>> for PasswordCommand {
66 type Error = Error;
67
68 fn try_from(words: Vec<String>) -> Result<Self, Error> {
69 if words.first().is_none_or(String::is_empty) {
70 return Err(Error::Empty);
71 }
72 Ok(Self(words))
73 }
74}
75
76impl From<PasswordCommand> for Vec<String> {
77 fn from(command: PasswordCommand) -> Self {
78 command.0
79 }
80}
81
82impl FromStr for PasswordCommand {
83 type Err = Error;
84
85 fn from_str(text: &str) -> Result<Self, Error> {
88 let words: Vec<String> = if text.trim_start().starts_with('[') {
89 serde_json::from_str(text).map_err(|_| Error::Invalid)?
90 } else {
91 text.split_whitespace().map(str::to_owned).collect()
92 };
93 words.try_into()
94 }
95}
96
97impl PasswordCommand {
98 pub fn name(&self) -> &str {
100 &self.0[0]
101 }
102
103 pub fn run(&self, timeout: Duration) -> Result<SecretString, Error> {
114 self.run_with(timeout, io::stdin().is_terminal())
115 }
116
117 fn run_with(&self, timeout: Duration, terminal: bool) -> Result<SecretString, Error> {
118 let name = || self.name().to_owned();
119 let deadline = Instant::now() + timeout;
120 let stdin = terminal.then(Stdio::inherit).unwrap_or_else(Stdio::null);
121 let mut command = Command::new(&self.0[0]);
122 command
123 .args(&self.0[1..])
124 .stdin(stdin)
125 .stdout(Stdio::piped())
126 .stderr(Stdio::inherit());
127 #[cfg(unix)]
128 if !terminal {
129 use std::os::unix::process::CommandExt as _;
130 command.process_group(0);
131 }
132 let mut child = command.spawn().map_err(|error| Error::Run(name(), error))?;
133 let mut stdout = child.stdout.take().expect("the output is piped");
134 let (sender, receiver) = mpsc::channel();
135 thread::spawn(move || {
137 let mut output = Vec::new();
138 let result = stdout.read_to_end(&mut output).map(|_| output);
139 let _ = sender.send(result);
141 });
142 let timed_out = |mut child: Child| {
143 #[cfg(unix)]
147 if !terminal {
148 use rustix::process::{Pid, Signal, kill_process_group};
149 let _ = kill_process_group(Pid::from_child(&child), Signal::KILL);
150 }
151 let _ = child.kill();
153 let _ = child.wait();
154 Error::Timeout(name(), timeout)
155 };
156 let Some(status) = wait(&mut child, deadline).map_err(|e| Error::Run(name(), e))? else {
157 return Err(timed_out(child));
158 };
159 if !status.success() {
160 return Err(Error::Failed(name(), status));
161 }
162 let remaining = deadline.saturating_duration_since(Instant::now());
164 let Ok(output) = receiver.recv_timeout(remaining) else {
165 return Err(timed_out(child));
166 };
167 let mut output = output.map_err(|e| Error::Run(name(), e))?;
168 if output.last() == Some(&b'\n') {
169 output.pop();
170 if output.last() == Some(&b'\r') {
171 output.pop();
172 }
173 }
174 if output.is_empty() {
175 return Err(Error::NoOutput(name()));
176 }
177 let password = String::from_utf8(output).map_err(|_| Error::NotUtf8(name()))?;
178 Ok(password.into())
179 }
180}
181
182fn wait(child: &mut Child, deadline: Instant) -> io::Result<Option<ExitStatus>> {
185 loop {
186 if let Some(status) = child.try_wait()? {
187 return Ok(Some(status));
188 }
189 if Instant::now() >= deadline {
190 return Ok(None);
191 }
192 thread::sleep(Duration::from_millis(10));
193 }
194}
195
196#[cfg(test)]
197mod tests {
198 use secrecy::ExposeSecret as _;
199
200 use super::*;
201
202 fn command(words: &[&str]) -> PasswordCommand {
203 words
204 .iter()
205 .map(|w| (*w).to_owned())
206 .collect::<Vec<_>>()
207 .try_into()
208 .unwrap()
209 }
210
211 #[test]
212 fn parses_lists_and_words() {
213 let parsed: PasswordCommand = r#" ["op", "read", "op://Private/My Box/password"]"#
214 .parse()
215 .unwrap();
216 assert_eq!(
217 Vec::from(parsed.clone()),
218 ["op", "read", "op://Private/My Box/password"]
219 );
220 assert_eq!(parsed.name(), "op");
221 assert_eq!(format!("{parsed:?}"), "PasswordCommand(\"op\")");
222
223 let parsed: PasswordCommand = "pass show\tfritz\n".parse().unwrap();
224 assert_eq!(parsed, command(&["pass", "show", "fritz"]));
225
226 for text in ["", " ", "[]", r#"[""]"#] {
227 let error = text.parse::<PasswordCommand>().unwrap_err();
228 assert_eq!(error.to_string(), "the password command is empty", "{text}");
229 }
230 for text in ["[1]", "[\"op\""] {
231 let error = text.parse::<PasswordCommand>().unwrap_err();
232 assert_eq!(
233 error.to_string(),
234 "the password command is not a JSON list of strings"
235 );
236 }
237 }
238
239 #[test]
240 fn reports_a_missing_program() {
241 let error = command(&["fritz-test-no-such-program"])
242 .run(TIMEOUT)
243 .unwrap_err();
244 assert_eq!(
245 error.to_string(),
246 "cannot run the password command `fritz-test-no-such-program`"
247 );
248 }
249
250 #[cfg(unix)]
251 mod unix {
252 use super::*;
253
254 const SHORT: Duration = Duration::from_millis(300);
255
256 #[test]
257 fn reads_the_password() {
258 for (output, expected) in [
259 ("secret\n", "secret"),
260 ("secret\r\n", "secret"),
261 ("secret\n\n", "secret\n"),
262 ("secret", "secret"),
263 (" with space ", " with space "),
264 ] {
265 let password = command(&["printf", "%s", output]).run(TIMEOUT).unwrap();
266 assert_eq!(password.expose_secret(), expected, "{output:?}");
267 }
268 }
269
270 #[test]
271 fn runs_no_shell() {
272 let password = command(&["printf", "%s", "$(echo x) | y; z"])
273 .run(TIMEOUT)
274 .unwrap();
275 assert_eq!(password.expose_secret(), "$(echo x) | y; z");
276 }
277
278 #[test]
279 fn reports_failures_without_the_output() {
280 let error = command(&["sh", "-c", "echo secret; exit 3"])
281 .run(TIMEOUT)
282 .unwrap_err();
283 assert_eq!(
284 error.to_string(),
285 "the password command `sh` failed with exit status: 3"
286 );
287
288 for output in ["", "\n"] {
289 let error = command(&["printf", output]).run(TIMEOUT).unwrap_err();
290 assert_eq!(
291 error.to_string(),
292 "the password command `printf` printed no password"
293 );
294 }
295
296 let error = command(&["printf", "\\377"]).run(TIMEOUT).unwrap_err();
297 assert_eq!(
298 error.to_string(),
299 "the password command `printf` printed no valid UTF-8"
300 );
301 }
302
303 #[test]
304 fn stops_slow_commands() {
305 for terminal in [false, true] {
306 let started = Instant::now();
307 let error = command(&["sleep", "5"])
308 .run_with(SHORT, terminal)
309 .unwrap_err();
310 assert_eq!(
311 error.to_string(),
312 "the password command `sleep` did not finish within 300ms"
313 );
314 assert!(started.elapsed() < Duration::from_secs(4));
315 }
316 }
317
318 fn alive(pid: &str) -> bool {
321 (0..100).all(|_| {
322 thread::sleep(Duration::from_millis(50));
323 let status = Command::new("kill")
324 .args(["-0", pid])
325 .stderr(Stdio::null())
326 .status()
327 .unwrap();
328 status.success()
329 })
330 }
331
332 #[test]
333 fn stops_the_processes_the_command_started() {
334 let dir = tempfile::tempdir().unwrap();
337 let file = dir.path().join("pid");
338 let script = format!("sleep 30 & echo $! > '{}'; echo secret", file.display());
339 let started = Instant::now();
340 let error = command(&["sh", "-c", &script])
341 .run_with(SHORT, false)
342 .unwrap_err();
343 assert!(matches!(error, Error::Timeout(..)), "{error}");
344 assert!(started.elapsed() < Duration::from_secs(4));
345 let pid = std::fs::read_to_string(&file).unwrap();
346 assert!(!alive(pid.trim()), "sleep {pid} still runs");
347 }
348
349 #[test]
350 fn uses_the_terminal_of_fritz() {
351 let password = command(&["printf", "secret"])
352 .run_with(TIMEOUT, true)
353 .unwrap();
354 assert_eq!(password.expose_secret(), "secret");
355 }
356 }
357}