artifactize_core/platform/
hidden_input.rs1use std::io::{self, IsTerminal};
4
5use super::os::{HiddenInput, VISIBLE_INPUT_FALLBACK};
6
7pub fn stdin_is_terminal() -> bool {
9 io::stdin().is_terminal()
10}
11
12pub enum SecretInput {
14 Redirected,
16 Hidden(HiddenInput),
18 Visible(io::Error),
20}
21
22pub 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 #[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 #[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(); drop(reading); 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 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}