Skip to main content

artifactize_core/platform/
hidden_input.rs

1//! Stdin detection and the platform's echo-only guard for secret prompts.
2
3use std::io::{self, IsTerminal};
4
5use super::os::{HiddenInput, VISIBLE_INPUT_FALLBACK};
6
7/// Whether stdin can be used for an interactive prompt rather than a pipe or file.
8pub fn stdin_is_terminal() -> bool {
9    io::stdin().is_terminal()
10}
11
12/// How to read a secret from stdin without changing how redirected input is handled.
13pub enum SecretInput {
14    /// Read silently, without a terminal prompt.
15    Redirected,
16    /// Echo is disabled until the guard drops.
17    Hidden(HiddenInput),
18    /// Echo could not be disabled and the platform permits a visible read after warning.
19    Visible(io::Error),
20}
21
22/// Choose the stdin mode for a secret, disabling echo before the caller prompts if possible.
23pub fn secret_input() -> io::Result<SecretInput> {
24    if !stdin_is_terminal() {
25        return Ok(SecretInput::Redirected);
26    }
27    match HiddenInput::new() {
28        Ok(guard) => Ok(SecretInput::Hidden(guard)),
29        Err(error) if VISIBLE_INPUT_FALLBACK => Ok(SecretInput::Visible(error)),
30        Err(error) => Err(error),
31    }
32}
33
34#[cfg(test)]
35mod tests {
36    use std::io::{self, BufRead, Write};
37
38    use super::super::HiddenInput;
39    use crate::test_os::{self, PseudoTerminal};
40
41    const READY: &str = "HIDDEN_INPUT_READY";
42    const RESTORED: &str = "HIDDEN_INPUT_RESTORED";
43    const VISIBLE: &str = "visible-after-restoration";
44
45    /// Each acknowledgment is emitted only after the mode change it describes. No sleeps
46    /// or elapsed-time assertions decide whether input is hidden or restored.
47    #[test]
48    fn terminal_modes_restore_after_success_error_and_cancellation() {
49        let (mut terminal, receiver) = PseudoTerminal::start(
50            &std::env::current_exe().unwrap(),
51            &[
52                "--exact",
53                "platform::hidden_input::tests::restoration_probe",
54                "--ignored",
55                "--nocapture",
56            ],
57            &[],
58            100,
59            30,
60        );
61        let wait = test_os::patience(std::time::Duration::from_secs(10));
62        let mut output = Vec::new();
63        for case in 0..3 {
64            let ready = format!("{READY}_{case}");
65            while !String::from_utf8_lossy(&output).contains(&ready) {
66                output.extend(
67                    receiver
68                        .recv_timeout(wait)
69                        .expect("no hidden-input acknowledgment"),
70                );
71            }
72            terminal.type_text(format!("secret-input-{case}\r").as_bytes());
73            let restored = format!("{RESTORED}_{case}");
74            while !String::from_utf8_lossy(&output).contains(&restored) {
75                output.extend(
76                    receiver
77                        .recv_timeout(wait)
78                        .expect("no restoration acknowledgment"),
79                );
80            }
81            terminal.type_text(format!("{VISIBLE}-{case}\r").as_bytes());
82        }
83        assert!(terminal.finish_and_drain(receiver, &mut output));
84        let output = String::from_utf8_lossy(&output);
85        for case in 0..3 {
86            assert!(
87                !output.contains(&format!("secret-input-{case}")),
88                "{output}"
89            );
90            assert!(output.contains(&format!("{VISIBLE}-{case}")), "{output}");
91        }
92    }
93
94    /// Runs only in the parent test's private terminal, never in the test runner's console.
95    #[tokio::test]
96    #[ignore = "launched by the restoration test inside a private pseudo-terminal"]
97    async fn restoration_probe() {
98        for case in 0..3 {
99            let original = test_os::input_terminal_mode();
100            if case == 2 {
101                let (send, receive) = tokio::sync::oneshot::channel::<()>();
102                let mut reading = Box::pin(async {
103                    let _hidden = HiddenInput::new().unwrap();
104                    acknowledge(READY, case);
105                    receive.await.unwrap();
106                });
107                assert!(futures_util::poll!(&mut reading).is_pending());
108                assert_ne!(test_os::input_terminal_mode(), original);
109                read_line(); // The parent acknowledges the pending future with hidden input.
110                drop(reading); // Cancellation drops the guard without resolving the read.
111                drop(send);
112            } else {
113                assert_eq!(read_hidden(case).is_err(), case == 1);
114            }
115            assert_eq!(test_os::input_terminal_mode(), original);
116            acknowledge(RESTORED, case);
117            assert_eq!(read_line().trim(), format!("{VISIBLE}-{case}"));
118        }
119    }
120
121    fn read_hidden(case: usize) -> io::Result<()> {
122        let original = test_os::input_terminal_mode();
123        let _hidden = HiddenInput::new()?;
124        assert_ne!(test_os::input_terminal_mode(), original);
125        acknowledge(READY, case);
126        read_line();
127        if case == 1 {
128            // An I/O failure propagates out of the scope that owns the guard.
129            Err(io::ErrorKind::UnexpectedEof.into())
130        } else {
131            Ok(())
132        }
133    }
134
135    fn acknowledge(message: &str, case: usize) {
136        let mut stdout = io::stdout().lock();
137        writeln!(stdout, "{message}_{case}").unwrap();
138        stdout.flush().unwrap();
139    }
140
141    fn read_line() -> String {
142        let mut line = String::new();
143        io::stdin().lock().read_line(&mut line).unwrap();
144        line
145    }
146}