From 35b8caa716df6f705e12e378dc37ef2dee5ec235 Mon Sep 17 00:00:00 2001 From: Sirius DevOps Date: Sat, 12 Sep 2026 00:54:16 -0400 Subject: [PATCH 1/2] feat(tui): ASCII chrome, invite wrap, alert truncate, remaining copy ONIONWIRE_ASCII (and NO_COLOR) switches truncation to ... and ASCII borders. Share/paste wrap at : so a mouse-copy cannot lose a mid-hex line. Alerts truncate to the frame; empty threads and paste errors keep the next-step hint. Skip the optional 40-row wordmark. --- docs/TUI.md | 60 ++++++++++++++++ src/tui.rs | 122 +++++++++++++++++++++++++++----- tests/tui_spec.rs | 173 +++++++++++++++++++++++++++++++++++++++++++++- 3 files changed, 337 insertions(+), 18 deletions(-) diff --git a/docs/TUI.md b/docs/TUI.md index 925d351..40e82e5 100644 --- a/docs/TUI.md +++ b/docs/TUI.md @@ -510,3 +510,63 @@ add it on this card. Preferred: depend on `unicode-width` explicitly and assert `tests/tui_frames.rs` `chars_count_is_not_terminal_cells` documents the three examples without adding a crate. + +## After frames (spacing / ASCII / wrap / copy) + +Base: `origin/main` after PR #24 (`33beede`). Hierarchy, fail-closed footer, +1-line header, roster width, help overlay, and `NO_COLOR` palette are unchanged +here. Optional 3-line wordmark at height ≥ 40 was skipped (it fights the 1-line +header without buying hierarchy). + +### 80x24 — `draw_share` after (field-boundary wrap) + +Invite lines break on `:`. `sig=` hex that does not fit continues as an +all-hex line. Joining those lines (no extra spaces) is the original payload. + +``` +┌(o) invite────────────────────────────────────────────────────────────────────┐ +│give this string to a friend; they F3 paste it │ +│ │ +│fp ea4a6c63… │ +│onion abcdefghijklmnopqrstuvwxyz234567abcdefghijklmnopqrstuvwx.onion │ +│ │ +│onionwire:v1: │ +│k=ea4a6c63e29c520abef5507b132ec5f9954776aebebe7b92421eea691446d22c: │ +│o=abcdefghijklmnopqrstuvwxyz234567abcdefghijklmnopqrstuvwx.onion: │ +│spk=0101010101010101010101010101010101010101010101010101010101010101: │ +│sig=46caf16b6da95e86bf93a6ee80605ec74d9e24a419c4ef802632af74f46406fae9953690e0│ +│5401b0af934cefea617f71466f406af4bef956847200a8e915190b │ +└──────────────────────────────────────────────────────────────────────────────┘ +``` + +### 80x24 — ASCII switch (`ONIONWIRE_ASCII=1`) + +No non-ASCII byte. Truncation marker is `...`. Borders are `+` `-` `|`. + +``` ++(o) invite--------------------------------------------------------------------+ +|give this string to a friend; they F3 paste it | +| | +|fp ea4a6c63... | +|onion abcdefghijklmnopqrstuvwxyz234567abcdefghijklmnopqrstuvwx.onion | +| | +|onionwire:v1: | +|k=ea4a6c63e29c520abef5507b132ec5f9954776aebebe7b92421eea691446d22c: | +|o=abcdefghijklmnopqrstuvwxyz234567abcdefghijklmnopqrstuvwx.onion: | +|spk=0101010101010101010101010101010101010101010101010101010101010101: | +|sig=46caf16b6da95e86bf93a6ee80605ec74d9e24a419c4ef802632af74f46406fae9953690e0| +|5401b0af934cefea617f71466f406af4bef956847200a8e915190b | ++------------------------------------------------------------------------------+ +``` + +### 80x24 / 120x40 — main chrome after + +Same 1-line header, unboxed composer, fail-closed footer as PR #24. Dump: + +``` +cargo test --locked --test tui_spec -- --nocapture dump_spec_frames +``` + +Copy wired in `src/tui.rs` (not in the reconstructed standin): empty thread is +`no messages` / `type below, Enter sends`; paste error is `{err}` then +`Enter resubmits Esc back`; alerts truncate to the frame width. diff --git a/src/tui.rs b/src/tui.rs index 2ce2eab..20eb4b6 100644 --- a/src/tui.rs +++ b/src/tui.rs @@ -5,6 +5,7 @@ use std::time::Duration; use ratatui::crossterm::event::{self, Event, KeyCode, KeyEvent, KeyEventKind, KeyModifiers}; use ratatui::layout::{Constraint, Layout, Rect}; use ratatui::style::{Color, Modifier, Style}; +use ratatui::symbols::border; use ratatui::widgets::{Block, Borders, Clear, List, ListItem, ListState, Paragraph, Wrap}; use ratatui::{DefaultTerminal, Frame}; @@ -38,8 +39,90 @@ fn color_mode() -> ColorMode { } } +/// ASCII chrome when `ONIONWIRE_ASCII` or `NO_COLOR` is set. No extra crate. +pub fn ascii_chrome() -> bool { + std::env::var_os("ONIONWIRE_ASCII").is_some() || std::env::var_os("NO_COLOR").is_some() +} + +const ASCII_BORDERS: border::Set = border::Set { + top_left: "+", + top_right: "+", + bottom_left: "+", + bottom_right: "+", + vertical_left: "|", + vertical_right: "|", + horizontal_top: "-", + horizontal_bottom: "-", +}; + fn ellipsis() -> &'static str { - "…" + if ascii_chrome() { "..." } else { "…" } +} + +/// Truncate or keep an alert so it cannot spill into the roster row. +pub fn alert_line(msg: &str, width: u16) -> String { + let mut text = msg.to_string(); + if color_mode() == ColorMode::None && !text.starts_with("! ") { + text = format!("! {text}"); + } + truncate_chars(&text, width as usize) +} + +/// Wrap an invite at `:` so a mouse-copy cannot lose a mid-hex continuation. +/// Joining the lines (no extra spaces) reconstructs `payload`. +pub fn wrap_invite(payload: &str, width: usize) -> String { + if width == 0 { + return String::new(); + } + let mut lines: Vec = Vec::new(); + let mut cur = String::new(); + let parts: Vec<&str> = payload.split(':').collect(); + for (i, part) in parts.iter().enumerate() { + let piece = if i + 1 < parts.len() { + format!("{part}:") + } else { + (*part).to_string() + }; + for chunk in char_chunks(&piece, width) { + if cur.is_empty() { + cur = chunk; + } else if char_len(&cur) + char_len(&chunk) <= width { + cur.push_str(&chunk); + } else { + lines.push(std::mem::take(&mut cur)); + cur = chunk; + } + } + } + if !cur.is_empty() { + lines.push(cur); + } + lines.join("\n") +} + +fn char_chunks(s: &str, width: usize) -> Vec { + if width == 0 { + return Vec::new(); + } + if char_len(s) <= width { + return vec![s.to_string()]; + } + let chars: Vec = s.chars().collect(); + chars.chunks(width).map(|c| c.iter().collect()).collect() +} + +/// Friend selected, no messages yet. +pub fn empty_friend_chat_text() -> &'static str { + "no messages\ntype below, Enter sends" +} + +/// Paste overlay copy. Error keeps the resubmit hint. +pub fn paste_screen_text(buf: &str, err: Option<&str>) -> String { + let hint = match err { + Some(e) => format!("{e}\nEnter resubmits Esc back"), + None => "paste onionwire:v1 payload, Enter to submit".to_string(), + }; + format!("{hint}\n\n{buf}") } fn char_len(s: &str) -> usize { @@ -1429,11 +1512,7 @@ impl App { f.render_widget(Paragraph::new(header).style(style_accent()), cols[0]); if let Some(msg) = &self.alert { - let text = if color_mode() == ColorMode::None && !msg.starts_with("! ") { - format!("! {msg}") - } else { - msg.clone() - }; + let text = alert_line(msg, area.width); f.render_widget(Paragraph::new(text).style(style_alert()), cols[1]); } @@ -1559,7 +1638,10 @@ impl App { ]; }; match self.node.list_messages(&friend.pubkey) { - Ok(msgs) if msgs.is_empty() => vec!["no messages".into()], + Ok(msgs) if msgs.is_empty() => empty_friend_chat_text() + .lines() + .map(str::to_string) + .collect(), Ok(msgs) => msgs .iter() .map(|m| { @@ -1583,8 +1665,7 @@ impl App { } else { style_dim() }; - Block::default() - .borders(Borders::ALL) + apply_chrome_borders(Block::default()) .border_style(border) .title(title) .title_style(title_style) @@ -1699,9 +1780,17 @@ fn footer_hints(screen: &Screen) -> &'static str { } } +fn apply_chrome_borders(block: Block<'_>) -> Block<'_> { + let block = block.borders(Borders::ALL); + if ascii_chrome() { + block.border_set(ASCII_BORDERS) + } else { + block + } +} + fn themed_block(title: &str) -> Block<'_> { - Block::default() - .borders(Borders::ALL) + apply_chrome_borders(Block::default()) .border_style(style_accent()) .title(title) .title_style(style_accent().add_modifier(Modifier::BOLD)) @@ -1712,8 +1801,10 @@ pub fn draw_share(f: &mut Frame, payload: &str) { Ok(p) => (truncate_fp(&to_hex(&p.pubkey)), p.onion), Err(_) => ("?".into(), "?".into()), }; + let inner = f.area().width.saturating_sub(2) as usize; + let invite = wrap_invite(payload, inner.max(1)); let body = format!( - "give this string to a friend; they F3 paste it\n\nfp {fp}\nonion {onion}\n\n{payload}" + "give this string to a friend; they F3 paste it\n\nfp {fp}\nonion {onion}\n\n{invite}" ); f.render_widget( Paragraph::new(body) @@ -1725,10 +1816,9 @@ pub fn draw_share(f: &mut Frame, payload: &str) { } fn draw_paste(f: &mut Frame, buf: &str, err: Option<&str>) { - let hint = err - .unwrap_or("paste onionwire:v1 payload, Enter to submit") - .to_string(); - let body = format!("{hint}\n\n{buf}"); + let inner = f.area().width.saturating_sub(2) as usize; + let shown = wrap_invite(buf, inner.max(1)); + let body = paste_screen_text(&shown, err); let style = if err.is_some() { style_alert() } else { diff --git a/tests/tui_spec.rs b/tests/tui_spec.rs index b29270f..2310487 100644 --- a/tests/tui_spec.rs +++ b/tests/tui_spec.rs @@ -1,17 +1,21 @@ //! Spec implementation tests for docs/TUI.md (this card). //! Does not own `tests/tui_frames.rs` (PR #23). +use onionwire::qr; use onionwire::tui::{ - draw_text_overlay, help_overlay_text, main_footer_hints, main_header_line, roster_col_width, - status_footer, + alert_line, ascii_chrome, draw_share, draw_text_overlay, empty_friend_chat_text, + help_overlay_text, main_footer_hints, main_header_line, paste_screen_text, roster_col_width, + status_footer, wrap_invite, }; use ratatui::Frame; use ratatui::Terminal; use ratatui::backend::TestBackend; use ratatui::layout::{Constraint, Layout}; use ratatui::widgets::{Block, Borders, List, ListItem, Paragraph, Wrap}; +use std::sync::Mutex; const FP: &str = "abcdef0123456789deadbeefcafebabe"; +static ASCII_ENV: Mutex<()> = Mutex::new(()); const ONION: &str = "abcdefghijklmnopqrstuvwxyz234567abcdefghijklmnopqrstuvwx.onion"; fn screen_from(buf: &ratatui::buffer::Buffer, w: u16, h: u16) -> String { @@ -179,6 +183,8 @@ fn reconstructed_main_keeps_send_failed_on_footer() { #[test] fn dump_spec_frames() { + let _guard = ASCII_ENV.lock().expect("ascii env lock"); + unsafe { std::env::remove_var("ONIONWIRE_ASCII") }; for (w, h) in [(80u16, 24u16), (120, 40)] { let backend = TestBackend::new(w, h); let mut terminal = Terminal::new(backend).expect("terminal"); @@ -205,5 +211,168 @@ fn dump_spec_frames() { .expect("draw"); println!("===== AFTER help {w}x{h} ====="); print!("{}", screen_from(terminal.backend().buffer(), w, h)); + + let invite = sample_invite(); + let backend = TestBackend::new(w, h); + let mut terminal = Terminal::new(backend).expect("terminal"); + terminal.draw(|f| draw_share(f, &invite)).expect("draw"); + println!("===== AFTER share {w}x{h} ====="); + print!("{}", screen_from(terminal.backend().buffer(), w, h)); } } + +fn sample_invite() -> String { + let sk = [7u8; 32]; + qr::encode(&sk, ONION, &[1u8; 32]).expect("encode") +} + +fn invite_line_ok(line: &str) -> bool { + let t = line.trim(); + t.is_empty() + || t.starts_with("onionwire:") + || t.starts_with("k=") + || t.starts_with("o=") + || t.starts_with("spk=") + || t.starts_with("sig=") + || t.chars().all(|c| c.is_ascii_hexdigit()) +} + +#[test] +fn alert_line_truncates_to_frame_width() { + let long = "passphrases do not match and then a lot more context that would collide with the roster on the next row if left unwrapped"; + let line = alert_line(long, 80); + assert!( + line.chars().count() <= 80, + "alert wider than 80: {} {line:?}", + line.chars().count() + ); + assert!( + line.contains('…') || line.contains("..."), + "long alert was not truncated: {line:?}" + ); + assert!( + !line.contains("roster on the next row"), + "alert still has overflow tail: {line:?}" + ); +} + +#[test] +fn wrap_invite_breaks_on_field_boundaries() { + let invite = sample_invite(); + assert!(invite.len() > 78, "fixture too short to wrap: {invite}"); + let wrapped = wrap_invite(&invite, 78); + for line in wrapped.lines() { + assert!( + line.chars().count() <= 78, + "invite line wider than 78: {} {line:?}", + line.chars().count() + ); + assert!( + invite_line_ok(line), + "invite wrapped mid-token: {line:?}\n{wrapped}" + ); + } + assert!( + wrapped.contains("onionwire:v1:"), + "lost invite prefix:\n{wrapped}" + ); + assert!(wrapped.contains("k="), "lost k= field:\n{wrapped}"); + assert!(wrapped.contains("spk="), "lost spk= field:\n{wrapped}"); + let joined: String = wrapped.lines().map(str::trim).collect(); + assert_eq!( + joined, invite, + "wrap must be newline-joinable back to payload" + ); +} + +#[test] +fn draw_share_invite_does_not_wrap_mid_token() { + let invite = sample_invite(); + let backend = TestBackend::new(80, 24); + let mut terminal = Terminal::new(backend).expect("terminal"); + terminal.draw(|f| draw_share(f, &invite)).expect("draw"); + let screen = screen_from(terminal.backend().buffer(), 80, 24); + assert!( + screen.contains("onionwire:v1:"), + "missing prefix:\n{screen}" + ); + for raw in screen.lines() { + let inner = raw.trim_start_matches(['│', '|', ' ']); + let inner = inner.trim_end_matches(['│', '|', ' ']); + if inner.starts_with("onionwire:") + || inner.starts_with("k=") + || inner.starts_with("o=") + || inner.starts_with("spk=") + || inner.starts_with("sig=") + || inner.chars().all(|c| c.is_ascii_hexdigit()) + { + assert!( + invite_line_ok(inner), + "share pane mid-token wrap: {inner:?}\n{screen}" + ); + } + if inner.starts_with('c') && inner.contains(":o=") { + panic!("share still wraps mid-hex into :o=: {inner:?}\n{screen}"); + } + } +} + +#[test] +fn empty_friend_chat_has_send_hint() { + let text = empty_friend_chat_text(); + assert!(text.contains("no messages"), "{text:?}"); + assert!(text.contains("type below, Enter sends"), "{text:?}"); +} + +#[test] +fn paste_error_keeps_resubmit_hint() { + let body = paste_screen_text("", Some("bad invite")); + assert!(body.contains("bad invite"), "{body:?}"); + assert!(body.contains("Enter resubmits"), "{body:?}"); + assert!(body.contains("Esc back"), "{body:?}"); + let ok = paste_screen_text("onionwire:v1:k=x", None); + assert!( + ok.contains("paste onionwire:v1 payload"), + "happy-path hint lost: {ok:?}" + ); +} + +#[test] +fn ascii_switch_80x24_frame_is_pure_ascii() { + let _guard = ASCII_ENV.lock().expect("ascii env lock"); + unsafe { std::env::set_var("ONIONWIRE_ASCII", "1") }; + assert!( + ascii_chrome(), + "ONIONWIRE_ASCII set but ascii_chrome() is false" + ); + let footer = status_footer(80, FP, ONION, None, main_footer_hints()); + assert!( + footer.contains("..."), + "ASCII truncation marker missing: {footer:?}" + ); + assert!( + !footer.contains('…'), + "unicode ellipsis still in footer: {footer:?}" + ); + + let invite = sample_invite(); + let backend = TestBackend::new(80, 24); + let mut terminal = Terminal::new(backend).expect("terminal"); + terminal.draw(|f| draw_share(f, &invite)).expect("draw"); + let screen = screen_from(terminal.backend().buffer(), 80, 24); + let non_ascii: Vec = screen.chars().filter(|c| !c.is_ascii()).collect(); + assert!( + non_ascii.is_empty(), + "ASCII switch ignored, non-ASCII in 80x24 frame: {non_ascii:?}\n{screen}" + ); + assert!( + screen.contains("..."), + "truncation marker missing from ASCII frame:\n{screen}" + ); + assert!( + screen.contains('+') && screen.contains('|') && screen.contains('-'), + "ASCII borders missing:\n{screen}" + ); + println!("===== AFTER ascii share 80x24 =====\n{screen}"); + unsafe { std::env::remove_var("ONIONWIRE_ASCII") }; +} From f5576e751bad461b3f88b9987e71908d7e7786a1 Mon Sep 17 00:00:00 2001 From: t Date: Sat, 12 Sep 2026 14:06:20 -0400 Subject: [PATCH 2/2] feat(core): zeroize the profile/loc signing copy and the TUI passphrase buffer MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The Ed25519 identity secret was still copied into a bare [u8; 32] on the stack in two signers (profile::sign, loc::sign), and the TUI kept the typed backup/restore passphrase in a plain String for the life of the screen. Both now go through Zeroizing: - profile::signing_key_bytes() builds the 32-byte copy into a Zeroizing<[u8; 32]> (same pattern as pay::sign_bytes / qr::encode, but with copy_from_slice so no Copy temporary is left behind); loc::sign shares the helper instead of making its own copy. - Screen::Passphrase now owns a PassphraseEntry whose buffers are Zeroizing. Every exit path (Enter, mismatch, Esc) calls close(), which wipes both buffers eagerly; a drop — including Ctrl-Q and a panic — is the backstop. Evidence: tests/zeroize.rs gains a drop probe (ManuallyDrop + drop_in_place + read_volatile) on the Zeroizing signing buffer and a length-rejection test; src/tui.rs gains unit tests asserting the buffer types and that close() leaves every byte of the passphrase's heap capacity zeroed. --- src/loc.rs | 7 +- src/profile.rs | 22 +++++- src/tui.rs | 177 ++++++++++++++++++++++++++++++++++++++++------- tests/zeroize.rs | 39 +++++++++++ 4 files changed, 215 insertions(+), 30 deletions(-) diff --git a/src/loc.rs b/src/loc.rs index aa25574..9803f77 100644 --- a/src/loc.rs +++ b/src/loc.rs @@ -23,9 +23,10 @@ pub struct Loc { const PREFIX: &[u8] = b"loc "; pub fn sign(identity_sk: &[u8], onion: &str, ts: i64) -> Result { - let sk_bytes: [u8; 32] = identity_sk - .try_into() - .map_err(|_| Error("identity secret key must be 32 bytes".into()))?; + // Same one-shot raw identity-secret copy as `profile::sign`; shared so + // `Zeroize` covers it here too. + let sk_bytes = + crate::profile::signing_key_bytes(identity_sk).map_err(|e| Error(e.to_string()))?; let sk = SigningKey::from_bytes(&sk_bytes); let sig = sk.sign(&sign_msg_v2(onion, ts)).to_bytes().to_vec(); Ok(Loc { diff --git a/src/profile.rs b/src/profile.rs index a22d0ef..8a8ac24 100644 --- a/src/profile.rs +++ b/src/profile.rs @@ -1,4 +1,5 @@ use ed25519_dalek::{Signature, Signer, SigningKey, Verifier, VerifyingKey}; +use zeroize::Zeroizing; pub type Result = std::result::Result; @@ -30,6 +31,23 @@ pub fn validate(display_name: &str, bio: &str, xmr_addr: &str) -> Result<()> { check_fields(display_name, bio, xmr_addr) } +/// The raw 32-byte identity-secret copy that `ed25519-dalek` needs in order to +/// build a `SigningKey`. +/// +/// `SigningKey` wipes its own copy on drop (its default `zeroize` feature); +/// the raw bytes are ours to wipe, so they live in a `Zeroizing` buffer rather +/// than on the stack in a bare `[u8; 32]`. Same pattern as `pay::sign_bytes` +/// and `qr::encode`; `loc::sign` shares this helper for the identical copy it +/// used to make. +pub fn signing_key_bytes(identity_sk: &[u8]) -> Result> { + if identity_sk.len() != 32 { + return Err(Error("identity secret key must be 32 bytes".into())); + } + let mut bytes = Zeroizing::new([0u8; 32]); + bytes[..].copy_from_slice(identity_sk); + Ok(bytes) +} + pub fn sign( identity_sk: &[u8], display_name: &str, @@ -38,9 +56,7 @@ pub fn sign( ts: i64, ) -> Result { check_fields(display_name, bio, xmr_addr)?; - let sk_bytes: [u8; 32] = identity_sk - .try_into() - .map_err(|_| Error("identity secret key must be 32 bytes".into()))?; + let sk_bytes = signing_key_bytes(identity_sk)?; let sk = SigningKey::from_bytes(&sk_bytes); let sig = sk .sign(&sign_msg_v2(display_name, bio, xmr_addr, ts)) diff --git a/src/tui.rs b/src/tui.rs index 20eb4b6..7589b18 100644 --- a/src/tui.rs +++ b/src/tui.rs @@ -8,6 +8,7 @@ use ratatui::style::{Color, Modifier, Style}; use ratatui::symbols::border; use ratatui::widgets::{Block, Borders, Clear, List, ListItem, ListState, Paragraph, Wrap}; use ratatui::{DefaultTerminal, Frame}; +use zeroize::{Zeroize, Zeroizing}; use crate::node::Node; use crate::qr::{self, QrPayload}; @@ -761,6 +762,78 @@ impl BackupPrompt { } } +/// The in-progress passphrase on the backup/restore screen: the hidden buffer +/// plus the first entry, kept across the second prompt of the backup flow. +/// +/// Both are `Zeroizing`, so the passphrase does not sit in a plain +/// heap `String` for the life of the screen; `close()` wipes eagerly on every +/// exit path (submit, mismatch, cancel) instead of waiting for the screen +/// value to be dropped, and the wrapper covers the paths that cannot call it +/// (Ctrl-Q, a panic). +pub struct PassphraseEntry { + first: Option>, + buf: Zeroizing, +} + +impl Default for PassphraseEntry { + fn default() -> Self { + Self { + first: None, + buf: Zeroizing::new(String::new()), + } + } +} + +impl PassphraseEntry { + pub fn new() -> Self { + Self::default() + } + + /// Second prompt of the backup flow: the first passphrase was already typed. + pub fn with_first(first: &str) -> Self { + Self { + first: Some(Zeroizing::new(first.to_string())), + ..Self::default() + } + } + + pub fn push(&mut self, c: char) { + self.buf.push(c); + } + + pub fn backspace(&mut self) { + self.buf.pop(); + } + + /// What the screen echoes back — the passphrase itself is not drawn. + pub fn buf(&self) -> &str { + self.buf.as_str() + } + + pub fn first(&self) -> Option<&str> { + self.first.as_deref().map(String::as_str) + } + + /// Take the typed passphrase for submission, leaving this entry empty. + pub fn take_buf(&mut self) -> Zeroizing { + std::mem::replace(&mut self.buf, Zeroizing::new(String::new())) + } + + /// Take the first-passphrase copy for the confirm comparison. + pub fn take_first(&mut self) -> Option> { + self.first.take() + } + + /// Wipe both buffers: the screen is done with them. + pub fn close(&mut self) { + self.buf.zeroize(); + if let Some(first) = self.first.as_mut() { + first.zeroize(); + } + self.first = None; + } +} + pub fn backup_screen_text() -> &'static str { "Write encrypted identity backup?\n\ This file is your identity secret. Treat it like the database.\n\ @@ -840,8 +913,7 @@ enum Screen { Passphrase { kind: BackupKind, path: String, - first: Option, - buf: String, + entry: PassphraseEntry, }, Quit { prompt: QuitPrompt, @@ -929,6 +1001,7 @@ impl App { let mut tip_cmd = None; let mut file_cmd = None; let mut chat_send = None; + let mut pass_submit = None; match &mut self.screen { Screen::Main => match key.code { KeyCode::Tab => self.focus = self.focus.next(), @@ -1090,8 +1163,7 @@ impl App { self.screen = Screen::Passphrase { kind, path: path.clone(), - first: None, - buf: String::new(), + entry: PassphraseEntry::new(), }; } } @@ -1101,25 +1173,17 @@ impl App { _ => {} } } - Screen::Passphrase { - kind, - path, - first, - buf, - } => match key.code { - KeyCode::Esc => self.screen = Screen::Main, - KeyCode::Backspace => { - buf.pop(); + Screen::Passphrase { kind, path, entry } => match key.code { + KeyCode::Esc => { + entry.close(); + self.screen = Screen::Main; } + KeyCode::Backspace => entry.backspace(), KeyCode::Enter => { - let kind = *kind; - let path = path.clone(); - let first = first.clone(); - let pass = buf.clone(); - self.submit_passphrase(kind, &path, first.as_deref(), &pass)?; + pass_submit = Some((*kind, path.clone(), entry.take_first(), entry.take_buf())); } KeyCode::Char(c) if !key.modifiers.contains(KeyModifiers::CONTROL) => { - buf.push(c); + entry.push(c); } _ => {} }, @@ -1166,6 +1230,9 @@ impl App { if let Some(text) = chat_send { self.send_chat(&text)?; } + if let Some((kind, path, first, pass)) = pass_submit { + self.submit_passphrase(kind, &path, first.as_deref().map(String::as_str), &pass)?; + } Ok(None) } @@ -1279,8 +1346,7 @@ impl App { self.screen = Screen::Passphrase { kind, path: path.to_string(), - first: Some(pass.to_string()), - buf: String::new(), + entry: PassphraseEntry::with_first(pass), }; } } @@ -1485,9 +1551,9 @@ impl App { Screen::Wipe { kind, prompt } => draw_wipe(f, *kind, prompt.typed()), Screen::Profile { editor } => draw_profile(f, editor), Screen::ConfirmKeys { kind, prompt, .. } => draw_confirm_keys(f, *kind, prompt.typed()), - Screen::Passphrase { - kind, first, buf, .. - } => draw_passphrase(f, *kind, first.is_some(), buf), + Screen::Passphrase { kind, entry, .. } => { + draw_passphrase(f, *kind, entry.first().is_some(), entry.buf()) + } Screen::Quit { prompt } => draw_quit(f, prompt.typed()), } if self.help_open { @@ -2015,3 +2081,66 @@ fn to_hex(bytes: &[u8]) -> String { fn io_err(e: io::Error) -> String { e.to_string() } + +#[cfg(test)] +mod passphrase_buffer_tests { + use super::*; + + fn assert_zeroize_on_drop() {} + + /// The typed passphrase lives in `Zeroizing` buffers, not in bare + /// `String`s that sit in the heap for the life of the screen. + #[test] + fn passphrase_buffers_are_zeroizing() { + let mut entry = PassphraseEntry::new(); + entry.push('x'); + + let _: &Zeroizing = &entry.buf; + let _: &Option> = &entry.first; + assert_zeroize_on_drop::>(); + } + + /// Closing the screen (submit, mismatch or cancel) must leave nothing of + /// the typed passphrase behind in its heap buffer. + #[test] + fn closing_the_passphrase_screen_wipes_the_typed_secret() { + let mut entry = PassphraseEntry::new(); + for c in "hunter2-secret".chars() { + entry.push(c); + } + assert_eq!(entry.buf(), "hunter2-secret"); + + let ptr = entry.buf.as_ptr(); + let cap = entry.buf.capacity(); + assert!(cap >= 14, "expected a heap buffer, capacity {cap}"); + + entry.close(); + + assert!(entry.buf().is_empty(), "buffer not cleared"); + // SAFETY: `close()` wipes through `Zeroize`, which zeroes the whole + // capacity and *keeps* the allocation (`Vec::zeroize`: zero the + // elements, clear the length, zero the spare capacity). `entry` still + // owns that buffer, so these `cap` bytes are live memory. + let bytes = unsafe { std::slice::from_raw_parts(ptr, cap) }; + assert!( + bytes.iter().all(|b| *b == 0), + "typed passphrase survived close(): {bytes:?}" + ); + } + + /// The first entry of the two-step backup flow is a secret too, and the + /// screen holds it across the second prompt. + #[test] + fn closing_the_passphrase_screen_drops_the_first_entry_copy() { + let mut entry = PassphraseEntry::with_first("first-typed"); + assert_eq!(entry.first(), Some("first-typed")); + + entry.close(); + + assert_eq!( + entry.first(), + None, + "first passphrase copy survived close()" + ); + } +} diff --git a/tests/zeroize.rs b/tests/zeroize.rs index 985a77c..ce77a45 100644 --- a/tests/zeroize.rs +++ b/tests/zeroize.rs @@ -5,6 +5,7 @@ //! Noise handshake/transport state that lives inside `snow`. use onionwire::backup::BackupKeys; +use onionwire::profile; use onionwire::session::Keys; use onionwire::wallet::Wallet; use onionwire::Store; @@ -52,6 +53,20 @@ unsafe fn drop_in_place_and_peek_identity_sk(v: &mut Keys) -> [u8; 32] { } } +/// Drops a `Zeroizing<[u8; 32]>` in place and reads its buffer back. +/// +/// SAFETY: only for `ManuallyDrop>` locals — same contract +/// as `drop_in_place_and_peek_identity_sk`. +unsafe fn drop_in_place_and_peek_zeroizing_u8x32(v: &mut Zeroizing<[u8; 32]>) -> [u8; 32] { + let p: *const [u8; 32] = &**v; + // SAFETY: the caller guarantees `v` is dropped exactly once and is still + // alive at its own address when read back. + unsafe { + std::ptr::drop_in_place(v as *mut Zeroizing<[u8; 32]>); + std::ptr::read_volatile(p) + } +} + /// Drop behaviour, not a comment: after the value drops, the local secret key /// material that feeds the Noise IK handshake is gone from its memory. #[test] @@ -116,3 +131,27 @@ fn wallet_endpoint_debug_redacts_the_rpc_password() { ); assert!(dbg.contains(""), "{dbg}"); } + +/// `profile::sign` needs a raw 32-byte copy of the identity secret to build the +/// dalek `SigningKey`. That copy is a `Zeroizing` buffer, not a bare array that +/// stays on the stack until the function returns. +#[test] +fn profile_signing_key_bytes_are_zeroizing_and_wipe() { + let secret = [0x5au8; 32]; + let bytes = profile::signing_key_bytes(&secret).expect("32 bytes"); + + let _: &Zeroizing<[u8; 32]> = &bytes; + assert_eq!(&bytes[..], &secret[..], "buffer must hold the secret"); + + let mut probe = std::mem::ManuallyDrop::new(bytes); + let after = unsafe { drop_in_place_and_peek_zeroizing_u8x32(&mut probe) }; + + assert_eq!(after, [0u8; 32], "identity secret survived its drop"); +} + +/// A length-mismatched secret is an error, not a truncated/padded key. +#[test] +fn profile_signing_key_bytes_rejects_a_short_secret() { + assert!(profile::signing_key_bytes(&[7u8; 31]).is_err()); + assert!(profile::signing_key_bytes(&[7u8; 33]).is_err()); +}