fix: make prompt LUKS more visible

This commit is contained in:
Willem Vanhulle committed 2026-10-16 11:42:52 +02:00
1 parent 5e4ce012f4
commit 589d0b7655
9 files changed
+563 -92

No files matched your search

+1
View File
@@ -3,5 +3,6 @@ pub mod glyphs;
pub mod model;
pub mod origin;
pub mod palette;
pub mod passphrase;
pub mod script;
pub mod view;
+81
View File
@@ -0,0 +1,81 @@
use std::mem::take;
use ratatui::crossterm::event::{Event, KeyCode, KeyEvent, KeyEventKind, KeyModifiers};
use zeroize::Zeroizing;
const ROOM_FOR_TYPING: usize = 512;
#[must_use]
pub fn empty() -> Zeroizing<String> {
Zeroizing::new(String::with_capacity(ROOM_FOR_TYPING))
}
#[must_use]
pub fn masked(typed: &str) -> String {
"*".repeat(typed.chars().count())
}
pub fn type_key(typed: &mut Zeroizing<String>, event: &Event) -> Option<Zeroizing<String>> {
let Event::Key(KeyEvent {
code,
modifiers,
kind: KeyEventKind::Press,
..
}) = event
else {
return None;
};
match code {
KeyCode::Enter => return Some(Zeroizing::new(take(&mut **typed))),
KeyCode::Backspace => {
typed.pop();
}
KeyCode::Char('u') if modifiers.contains(KeyModifiers::CONTROL) => typed.clear(),
KeyCode::Char(_) if modifiers.contains(KeyModifiers::CONTROL) => {}
KeyCode::Char(character) if typed.len() + character.len_utf8() <= ROOM_FOR_TYPING => {
typed.push(*character);
}
_ => {}
}
None
}
#[cfg(test)]
mod tests {
use super::*;
fn press(code: KeyCode) -> Event {
Event::Key(KeyEvent::from(code))
}
fn typed(text: &str) -> Zeroizing<String> {
let mut typed = empty();
text.chars()
.map(KeyCode::Char)
.for_each(|code| assert_eq!(type_key(&mut typed, &press(code)), None));
typed
}
#[test]
fn hides_what_is_typed() {
let mut typed = typed("secret");
type_key(&mut typed, &press(KeyCode::Backspace));
assert_eq!(masked(&typed), "*****");
}
#[test]
fn control_u_clears() {
let mut typed = typed("secret");
let control_u = Event::Key(KeyEvent::new(KeyCode::Char('u'), KeyModifiers::CONTROL));
type_key(&mut typed, &control_u);
assert_eq!(typed.as_str(), "");
}
#[test]
fn enter_hands_over_what_was_typed() {
let mut typed = typed("secret");
let submitted = type_key(&mut typed, &press(KeyCode::Enter));
assert_eq!(submitted.as_deref().map(String::as_str), Some("secret"));
assert_eq!(typed.as_str(), "");
}
}
+18 -37
View File
@@ -5,8 +5,8 @@ use std::{
time::Duration,
};
use bootvine::view::PasswordPrompt;
use crossterm::event::{Event, KeyCode, KeyEvent, KeyEventKind, KeyModifiers};
use bootvine::{passphrase, view::PasswordPrompt};
use crossterm::event::Event;
use rustix::process::{Pid, test_kill_process};
use zeroize::Zeroizing;
@@ -15,7 +15,6 @@ use crate::clock::monotonic_now;
const REQUESTS: &str = "/run/systemd/ask-password";
const REQUEST_PREFIX: &str = "ask.";
const ASK_SECTION: &str = "[Ask]";
const ROOM_FOR_TYPING: usize = 512;
#[derive(Debug, PartialEq, Eq)]
pub struct PasswordRequest {
@@ -137,16 +136,18 @@ impl PasswordEntry {
);
Some(Self {
request,
typed: Zeroizing::new(String::with_capacity(ROOM_FOR_TYPING)),
typed: passphrase::empty(),
sent: false,
})
}
pub fn prompt(&self) -> PasswordPrompt<'_> {
let input = match (self.sent, self.request.echo, self.request.silent) {
(true, _, _) | (false, _, true) => String::new(),
(false, true, false) => self.typed.as_str().to_owned(),
(false, false, false) => "*".repeat(self.typed.chars().count()),
let input = if self.request.silent {
String::new()
} else if self.request.echo {
self.typed.to_string()
} else {
passphrase::masked(&self.typed)
};
PasswordPrompt {
message: &self.request.message,
@@ -156,43 +157,23 @@ impl PasswordEntry {
}
pub fn type_key(&mut self, event: &Event) -> io::Result<()> {
let Event::Key(KeyEvent {
code,
modifiers,
kind: KeyEventKind::Press,
..
}) = event
else {
return Ok(());
};
if self.sent {
return Ok(());
}
match code {
KeyCode::Enter => {
self.request.answer(&self.typed)?;
self.sent = true;
self.typed.clear();
eprintln!("bootvine: answered a password prompt");
}
KeyCode::Backspace => {
self.typed.pop();
}
KeyCode::Char('u') if modifiers.contains(KeyModifiers::CONTROL) => self.typed.clear(),
KeyCode::Char(_) if modifiers.contains(KeyModifiers::CONTROL) => {}
KeyCode::Char(character)
if self.typed.len() + character.len_utf8() <= ROOM_FOR_TYPING =>
{
self.typed.push(*character);
}
_ => {}
}
let Some(submitted) = passphrase::type_key(&mut self.typed, event) else {
return Ok(());
};
self.request.answer(&submitted)?;
self.sent = true;
eprintln!("bootvine: answered a password prompt");
Ok(())
}
}
#[cfg(test)]
mod tests {
use crossterm::event::{KeyCode, KeyEvent};
use super::*;
const CRYPTSETUP_ASK: &str = concat!(
@@ -236,7 +217,7 @@ mod tests {
fn hides_what_is_typed() {
let mut entry = PasswordEntry {
request: PasswordRequest::parse(Path::new("ask.x"), CRYPTSETUP_ASK).expect("parsed"),
typed: Zeroizing::new(String::new()),
typed: passphrase::empty(),
sent: false,
};
"secret".chars().for_each(|character| {
+98 -24
View File
@@ -15,18 +15,22 @@ use crate::{
model::{ActiveState, Activity, BootState, JobKind, JobResult, Phase, UnitFacts},
origin::BootOrigin,
palette::Palette,
view::BootView,
passphrase,
view::{BootView, PasswordPrompt},
};
const FRAME_INTERVAL: Duration = Duration::from_millis(100);
const FINAL_FRAME: Duration = Duration::from_secs(3);
pub const DEMO_PASSPHRASE: &str = "demo";
pub struct Step {
unit: &'static str,
after: &'static [&'static str],
work: Duration,
fails: bool,
stops: bool,
asks: Option<&'static str>,
}
#[must_use]
@@ -37,28 +41,36 @@ pub const fn step(unit: &'static str, after: &'static [&'static str], work: Dura
work,
fails: false,
stops: false,
asks: None,
}
}
#[must_use]
pub const fn failing(unit: &'static str, after: &'static [&'static str], work: Duration) -> Step {
Step {
unit,
after,
work,
fails: true,
stops: false,
..step(unit, after, work)
}
}
#[must_use]
pub const fn stopping(unit: &'static str, after: &'static [&'static str], work: Duration) -> Step {
Step {
unit,
after,
work,
fails: false,
stops: true,
..step(unit, after, work)
}
}
#[must_use]
pub const fn unlocking(
unit: &'static str,
after: &'static [&'static str],
message: &'static str,
key_derivation: Duration,
) -> Step {
Step {
asks: Some(message),
..step(unit, after, key_derivation)
}
}
@@ -127,10 +139,12 @@ impl ScriptedJob {
}
fn settled_activity(&self, now: Duration) -> Activity {
let state = match (self.step.fails, self.step.stops) {
(true, _) => ActiveState::Failed,
(false, true) => ActiveState::Inactive,
(false, false) => ActiveState::Active,
let state = if self.step.fails {
ActiveState::Failed
} else if self.step.stops {
ActiveState::Inactive
} else {
ActiveState::Active
};
Activity {
state: Some(state),
@@ -144,6 +158,13 @@ struct Script {
jobs: Vec<ScriptedJob>,
started: HashMap<&'static str, Duration>,
finished: HashSet<&'static str>,
answer: Option<Answer>,
}
#[derive(Clone, Copy)]
struct Answer {
checked_at: Duration,
unlocks: bool,
}
impl Script {
@@ -169,9 +190,40 @@ impl Script {
jobs,
started: HashMap::new(),
finished: HashSet::new(),
answer: None,
}
}
fn asking(&self) -> Option<&'static Step> {
self.jobs.iter().map(|job| job.step).find(|step| {
step.asks.is_some()
&& self.started.contains_key(step.unit)
&& !self.finished.contains(step.unit)
})
}
fn is_checking(&self, now: Duration) -> bool {
self.answer.is_some_and(|answer| now < answer.checked_at)
}
fn prompt(&self, typed: &str, now: Duration) -> Option<PasswordPrompt<'static>> {
Some(PasswordPrompt {
message: self.asking()?.asks?,
input: passphrase::masked(typed),
sent: self.is_checking(now),
})
}
fn answer(&mut self, submitted: &str, now: Duration) {
let Some(step) = self.asking() else {
return;
};
self.answer = Some(Answer {
checked_at: now + step.work,
unlocks: submitted == DEMO_PASSPHRASE,
});
}
fn is_ready(&self, job: &ScriptedJob) -> bool {
!self.started.contains_key(job.step.unit)
&& job
@@ -186,11 +238,17 @@ impl Script {
}
fn is_due(&self, job: &ScriptedJob, now: Duration) -> bool {
!self.finished.contains(job.step.unit)
&& self
let done_at = match job.step.asks {
Some(_) => self
.answer
.filter(|answer| answer.unlocks)
.map(|answer| answer.checked_at),
None => self
.started
.get(job.step.unit)
.is_some_and(|started| now >= *started + job.step.work)
.map(|started| *started + job.step.work),
};
!self.finished.contains(job.step.unit) && done_at.is_some_and(|done_at| now >= done_at)
}
fn advance(&mut self, state: &mut BootState, now: Duration) {
@@ -224,12 +282,18 @@ impl Script {
}
}
fn wants_to_quit() -> io::Result<bool> {
if !event::poll(FRAME_INTERVAL)? {
return Ok(false);
fn next_event() -> io::Result<Option<Event>> {
if event::poll(FRAME_INTERVAL)? {
event::read().map(Some)
} else {
Ok(None)
}
Ok(
matches!(event::read()?, Event::Key(key) if matches!(key.code, KeyCode::Char('q') | KeyCode::Esc)),
}
fn quits(event: &Event, typing: bool) -> bool {
matches!(
event,
Event::Key(key) if key.code == KeyCode::Esc || (!typing && key.code == KeyCode::Char('q'))
)
}
@@ -247,6 +311,7 @@ pub fn play(terminal: &mut DefaultTerminal, scenario: &Scenario) -> io::Result<(
let mut switched_root = scenario.after_switch_root.is_empty();
let mut settled_at = None;
let mut frame = 0;
let mut typed = passphrase::empty();
loop {
script.advance(&mut state, now());
if script.is_done() && !switched_root {
@@ -270,7 +335,7 @@ pub fn play(terminal: &mut DefaultTerminal, scenario: &Scenario) -> io::Result<(
now: now(),
origin: &origin,
frame,
password_prompt: None,
password_prompt: script.prompt(&typed, now()),
},
canvas.area(),
);
@@ -279,8 +344,17 @@ pub fn play(terminal: &mut DefaultTerminal, scenario: &Scenario) -> io::Result<(
{
return Ok(());
}
if wants_to_quit()? {
return Ok(());
if let Some(event) = next_event()? {
let asking = script.asking().is_some();
if quits(&event, asking) {
return Ok(());
}
if asking
&& !script.is_checking(now())
&& let Some(submitted) = passphrase::type_key(&mut typed, &event)
{
script.answer(&submitted, now());
}
}
frame += 1;
}
+106 -9
View File
@@ -17,7 +17,7 @@ use unicode_width::UnicodeWidthStr;
pub use self::chrome::PasswordPrompt;
use self::{
chrome::{FOOTER_HEIGHT, Footer, Header, PasswordBar},
chrome::{FOOTER_HEIGHT, Footer, Header, PasswordPopup},
stages::Stages,
timeline::Timeline,
tree::UnitTree,
@@ -183,14 +183,14 @@ impl Widget for BootView<'_> {
if heights.timeline > 0 {
timeline.render(timeline_area, buf);
}
match &self.password_prompt {
Some(asking) => PasswordBar {
footer.render(footer_area, buf);
if let Some(asking) = &self.password_prompt {
PasswordPopup {
asking,
palette: self.palette,
glyphs: self.glyphs,
}
.render(footer_area, buf),
None => footer.render(footer_area, buf),
.render(area, buf);
}
}
}
@@ -260,6 +260,16 @@ mod tests {
}
fn render(state: &BootState, now: Duration, width: u16, height: u16) -> Vec<String> {
screen_lines(&render_prompted(state, now, width, height, None))
}
fn render_prompted(
state: &BootState,
now: Duration,
width: u16,
height: u16,
password_prompt: Option<PasswordPrompt>,
) -> Buffer {
let mut terminal = Terminal::new(TestBackend::new(width, height)).expect("test backend");
terminal
.draw(|frame| {
@@ -277,16 +287,20 @@ mod tests {
kernel: "Linux 7.2.9".to_owned(),
},
frame: 1,
password_prompt: None,
password_prompt,
},
frame.area(),
);
})
.expect("draw");
let buffer = terminal.backend().buffer().clone();
(0..height)
terminal.backend().buffer().clone()
}
fn screen_lines(buffer: &Buffer) -> Vec<String> {
let area = buffer.area;
(0..area.height)
.map(|y| {
let line: String = (0..width)
let line: String = (0..area.width)
.map(|x| buffer[(x, y)].symbol().to_owned())
.collect();
line.trim_end().to_owned()
@@ -477,6 +491,89 @@ mod tests {
assert!(lines[5].ends_with("web"), "{screen}");
}
const CRYPTSETUP_MESSAGE: &str =
"Please enter passphrase for disk Samsung SSD 980 PRO 1TB (cryptroot):";
#[test]
fn password_prompt_floats_over_a_dimmed_view() {
let buffer = render_prompted(
&boot_in_progress(),
12_400 * MS,
110,
24,
Some(PasswordPrompt {
message: CRYPTSETUP_MESSAGE,
input: "***".to_owned(),
sent: false,
}),
);
let lines = screen_lines(&buffer);
let screen = lines.join("\n");
let title_row = lines
.iter()
.position(|line| line.contains("┌ Password "))
.unwrap_or_else(|| panic!("{screen}"));
assert!(lines[title_row].starts_with(' '), "{screen}");
assert!(
lines[title_row + 1].contains(&format!("│ {CRYPTSETUP_MESSAGE}")),
"{screen}"
);
assert!(lines[title_row + 3].contains("│ > ***_"), "{screen}");
assert!(lines[title_row + 4].contains("Enter unlock"), "{screen}");
assert!(
lines[23].starts_with("√ 2 done 2 running 3 waiting × 1 failed"),
"{screen}"
);
assert_eq!(buffer[(0, 0)].fg, Palette::default().muted, "{screen}");
let corner = buffer
.content
.iter()
.find(|cell| cell.symbol() == "┌")
.unwrap_or_else(|| panic!("{screen}"));
assert_eq!(corner.fg, Palette::default().running, "{screen}");
}
#[test]
fn answered_password_prompt_shows_it_is_checking() {
let lines = screen_lines(&render_prompted(
&boot_in_progress(),
12_400 * MS,
110,
24,
Some(PasswordPrompt {
message: CRYPTSETUP_MESSAGE,
input: String::new(),
sent: true,
}),
));
assert!(
lines.iter().any(|line| line.contains("│ Checking…")),
"{}",
lines.join("\n")
);
}
#[test]
fn long_password_messages_wrap_inside_narrow_screens() {
let lines = screen_lines(&render_prompted(
&boot_in_progress(),
12_400 * MS,
50,
24,
Some(PasswordPrompt {
message: CRYPTSETUP_MESSAGE,
input: String::new(),
sent: false,
}),
));
let screen = lines.join("\n");
assert!(
lines.iter().any(|line| line.contains("(cryptroot):")),
"{screen}"
);
assert!(lines.iter().any(|line| line.contains("> _")), "{screen}");
}
#[test]
fn sub_second_runs_stay_off_the_timeline() {
let mut state = boot_in_progress();
+50 -20
View File
@@ -2,13 +2,13 @@ use std::{iter::once, time::Duration};
use ratatui::{
buffer::Buffer,
layout::Rect,
style::Stylize,
layout::{Constraint, Rect},
style::{Style, Stylize},
text::{Line, Span},
widgets::{Block, Borders, Paragraph, Widget},
widgets::{Block, Borders, Clear, Padding, Paragraph, Widget, Wrap},
};
use super::{DURATION_WIDTH, ELAPSED, rule};
use super::{DURATION_WIDTH, ELAPSED};
use crate::{glyphs::Glyphs, model::Tally, origin::BootOrigin, palette::Palette};
pub const FOOTER_HEIGHT: u16 = 2;
@@ -92,27 +92,57 @@ pub struct PasswordPrompt<'a> {
pub sent: bool,
}
pub struct PasswordBar<'a> {
pub struct PasswordPopup<'a> {
pub asking: &'a PasswordPrompt<'a>,
pub palette: &'a Palette,
pub glyphs: &'a Glyphs,
}
impl Widget for PasswordBar<'_> {
fn render(self, area: Rect, buf: &mut Buffer) {
let status = if self.asking.sent {
format!(" Checking{}", self.glyphs.ellipsis).fg(self.palette.waiting)
impl PasswordPopup<'_> {
const MIN_WIDTH: u16 = 40;
fn input(&self) -> Line<'static> {
if self.asking.sent {
Line::from(format!("Checking{}", self.glyphs.ellipsis).fg(self.palette.waiting))
} else {
format!(" {}_", self.asking.input).fg(self.palette.text)
};
Paragraph::new(Line::from(vec![
self.asking.message.fg(self.palette.running).bold(),
status,
]))
.block(rule(
self.palette,
Line::from(" Password ".fg(self.palette.running)),
))
.render(area, buf);
Line::from(vec![
"> ".fg(self.palette.running),
format!("{}_", self.asking.input).fg(self.palette.text),
])
}
}
fn paragraph(&self) -> Paragraph<'_> {
Paragraph::new(vec![
Line::from(self.asking.message.fg(self.palette.text).bold()),
Line::default(),
self.input(),
])
.wrap(Wrap { trim: false })
.block(
Block::bordered()
.border_style(self.palette.running)
.padding(Padding::horizontal(2))
.title(" Password ".fg(self.palette.running).bold())
.title_bottom(
Line::from(" Enter unlock · Ctrl+U clear ".fg(self.palette.muted))
.right_aligned(),
),
)
}
}
impl Widget for PasswordPopup<'_> {
fn render(self, area: Rect, buf: &mut Buffer) {
buf.set_style(area, Style::new().fg(self.palette.muted));
let paragraph = self.paragraph();
let width = u16::try_from(paragraph.line_width())
.unwrap_or(u16::MAX)
.max(Self::MIN_WIDTH)
.min(area.width);
let height = u16::try_from(paragraph.line_count(width)).unwrap_or(u16::MAX);
let popup = area.centered(Constraint::Length(width), Constraint::Length(height));
Clear.render(popup, buf);
paragraph.render(popup, buf);
}
}