diff --git a/docs/THREAT_MODEL.md b/docs/THREAT_MODEL.md index 9773e46..67ca9f0 100644 --- a/docs/THREAT_MODEL.md +++ b/docs/THREAT_MODEL.md @@ -34,6 +34,18 @@ A signed `prf` frame is shown to people who already have a session with you. App OnionWire never holds spend keys. Optional `ONIONWIRE_WALLET_RPC` talks HTTP Digest to a user-hosted `monero-wallet-rpc` on loopback (`--rpc-login` required; open RPC is refused). A Noise friend can sign any `rcp`; the signature proves who sent the claim, not that a payment happened. `verified=1` only after a conjunctive RPC match: one `get_transfers` row with the same non-empty `txid`, `amount`, and `address`. Incoming `rcp` stays `verified=0` if RPC is down, errors, or no exact row. Subaddress reuse is the user’s wallet policy. +Run it **view-only** (recommended). `/pay` and receipt verification need only +`create_address`/`get_transfers`, which a wallet without a spend key serves +fine; `ONIONWIRE_WALLET_NO_SPEND=1` disables `/tip` locally, before any RPC +dial, and a view-only wallet is detected over RPC (`query_key` +`key_type=spend_key` → `-29`, `WALLET_RPC_ERROR_CODE_WATCH_ONLY`) so `/tip` says +so plainly instead of failing with a raw wallet error. The trade-off is +explicit: an OnionWire instance pointed at a **spend-capable** wallet is a local +spend authority — any process that can read the RPC credentials can move the +balance, and `/tip` gives a chat peer a supported way to ask for a transfer. +Loopback binding is not an authorization boundary. Full setup, view-only wallet +creation, and the credential/loopback reasoning: [WALLET.md](WALLET.md). + ## Backup file is the identity `/backup` writes the identity and Noise static secrets. Treat the file like `onionwire.db`. Restore overwrites self keys and does **not** rewrite the friends table. 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/docs/WALLET.md b/docs/WALLET.md new file mode 100644 index 0000000..7da17bc --- /dev/null +++ b/docs/WALLET.md @@ -0,0 +1,184 @@ +# OnionWire + monero-wallet-rpc + +OnionWire is not a wallet. It never holds a seed, a spend key, or a view key. +It talks optional JSON-RPC to a `monero-wallet-rpc` that **you** run, on +loopback, only to: + +- hand out a receive subaddress for `/pay` invoices (`create_address`), +- read incoming transfers to verify a peer's receipt (`get_transfers`), +- and — only if you let it — spend for `/tip` (`transfer`). + +**Run it view-only, and switch `/tip` off explicitly.** Everything else in this +document explains why, and what breaks when you do. + +## Env vars + +| Variable | Meaning | +|---|---| +| `ONIONWIRE_WALLET_RPC` | `http://[user:pass@]host[:port][/path]`. Unset → no wallet; chat still works and `/pay` falls back to the profile `xmr_addr`. | +| `ONIONWIRE_WALLET_RPC_LOGIN` | `user:pass` when you do not want the password in the URL. Ignored if the URL carries userinfo. | +| `ONIONWIRE_WALLET_NO_SPEND` | `1` / `true` / `yes` / `on` → view-only deployment: `/tip` is refused locally, before any RPC dial. `/pay` and receipt verification keep working. | + +`README.md` carries the operator summary; this file is the long form. + +## Recommended topology + +``` + wallet host (this machine) + ┌──────────────────────────────────────────────────────────────┐ + │ monero-wallet-rpc --rpc-bind-ip 127.0.0.1 --rpc-login u:p │ + │ ▲ HTTP Digest, loopback only │ + │ │ │ + │ OnionWire (ONIONWIRE_WALLET_NO_SPEND=1) ── /pay, receipts │ + │ └── /tip refused locally │ + └──────────────────────────────────────────────────────────────┘ +``` + +Loopback is the only address OnionWire will dial. `.onion` RPC URLs are +rejected: there is no Arti dial for the wallet, and a remote wallet would move +your key material off the box. + +## Create a view-only wallet + +Either path produces a wallet file with the view key only. Keep the seed / +spend key on a machine that is **not** running OnionWire. + +With `monero-wallet-cli` (`--generate-from-view-key` prompts for the *standard* +address the view key belongs to, then the secret view key): + +```bash +monero-wallet-cli --generate-from-view-key "$HOME/.onionwire-viewonly" \ + --daemon-address "$YOUR_MONEROD:18089" --restore-height "$BIRTH_HEIGHT" +# Standard address: 4... +# Secret view key: +``` + +Or through a running RPC that was started with `--wallet-dir` (`generate_from_keys` +without `spendkey` writes a watch-only wallet): + +```bash +curl -u onionwire:secret http://127.0.0.1:18083/json_rpc \ + -H 'Content-Type: application/json' \ + -d '{"jsonrpc":"2.0","id":"0","method":"generate_from_keys","params":{ + "filename":"viewonly","password":"walletpass", + "address":"4...","viewkey":"","restore_height":}}' +# → "Watch-only wallet has been generated successfully." +``` + +Then serve it: + +```bash +monero-wallet-rpc --wallet-file "$HOME/.onionwire-viewonly" \ + --rpc-bind-ip 127.0.0.1 --rpc-bind-port 18083 --rpc-login onionwire:secret \ + --daemon-address "$YOUR_MONEROD:18089" + +export ONIONWIRE_WALLET_RPC=http://127.0.0.1:18083 +export ONIONWIRE_WALLET_RPC_LOGIN=onionwire:secret +export ONIONWIRE_WALLET_NO_SPEND=1 +``` + +Restore the wallet from a height *at or before* its first incoming transaction +— a view-only wallet cannot rescan cheaply from height 0. + +## What works, what does not + +| Feature | View-only | Spend-capable | +|---|---|---| +| `/pay ` invoice subaddress (`create_address`) | works | works | +| Receipt verification (`get_transfers`) | works | works | +| Profile `xmr_addr` fallback when RPC is down | works | works | +| `/tip ` (`transfer`) | **cannot work** | works | +| OnionWire learns your spend key | never | never (it stays in the wallet) | + +With `ONIONWIRE_WALLET_NO_SPEND=1` a `/tip` is refused before the RPC is +contacted, with: + +``` +wallet is in view-only/no-spend mode — /tip is disabled; /pay and receipt verification still work +``` + +Without the flag, `/tip` against a view-only wallet fails at the wallet and +OnionWire then asks the wallet directly whether it can spend (see below), so you +get the same sentence instead of a raw RPC error. + +## How OnionWire detects view-only over RPC + +The signal people usually reach for is `query_key` with `key_type=mnemonic`. It +works, but it is the wrong key to ask for: on a spend-capable wallet it hands +over the whole seed (full spend ability) over loopback HTTP, and it answers +`-43` for wallets that have no mnemonic at all. The spend key is narrower and +just as unambiguous: + +``` +query_key {"key_type":"spend_key"} + spend-capable → result.key = + view-only → error code -29, "The wallet is watch-only. Cannot retrieve spend key." +``` + +(`query_key key_type=mnemonic` returns `-29` for a view-only wallet too, so the +two agree — OnionWire asks for the spend key because it is the smaller secret.) + +- Method: [`query_key`](https://www.getmonero.org/resources/developer-guides/wallet-rpc.html#query_key) +- `-29` is `WALLET_RPC_ERROR_CODE_WATCH_ONLY` in + [`wallet_rpc_server_error_codes.h`](https://github.com/monero-project/monero/blob/master/src/wallet/wallet_rpc_server_error_codes.h) +- The view-only branch is `on_query_key` in + [`wallet_rpc_server.cpp`](https://github.com/monero-project/monero/blob/master/src/wallet/wallet_rpc_server.cpp) + +OnionWire only calls this **after** a `transfer` has already failed — it never +probes a healthy wallet — and it discards `result.key` immediately. There is no +RPC method that reports "view-only" as a plain field; `query_key` is the +documented signal and this is its only cost: a spend-capable wallet answers with +its spend key over loopback HTTP, which is one more reason to run view-only. + +Fail-closed details: if the probe cannot answer (wallet down, `--restricted-rpc` +answers `-7 DENIED` instead), OnionWire surfaces the wallet's own error +unchanged. It never guesses "view-only" from an unrelated failure. + +## Why loopback still needs authentication + +`--rpc-bind-ip 127.0.0.1` keeps the port off the network; it does **not** keep it +away from other users or processes on the same machine. Any local process can +`connect(127.0.0.1:18083)`. + +- OnionWire refuses an RPC that answers HTTP 200 without a Digest challenge, and + refuses URLs without credentials. Unset the credentials and the wallet is open + to every local process — with a spend-capable wallet file, that is a + one-curl drain of your balance. +- `--rpc-login` is HTTP Digest (MD5), so the password is not sent in cleartext, + but Digest gives no confidentiality: a local attacker who can sniff loopback + can replay it. Treat loopback as trusted-ish, not safe. +- Do not log the password, and do not put it in a shell history you share. + Prefer `ONIONWIRE_WALLET_RPC_LOGIN` over userinfo in the URL. + +## The spend-authority warning + +An OnionWire instance pointed at a **spend-capable** `monero-wallet-rpc` is a +local spend authority: any process that can read the RPC credentials (env var, +`/proc//environ`, shell history, a stored URL) can spend the wallet's +balance, and `/tip` gives a chat peer a supported path to ask for a transfer. + +That is why view-only plus `ONIONWIRE_WALLET_NO_SPEND=1` is the recommended +default: + +- the wallet file holds no spend key, so a stolen wallet file cannot be used to + move funds; +- the RPC credentials grant only receive-address and history reads; +- `/tip` fails locally with a plain message, so nothing in the UI pretends the + spend path exists. + +If you want tips to work, understand that you are deliberately making the +OnionWire process able to spend. Give it a **separate hot wallet with a small +balance**, not your savings wallet. + +## References + +- Monero Wallet RPC reference: + +- `on_query_key` (view-only → `-29`): + +- `WALLET_RPC_ERROR_CODE_WATCH_ONLY = -29`: + +- `--generate-from-view-key` (incoming-only wallet): + +- `generate_from_keys` (watch-only when `spendkey` is omitted): + 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/src/wallet.rs b/src/wallet.rs index 9dd574f..844d053 100644 --- a/src/wallet.rs +++ b/src/wallet.rs @@ -41,8 +41,18 @@ impl std::fmt::Debug for Endpoint { #[derive(Debug, Clone)] pub struct Wallet { endpoint: Option, + no_spend: bool, } +/// What /tip says when the wallet cannot spend. Same text for the explicit +/// `ONIONWIRE_WALLET_NO_SPEND=1` switch and for a view-only wallet detected over +/// RPC, so the operator never has to guess which one it was. +const VIEW_ONLY_MSG: &str = "wallet is in view-only/no-spend mode — /tip is disabled; /pay and receipt verification still work"; + +/// `WALLET_RPC_ERROR_CODE_WATCH_ONLY` in monero's +/// `src/wallet/wallet_rpc_server_error_codes.h`. +const WATCH_ONLY_CODE: i64 = -29; + #[derive(Debug, Clone, PartialEq, Eq)] pub struct TransferRow { pub txid: String, @@ -54,10 +64,17 @@ const RPC_TIMEOUT: Duration = Duration::from_secs(5); impl Wallet { pub fn disabled() -> Self { - Self { endpoint: None } + Self { + endpoint: None, + no_spend: false, + } } + /// `ONIONWIRE_WALLET_NO_SPEND=1` asks for a view-only deployment: `/tip` is + /// refused locally, before any RPC dial. `/pay` and receipt verification + /// keep working. pub fn from_env() -> Self { + let no_spend = env_flag("ONIONWIRE_WALLET_NO_SPEND"); match std::env::var("ONIONWIRE_WALLET_RPC") { Ok(s) if !s.trim().is_empty() => { let login = std::env::var("ONIONWIRE_WALLET_RPC_LOGIN") @@ -67,23 +84,41 @@ impl Wallet { match parse_http_url(s.trim(), login.as_deref()) { Ok(endpoint) => Self { endpoint: Some(endpoint), + no_spend, }, Err(e) => { eprintln!("ONIONWIRE_WALLET_RPC: {e}"); - Self::disabled() + Self { + endpoint: None, + no_spend, + } } } } - _ => Self::disabled(), + _ => Self { + endpoint: None, + no_spend, + }, } } pub fn from_url(url: &str) -> Result { Ok(Self { endpoint: Some(parse_http_url(url, None)?), + no_spend: false, }) } + /// No-spend (view-only) mode. Same switch as `ONIONWIRE_WALLET_NO_SPEND`. + pub fn with_no_spend(mut self, on: bool) -> Self { + self.no_spend = on; + self + } + + pub fn no_spend(&self) -> bool { + self.no_spend + } + pub fn configured(&self) -> bool { self.endpoint.is_some() } @@ -103,7 +138,10 @@ impl Wallet { } pub async fn transfer(&self, address: &str, amount: u64) -> Result { - let v = self + if self.no_spend { + return Err(Error(VIEW_ONLY_MSG.into())); + } + let sent = self .rpc( "transfer", serde_json::json!({ @@ -111,10 +149,36 @@ impl Wallet { "account_index": 0 }), ) - .await?; + .await; + let v = match sent { + Ok(v) => v, + // The wallet's own refusal is opaque, so ask the documented + // pre-transfer signal before surfacing it. Fail closed: if the + // probe cannot answer, the original error stands. + Err(e) => { + if self.view_only().await { + return Err(Error(VIEW_ONLY_MSG.into())); + } + return Err(e); + } + }; json_str(&v, "tx_hash") } + /// View-only detection over RPC: `query_key` with `key_type=spend_key` is + /// the signal monero actually exposes for a wallet with no spend key. + /// A view-only wallet answers `WALLET_RPC_ERROR_CODE_WATCH_ONLY` (-29) + /// ("Cannot retrieve spend key"); a spend-capable wallet returns the key, + /// which this discards. + /// Source: `src/wallet/wallet_rpc_server.cpp` `on_query_key`. + async fn view_only(&self) -> bool { + matches!( + self.rpc("query_key", serde_json::json!({"key_type": "spend_key"})) + .await, + Err(e) if e.to_string() == VIEW_ONLY_MSG + ) + } + pub async fn get_transfers(&self) -> Result> { let v = self .rpc( @@ -185,6 +249,17 @@ fn credentials_required() -> Error { Error("wallet RPC requires credentials (user:pass in URL or ONIONWIRE_WALLET_RPC_LOGIN)".into()) } +/// `1` / `true` / `yes` / `on` (case-insensitive) mean set; anything else (or +/// unset) means off. +fn env_flag(name: &str) -> bool { + matches!( + std::env::var(name) + .map(|v| v.trim().to_ascii_lowercase()) + .as_deref(), + Ok("1" | "true" | "yes" | "on") + ) +} + fn parse_login(login: &str) -> Result<(String, String)> { let (user, pass) = login.split_once(':').ok_or_else(credentials_required)?; if user.is_empty() || pass.is_empty() { @@ -449,6 +524,11 @@ fn parse_json_rpc(raw: &[u8]) -> Result { .get("message") .and_then(|m| m.as_str()) .unwrap_or("rpc error"); + // The one RPC-level error we translate: a view-only wallet has no + // spend key (monero `WALLET_RPC_ERROR_CODE_WATCH_ONLY`). + if err.get("code").and_then(|c| c.as_i64()) == Some(WATCH_ONLY_CODE) { + return Err(Error(VIEW_ONLY_MSG.into())); + } return Err(Error(msg.into())); } json.get("result") 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") }; +} diff --git a/tests/wallet.rs b/tests/wallet.rs index 097c009..1d4a451 100644 --- a/tests/wallet.rs +++ b/tests/wallet.rs @@ -1,5 +1,7 @@ //! M8: optional monero-wallet-rpc JSON client. Mock TCP only — no live monerod. +use std::sync::{Arc, Mutex}; + use ed25519_dalek::SigningKey; use onionwire::pay; use onionwire::wallet::{self, TransferRow, Wallet}; @@ -8,6 +10,10 @@ use rand::rngs::OsRng; use tokio::io::{AsyncReadExt, AsyncWriteExt}; use tokio::net::TcpListener; +/// `ONIONWIRE_WALLET_NO_SPEND` is process-wide; tests that touch env serialize. +static ENV_LOCK: Mutex<()> = Mutex::new(()); + + fn row(txid: &str, amount: &str, address: &str) -> TransferRow { TransferRow { txid: txid.into(), @@ -241,6 +247,233 @@ async fn oversized_rpc_response_is_err() { ); } +/// Records every request the client sends, answers the Digest challenge and +/// then replies per RPC method. Lets a test assert on the *request log*. +async fn serve_recording( + listener: TcpListener, + log: Arc>>, + reply: Arc String + Send + Sync>, +) { + loop { + let Ok((mut sock, _)) = listener.accept().await else { + return; + }; + let mut buf = vec![0u8; 8192]; + let n = sock.read(&mut buf).await.unwrap_or(0); + let req = String::from_utf8_lossy(&buf[..n]).to_string(); + log.lock().expect("log").push(req.clone()); + if req.contains("Authorization:") { + let body = reply(&rpc_method(&req)); + let _ = sock.write_all(http_200_body(&body).as_bytes()).await; + } else { + let _ = sock.write_all(digest_401().as_bytes()).await; + } + } +} + +fn rpc_method(req: &str) -> String { + let body = req.split_once("\r\n\r\n").map(|(_, b)| b).unwrap_or(req); + serde_json::from_str::(body.trim()) + .ok() + .and_then(|v| v.get("method").and_then(|m| m.as_str()).map(str::to_string)) + .unwrap_or_default() +} + +fn http_200_body(body: &str) -> String { + format!( + "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", + body.len() + ) +} + +fn rpc_error(code: i64, message: &str) -> String { + format!(r#"{{"jsonrpc":"2.0","id":"0","error":{{"code":{code},"message":"{message}"}}}}"#) +} + +/// JSON-RPC body only (the server wraps it in an HTTP 200). +fn rpc_result(result: &str) -> String { + format!(r#"{{"jsonrpc":"2.0","id":"0","result":{result}}}"#) +} + +fn recording_wallet(port: u16) -> Wallet { + Wallet::from_url(&format!("http://ow:secret@127.0.0.1:{port}")).expect("url") +} + +/// The wallet mock speaks the two methods `/tip` can reach, and refuses the +/// local `transfer` before any socket is opened. +#[tokio::test] +async fn no_spend_mode_refuses_transfer_with_no_rpc_request() { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let port = listener.local_addr().unwrap().port(); + let log = Arc::new(Mutex::new(Vec::new())); + tokio::spawn(serve_recording( + listener, + Arc::clone(&log), + Arc::new(|_| rpc_result(r#"{"tx_hash":"abc123"}"#)), + )); + let w = recording_wallet(port).with_no_spend(true); + assert!(w.no_spend()); + let err = w + .transfer( + "8BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB", + 1, + ) + .await + .unwrap_err() + .to_string(); + assert!( + err.to_ascii_lowercase().contains("view-only"), + "got {err}" + ); + tokio::time::sleep(std::time::Duration::from_millis(200)).await; + let seen = log.lock().expect("log").clone(); + assert!(seen.is_empty(), "no RPC request may be made: {seen:?}"); + // Positive control: the recorder is live, so the emptiness above is real. + let _ = w.get_address().await; + assert!(!log.lock().expect("log").is_empty(), "recorder saw nothing"); +} + +/// `/pay` (subaddress) and receipt verification (`get_transfers`) keep working +/// with the no-spend flag on — only `transfer` is refused. +#[tokio::test] +async fn no_spend_mode_keeps_invoice_and_receipt_paths_working() { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let port = listener.local_addr().unwrap().port(); + let log = Arc::new(Mutex::new(Vec::new())); + tokio::spawn(serve_recording( + listener, + Arc::clone(&log), + Arc::new(|method| match method { + "create_address" => rpc_result( + r#"{"address":"8BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB"}"#, + ), + "get_transfers" => rpc_result( + r#"{"in":[{"txid":"deadbeef","amount":5,"address":"8BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB"}],"pending":[]}"#, + ), + _ => rpc_result(r#"{}"#), + }), + )); + let w = recording_wallet(port).with_no_spend(true); + let created = w.create_address().await.expect("create_address"); + assert!(created.starts_with('8'), "got {created}"); + let rows = w.get_transfers().await.expect("get_transfers"); + assert!(wallet::transfers_match(&rows, "deadbeef", "5", &created)); + let seen = log.lock().expect("log").clone(); + assert!( + seen.iter() + .any(|r| r.contains("\"method\":\"create_address\"")), + "recorder must have seen the invoice path: {seen:?}" + ); + assert!( + !seen.iter().any(|r| r.contains("\"method\":\"transfer\"")), + "transfer must never be dialed in no-spend mode" + ); +} + +/// A view-only wallet refuses `transfer` with its own opaque error. The +/// pre-transfer signal is `query_key` key_type=spend_key (Monero answers +/// WALLET_RPC_ERROR_CODE_WATCH_ONLY = -29), so /tip must say so plainly. +#[tokio::test] +async fn view_only_wallet_maps_transfer_failure_to_clear_message() { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let port = listener.local_addr().unwrap().port(); + let log = Arc::new(Mutex::new(Vec::new())); + tokio::spawn(serve_recording( + listener, + Arc::clone(&log), + Arc::new(|method| match method { + "query_key" => rpc_error(-29, "The wallet is watch-only. Cannot retrieve spend key."), + _ => rpc_error(-18, "No transaction created"), + }), + )); + let w = recording_wallet(port); + assert!(!w.no_spend()); + let err = w + .transfer( + "8BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB", + 1, + ) + .await + .unwrap_err() + .to_string(); + assert!(err.to_ascii_lowercase().contains("view-only"), "got {err}"); + let seen = log.lock().expect("log").clone(); + assert!( + seen.iter().any(|r| r.contains("\"method\":\"query_key\"")), + "must ask the RPC-side signal: {seen:?}" + ); +} + +/// A spend-capable wallet must keep its real error: no fabricated detection. +#[tokio::test] +async fn spend_capable_wallet_keeps_the_original_transfer_error() { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let port = listener.local_addr().unwrap().port(); + tokio::spawn(serve_recording( + listener, + Arc::new(Mutex::new(Vec::new())), + Arc::new(|method| match method { + "query_key" => rpc_result(r#"{"key":"00112233"}"#), + _ => rpc_error(-18, "No transaction created"), + }), + )); + let err = recording_wallet(port) + .transfer( + "8BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB", + 1, + ) + .await + .unwrap_err() + .to_string(); + assert!(err.contains("No transaction created"), "got {err}"); + assert!(!err.to_ascii_lowercase().contains("view-only"), "got {err}"); +} + +/// F5 must not regress: an open RPC (HTTP 200, no Digest challenge) is refused. +#[tokio::test] +async fn open_rpc_without_digest_challenge_is_still_refused() { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let port = listener.local_addr().unwrap().port(); + let canned = http_200_body( + r#"{"jsonrpc":"2.0","id":"0","result":{"address":"4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"}}"#, + ); + tokio::spawn(async move { + let (mut sock, _) = listener.accept().await.expect("accept"); + let mut buf = vec![0u8; 4096]; + let _ = sock.read(&mut buf).await; + let _ = sock.write_all(canned.as_bytes()).await; + }); + let err = recording_wallet(port) + .get_address() + .await + .unwrap_err() + .to_string(); + assert!(err.to_ascii_lowercase().contains("digest"), "got {err}"); +} + +/// `ONIONWIRE_WALLET_NO_SPEND` is the operator-facing switch. +#[test] +fn from_env_reads_no_spend_flag() { + let _guard = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + unsafe { + std::env::set_var("ONIONWIRE_WALLET_RPC", "http://ow:secret@127.0.0.1:18083"); + std::env::set_var("ONIONWIRE_WALLET_NO_SPEND", "1"); + } + let on = Wallet::from_env(); + assert!(on.no_spend(), "flag 1 must mean no-spend"); + unsafe { std::env::set_var("ONIONWIRE_WALLET_NO_SPEND", "true") }; + assert!(Wallet::from_env().no_spend(), "\"true\" must mean no-spend"); + for off in ["0", "no", "off"] { + unsafe { std::env::set_var("ONIONWIRE_WALLET_NO_SPEND", off) }; + assert!(!Wallet::from_env().no_spend(), "{off} must be off"); + } + unsafe { + std::env::remove_var("ONIONWIRE_WALLET_NO_SPEND"); + std::env::remove_var("ONIONWIRE_WALLET_RPC"); + } + assert!(!Wallet::from_env().no_spend(), "unset must be off"); +} + fn digest_401() -> String { "HTTP/1.1 401 Unauthorized\r\nWWW-Authenticate: Digest realm=\"monero-rpc\", nonce=\"abcnonce\", qop=\"auth\", algorithm=MD5\r\nContent-Length: 0\r\nConnection: close\r\n\r\n".into() }