diff --git a/android/app/src/main/java/com/siriusdevops/onionwire/WireViewModel.kt b/android/app/src/main/java/com/siriusdevops/onionwire/WireViewModel.kt index 93bc1ef..140c494 100644 --- a/android/app/src/main/java/com/siriusdevops/onionwire/WireViewModel.kt +++ b/android/app/src/main/java/com/siriusdevops/onionwire/WireViewModel.kt @@ -7,7 +7,10 @@ import com.siriusdevops.onionwire.crypto.KeyBacking import com.siriusdevops.onionwire.crypto.KeystorePassphraseCipher import com.siriusdevops.onionwire.crypto.StoreSecret import com.siriusdevops.onionwire.crypto.StoredPassphraseStore +import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.Job +import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow @@ -55,6 +58,14 @@ sealed interface Unlock { data class OneTap(val backing: KeyBacking) : Unlock } +/** + * Teardown work must outlive the ViewModel: `onCleared()` runs *after* + * `viewModelScope` is already cancelled, and stopping the node means draining + * the outbox and stopping Arti, not just dropping a reference. One process-wide + * scope is enough — there is one node per process. + */ +private val TEARDOWN = CoroutineScope(SupervisorJob() + Dispatchers.IO) + /** * Owns the single Wire node for the process. * @@ -87,6 +98,13 @@ class WireViewModel(app: Application) : AndroidViewModel(app) { private var wire: Wire? = null + /** + * The in-flight teardown, if any. Unlocking again has to wait for it: the + * old node holds the sqlite file and Arti's state lock until `shutdown()` + * returns, and racing it makes the new node fail to open. + */ + private var stopping: Job? = null + init { // Probe on a background dispatcher: this touches the Keystore and does // a full GCM decrypt. Doing it here means a killed Keystore key is @@ -143,12 +161,45 @@ class WireViewModel(app: Application) : AndroidViewModel(app) { } } - /** Drops our handle. The onion service stops; nothing is sent after this. */ + /** + * Stops the node and drops our handle. Nothing is sent after this. + * + * Flush first — the outbox is the whole point of losing the process — then + * `shutdown()`, which stops the onion service, aborts the retry worker and + * checkpoints the sqlite WAL. Both calls are on [TEARDOWN] because this + * runs from an `onClick`. + */ fun lock() { + val w = wire ?: return wire = null _friends.value = emptyList() _phase.value = Phase.Locked refreshUnlockState() + stopping = TEARDOWN.launch { stopNode(w) } + } + + /** + * The node must not outlive the UI. Doze and the background-process killer + * skip this entirely (that is what the outbox is for), but a normal finish + * tears Tor down here instead of leaving Arti running behind a dead screen. + */ + override fun onCleared() { + val w = wire + wire = null + if (w != null) stopping = TEARDOWN.launch { stopNode(w) } + super.onCleared() + } + + private suspend fun stopNode(w: Wire) { + // Best effort, both steps: teardown runs on a process-scope job after + // the UI is gone, so there is nobody to show an error to and nothing + // useful to retry. `shutdown()` drains again with a shorter budget, so + // a flush that times out is not fatal. + runCatching { w.flush() } + // A second shutdown — `lock()` and then `onCleared()`, say — lands here + // too: the SDK reports it as a typed WireException.Stopped, never a + // panic, so swallowing it is correct. + runCatching { w.shutdown() } } private fun refreshUnlockState() { @@ -180,13 +231,17 @@ class WireViewModel(app: Application) : AndroidViewModel(app) { * follow-up SDK signature this card cannot make itself. */ private fun openWith(secret: CharArray, storeAfterwards: Boolean) { - if (secret.isEmpty() || _phase.value is Phase.Opening) { + if (secret.isEmpty() || _phase.value is Phase.Opening || wire != null) { StoreSecret.wipe(secret) return } _phase.value = Phase.Opening viewModelScope.launch { try { + // Any previous node must be fully stopped first: the old node + // holds the sqlite file and Arti's state lock until its teardown + // returns, and racing it makes this open fail. + stopping?.join() val w = openWire(home.absolutePath, secret.concatToString()) wire = w if (storeAfterwards) store(secret) diff --git a/crates/onionwire-sdk/src/lib.rs b/crates/onionwire-sdk/src/lib.rs index e90c7fa..90e5b55 100644 --- a/crates/onionwire-sdk/src/lib.rs +++ b/crates/onionwire-sdk/src/lib.rs @@ -13,13 +13,20 @@ //! Orbot pipe. If the onion service cannot publish, this fails closed. //! * Chat bodies are encrypted at rest. Identity keys in sqlite are not. //! +//! Lifecycle: a node is started by [`open_wire`] and stopped by +//! [`Wire::shutdown`]. Between those, [`Wire::tor_state`] is the observable +//! state and [`Wire::flush`] is "deliver what is deliverable now". A process +//! killed by Doze or the background-process killer never runs `shutdown`, which +//! is exactly why queued sends live in sqlite and not in memory. +//! //! The façade deliberately exposes only plain data (records + hex strings) so //! no TUI/ratatui type leaks into the AAR. use std::path::PathBuf; -use std::sync::{Arc, OnceLock}; +use std::sync::{Arc, Mutex, OnceLock}; -use onionwire::node::Node; +use onionwire::hs::TorState as CoreTorState; +use onionwire::node::{FlushOutcome as CoreFlushOutcome, Node}; use onionwire::qr; uniffi::setup_scaffolding!(); @@ -54,6 +61,12 @@ pub fn install_crypto_provider() { pub enum WireError { #[error("{message}")] Failed { message: String }, + /// The node was shut down (or never opened). Distinct from `Failed` so + /// Kotlin can branch on it instead of string-matching a message, and so + /// "you must unlock again" is a different UI state from "the network is + /// broken". + #[error("node stopped: {message}")] + Stopped { message: String }, } impl WireError { @@ -62,6 +75,12 @@ impl WireError { message: e.to_string(), } } + + fn stopped(what: &str) -> Self { + Self::Stopped { + message: format!("{what} called on a shut-down node"), + } + } } type WResult = std::result::Result; @@ -98,10 +117,70 @@ pub struct InviteInfo { pub onion: String, } +/// Observable lifecycle state of the node's onion service. +/// +/// Mirrors Arti's own service status, projected onto the four states a UI +/// actually acts on. It is the same distinction `hs::hs_is_ready` makes when it +/// decides whether the onion is reachable yet. +#[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Enum)] +pub enum TorState { + /// Bootstrap or descriptor upload still in flight. Not reliably reachable. + Bootstrapping, + /// Onion service running and its descriptor published. + Published, + /// Reachable, but Arti reports the service degraded. Usable — worth saying + /// so, not identical to `Published`. + DegradedReachable, + /// Shut down: no onion service, no dials, store checkpointed. Every method + /// on the node now returns `WireError.Stopped`. + Stopped, +} + +impl From for TorState { + fn from(s: CoreTorState) -> Self { + match s { + CoreTorState::Bootstrapping => Self::Bootstrapping, + CoreTorState::Published => Self::Published, + CoreTorState::DegradedReachable => Self::DegradedReachable, + CoreTorState::Stopped => Self::Stopped, + } + } +} + +/// What a [`Wire::flush`] managed to do. +#[derive(Debug, Clone, Copy, uniffi::Record)] +pub struct FlushOutcome { + /// Rows the pass started a delivery for. `0` when the pass hit its time + /// budget before finishing — the rows are still queued, we just stopped + /// counting. + pub attempted: u32, + /// Rows delivered now. A message absent from `remaining` was sent. + pub delivered: u32, + /// Rows still queued or terminally failed afterwards. + pub remaining: u32, +} + /// A running OnionWire node: identity + Arti client + hosted v3 onion service. +/// +/// Holds the node handle. [`Wire::shutdown`] takes it out and drops it, which +/// is what lets the last reference to the Tor client and the store go away — +/// there is no hidden global keeping Arti (or the sqlite connection) alive +/// after the UI is gone. #[derive(uniffi::Object)] pub struct Wire { - inner: Arc, + node: Mutex>>, +} + +impl Wire { + /// The live node, or `Stopped` if this handle was shut down. A poisoned + /// mutex is reported the same way rather than panicking: a caller that sees + /// `Stopped` unlocks again, which is the correct recovery either way. + fn node(&self) -> WResult> { + let guard = self.node.lock().map_err(|_| WireError::Stopped { + message: "node handle lock poisoned by a panic; reopen the identity".to_string(), + })?; + guard.as_ref().cloned().ok_or_else(|| WireError::stopped("this call")) + } } /// Open (or create) the identity in `home` and start hosting an onion service. @@ -111,6 +190,11 @@ pub struct Wire { /// /// This resolves only once the onion service is published — on a cold network /// that is minutes, not seconds. Call it off the main thread. +/// +/// The returned handle owns the node: it lives until [`Wire::shutdown`], or +/// until the handle itself is dropped (which the JVM does without running the +/// drain, so call `shutdown()` from teardown — see the foreground-service +/// caller). #[uniffi::export(async_runtime = "tokio")] pub async fn open_wire(home: String, passphrase: String) -> WResult> { // Before anything that can build a TLS config: Arti's rustls backend dies @@ -120,7 +204,9 @@ pub async fn open_wire(home: String, passphrase: String) -> WResult> { let node = Node::start_with_passphrase(PathBuf::from(home), &passphrase) .await .map_err(WireError::new)?; - Ok(Arc::new(Wire { inner: node })) + Ok(Arc::new(Wire { + node: Mutex::new(Some(node)), + })) } /// Decode an invite without adding the friend. Verifies the signature. @@ -135,24 +221,81 @@ pub fn decode_invite(invite: String) -> WResult { #[uniffi::export(async_runtime = "tokio")] impl Wire { + /// Stop the node: give every queued outbox row one last bounded delivery + /// attempt, stop the onion service, abort the retry worker, checkpoint the + /// sqlite WAL, and drop the Tor client. + /// + /// The *node* teardown is idempotent: a second `Node::shutdown()` returns + /// `Ok` without repeating the work. This handle is spent by the first call, + /// so a second `Wire::shutdown()` — or two concurrent teardowns — returns + /// the typed `WireError.Stopped` instead of a silent `Ok`: a double + /// teardown is a caller bug worth surfacing, and `Stopped` is already the + /// answer every other method gives. It never panics. + /// + /// After it, every other method on this handle — including `send` — + /// returns `WireError.Stopped` instead of touching a dead client. + /// + /// Never called at all when the process is killed outright (Doze, the + /// background-process killer, a force-stop): that is the case [`flush`] + /// (Self::flush) and the sqlite outbox exist for. Once shut down, this + /// handle is spent — unlock again to get a new one. + pub async fn shutdown(&self) -> WResult<()> { + let node = self.node()?; + node.shutdown().await.map_err(WireError::new)?; + // Drop our handle to the node. With the onion service and the outbox + // worker aborted this is the last reference to the Tor client and the + // store, so Arti's runtime and the sqlite connection are released here. + let mut guard = self.node.lock().map_err(|_| WireError::Stopped { + message: "node handle lock poisoned by a panic".to_string(), + })?; + *guard = None; + Ok(()) + } + + /// Drain the outbox: one delivery attempt for every queued row, now, + /// ignoring its retry backoff, then checkpoint the WAL. + /// + /// Bounded by the SDK (30s): a dead peer's onion can hold a dial for ~20s + /// and this is called from UI/lifecycle threads. Rows that did not go out + /// stay queued; the retry worker keeps its normal schedule. Safe to call + /// repeatedly — use it on unlock, on foreground, and before `shutdown`. + pub async fn flush(&self) -> WResult { + let node = self.node()?; + let out = node.flush().await.map_err(WireError::new)?; + Ok(from_core_flush(out)) + } + + /// Where the onion service is right now. Cheap and read-only, no I/O: a + /// notification or a settings screen can call it directly. + pub fn tor_state(&self) -> TorState { + match self.node.lock() { + Ok(guard) => match guard.as_ref() { + Some(node) => node.tor_state().into(), + None => TorState::Stopped, + }, + // Poisoned: same answer as shut down — the node is unusable. + Err(_) => TorState::Stopped, + } + } + /// Fingerprint of our own identity key. Stable forever for this install. pub async fn fingerprint(&self) -> WResult { - self.inner.fingerprint().map_err(WireError::new) + self.node()?.fingerprint().map_err(WireError::new) } /// Current onion locator. Changes on rotate; identity does not. - pub async fn onion(&self) -> String { - self.inner.onion() + pub async fn onion(&self) -> WResult { + Ok(self.node()?.onion()) } /// `onionwire:v1:…` invite string to hand to the other person out of band. pub async fn invite(&self) -> WResult { - self.inner.qr_payload().map_err(WireError::new) + self.node()?.qr_payload().map_err(WireError::new) } /// Roster, sorted by petname then fingerprint. pub async fn friends(&self) -> WResult> { - let list = self.inner.list_friends().map_err(WireError::new)?; + let list = self.node()?.list_friends().map_err(WireError::new)?; Ok(list .into_iter() .map(|f| FriendInfo { @@ -168,9 +311,10 @@ impl Wire { /// Add a friend from an invite, or update the locator if the key is known. /// Same `k` never creates a second row. pub async fn add_friend(&self, invite: String) -> WResult { - self.inner.add_friend_from_qr(&invite).map_err(WireError::new)?; + let node = self.node()?; + node.add_friend_from_qr(&invite).map_err(WireError::new)?; let p = qr::decode(&invite).map_err(WireError::new)?; - let f = self.inner.friend(&p.pubkey).map_err(WireError::new)?; + let f = node.friend(&p.pubkey).map_err(WireError::new)?; Ok(FriendInfo { pubkey_hex: hex(&f.pubkey), fingerprint: f.fingerprint, @@ -183,26 +327,32 @@ impl Wire { /// Local label. Pass `None` to clear. Never goes on the wire. pub async fn set_petname(&self, pubkey_hex: String, petname: Option) -> WResult<()> { let pk = unhex(&pubkey_hex)?; - self.inner + self.node()? .set_petname(&pk, petname.as_deref()) .map_err(WireError::new) } - /// Send one message. Fail closed: if the peer's onion is down, this errors - /// after retrying. There is no outbox in v1 — no silent spooling. + /// Send one message. Returns once the outcome is known: delivered now, or + /// queued for retry because the peer's onion is unreachable. A protocol + /// error (bad signature, bad frame) still fails immediately and is never + /// queued. Use [`flush`](Self::flush) to retry the queue on demand. pub async fn send(&self, pubkey_hex: String, body: String) -> WResult<()> { let pk = unhex(&pubkey_hex)?; - self.inner + self.node()? .send(&pk, body.as_bytes()) .await - .map_err(WireError::new) + .map_err(WireError::new)?; + Ok(()) } /// Chat history for a friend, oldest first. Bodies are decrypted here; /// they are stored encrypted at rest. pub async fn messages(&self, pubkey_hex: String) -> WResult> { let pk = unhex(&pubkey_hex)?; - let rows = self.inner.list_messages(&pk).map_err(WireError::new)?; + let rows = self + .node()? + .list_messages(&pk) + .map_err(WireError::new)?; Ok(rows .into_iter() .map(|m| ChatMessage { @@ -214,7 +364,7 @@ impl Wire { /// Delete every message body. Identity and friends survive. pub async fn wipe_messages(&self) -> WResult<()> { - self.inner.wipe_messages().map_err(WireError::new) + self.node()?.wipe_messages().map_err(WireError::new) } /// Publish a NEW onion service and hard-cut the old one, then push a signed @@ -224,7 +374,7 @@ impl Wire { /// you until they rescan your invite — that is the documented v1 behaviour, /// not a bug. Confirm with a typed phrase in the UI; never one tap. pub async fn rotate_onion(&self) -> WResult { - let r = self.inner.rotate().await.map_err(WireError::new)?; + let r = self.node()?.rotate().await.map_err(WireError::new)?; Ok(RotateOutcome { notified: r.notified as u32, friends: r.friends as u32, @@ -237,6 +387,14 @@ impl Wire { } } +fn from_core_flush(o: CoreFlushOutcome) -> FlushOutcome { + FlushOutcome { + attempted: o.attempted as u32, + delivered: o.delivered as u32, + remaining: o.remaining as u32, + } +} + fn hex(bytes: &[u8]) -> String { let mut s = String::with_capacity(bytes.len() * 2); for b in bytes { @@ -256,3 +414,72 @@ fn unhex(s: &str) -> WResult> { }) .collect() } + +#[cfg(test)] +mod tests { + //! No Tor here on purpose: these exercise the *lifecycle* contract of the + //! handle, which is what a shut-down node must guarantee. A `Wire` with no + //! node is exactly the state `shutdown()` leaves behind. + + use super::*; + + fn stopped_wire() -> Wire { + Wire { + node: Mutex::new(None), + } + } + + fn block_on(f: F) -> F::Output { + // No `macros` feature on tokio in this crate, so build the runtime. + tokio::runtime::Builder::new_current_thread() + .build() + .expect("runtime") + .block_on(f) + } + + #[test] + fn tor_state_of_a_stopped_handle_is_stopped() { + assert_eq!(stopped_wire().tor_state(), TorState::Stopped); + } + + #[test] + fn calls_after_shutdown_are_typed_errors_not_panics() { + let wire = stopped_wire(); + + let err = block_on(wire.flush()).expect_err("flush after shutdown must fail"); + assert!( + matches!(err, WireError::Stopped { .. }), + "flush returned {err:?}, want WireError::Stopped" + ); + + let err = block_on(wire.send("00".repeat(32), "hi".to_string())) + .expect_err("send after shutdown must fail"); + assert!( + matches!(err, WireError::Stopped { .. }), + "send returned {err:?}, want WireError::Stopped" + ); + + let err = block_on(wire.friends()).expect_err("friends after shutdown must fail"); + assert!(matches!(err, WireError::Stopped { .. }), "got {err:?}"); + + let err = block_on(wire.shutdown()).expect_err("second shutdown must not re-run"); + assert!( + matches!(err, WireError::Stopped { .. }), + "second shutdown returned {err:?}" + ); + } + + #[test] + fn tor_state_maps_every_core_state() { + assert_eq!( + TorState::from(CoreTorState::Bootstrapping), + TorState::Bootstrapping + ); + assert_eq!(TorState::from(CoreTorState::Published), TorState::Published); + assert_eq!( + TorState::from(CoreTorState::DegradedReachable), + TorState::DegradedReachable + ); + assert_eq!(TorState::from(CoreTorState::Stopped), TorState::Stopped); + } +} diff --git a/docs/THREAT_MODEL.md b/docs/THREAT_MODEL.md index 56f44d2..48daf63 100644 --- a/docs/THREAT_MODEL.md +++ b/docs/THREAT_MODEL.md @@ -73,6 +73,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 40e82e5..ff571c2 100644 --- a/docs/TUI.md +++ b/docs/TUI.md @@ -351,6 +351,16 @@ Else RGB as today. | box | ratatui `Borders::ALL` (light) | `+` `-` `\|` via `border::Set` | | alert prefix | `! ` | `! ` | | stale | word `stale` | `stale` | +| delivery: delivered | `✓` | `ok` | +| delivery: queued | `◷` | (word) `queued` | +| delivery: sending | `»` | (word) `sending` | +| delivery: failed | `✗` | (word) `failed` | + +`queued` / `sending` / `failed` always carry their state word, so the ASCII +fallback drops the glyph instead of inventing one. Only `✓` is wordless, so it +falls back to `ok`. `delivery_glyph()` / +`tests/tui_spec.rs::delivery_markers_have_exercised_ascii_fallbacks` exercise the +fallback path. No emoji. `onion_glyph()` stays for callers that already use it; do not put it on the main header. @@ -401,6 +411,9 @@ Do not soften fail-closed into a loader. | sending | `sending` (keep, no spinner) | | sent | `sent` | | peer down / send err | `send failed: {e}` (visible) | +| queued (outbox) | `{n} queued` — replaces the flat `sent`/`send failed` while rows are outstanding | +| queued + terminal failure | `{n} queued, send failed: {short}` | +| terminal failure | `send failed: {short}` (`{f} failed` when more than one) | | already sending | `already sending` (keep) | | stale friend | `stale` suffix (keep) | | empty composer | `message` as dim placeholder (not the slash list). Slash list stays in `?` | @@ -570,3 +583,42 @@ 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. + +## Delivery state (outbox) — implemented + +Per-message state, read from the local outbox. The states are the store's own +(`Queued` / `Sending` / `Sent` / `Failed`) — no parallel model, no new wire +prefix, no server. + +| Row | Marker | +|---|---| +| delivered | `you: ping ✓` | +| queued (2nd attempt, 45s out) | `you: pong ◷ queued (try 2/8, retry 45s)` | +| sending | `you: pong » sending` | +| failed | `you: pong ✗ failed: connection timed out` | +| inbound | `them: pong` (no marker) | + +- `try {n}/{8}` is the outbox attempt count; `retry {s}s` / `retry {m}m` / + `retry now` comes from the stored absolute `next_attempt_at`. +- Failed reasons are sanitized, cut to the tail of the `a: b: c` chain and + capped at 24 cells (`short_send_reason`). +- Footer while rows are outstanding: `{n} queued`; any terminal failure keeps a + fail-closed `send failed: {short}` statement (with `! ` when colour is off). +- The tag trails the body and wraps with it, so it is never clipped away. + +Correlation: a delivered row is deleted from the outbox, so an outbound message +with no row is `Sent`; pending rows are matched to messages by body, newest send +first (`chat_with_delivery`). The outbox holds no message id the UI can join on, +so two identical bodies where only the newer one is still queued attach the +marker to the newer send. An id-bearing accessor would remove that last +ambiguity; see the follow-up card noted in the PR. + +### Size floor / target + +- **Floor: 80x24.** Everything above must render there. +- **Target: 120x40.** +- `tests/tui_spec.rs::chat_and_footer_rows_fit_80x24_and_wrap_instead_of_clipping` + draws the real `draw_chat` + `status_footer` at 80x24 and asserts every chat + and footer row is `<=` the terminal width, that the markers render, and that + an over-long message wraps instead of being clipped. +- Dump frames: `cargo test --locked --test tui_spec -- --nocapture dump_spec_frames`. 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/hs.rs b/src/hs.rs index 159e53d..f87f932 100644 --- a/src/hs.rs +++ b/src/hs.rs @@ -96,6 +96,64 @@ pub fn hs_is_ready(state: State, probe_ok: bool) -> bool { } } +/// Observable lifecycle state of the node's onion service. +/// +/// This is the four-state projection callers actually act on: is the onion +/// service serving, is it serving but unhealthy, is it still coming up, or did +/// we stop it. A process that gets killed by the Android background-process +/// killer never observes `Stopped` — that is why `Wire.flush()` exists — but a +/// clean teardown always does. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum TorState { + /// Bootstrap or HsDir descriptor upload is still in flight: the service is + /// not reliably reachable yet. + Bootstrapping, + /// The onion service is running and its descriptor is published. + Published, + /// Reachable through the service, but Arti reports the service degraded. + /// Usable, worth surfacing, not identical to `Published`. + DegradedReachable, + /// The node was shut down: no onion service, no client dials, and the + /// store is checkpointed. + Stopped, +} + +/// Project an Arti onion-service status onto [`TorState`]. +/// +/// Deliberately mirrors `hs_is_ready`: `Running` and `DegradedReachable` are +/// the states a probe could already reach, everything transient is +/// `Bootstrapping`, and a shut-down service is `Stopped`. +/// +/// `reachable` is the same evidence `wait_until_published` accepts from a +/// probe: a successful connect to our own onion means some HsDir already has +/// the descriptor even though Arti's combined status is still `Bootstrapping` +/// (that mismatch is exactly what the 360s publish wait exists for). Without +/// it, a node that is live and reachable would report `Bootstrapping` for +/// another few minutes. +/// +/// Two statuses look terminal but are not: +/// * `Shutdown` on a *live* node is transient — a freshly launched service +/// reports it before its publish reactor starts, which is why a live node +/// reads `Bootstrapping` there and only the explicit stop flag produces +/// `Stopped`. (Caught on device-real conditions by the live test: the +/// first `tor_state()` after `start()` returned `Shutdown`.) +/// * `Broken` maps to `Bootstrapping` rather than a state of its own: Arti +/// reads `Broken` while the HsDir retry loop is still going, and +/// `wait_until_published` is where a genuinely dead service surfaces as an +/// error instead of a flag the UI would have to poll for. +pub fn tor_state_of(state: State, stopped: bool, reachable: bool) -> TorState { + if stopped { + return TorState::Stopped; + } + match state { + State::Running => TorState::Published, + State::DegradedReachable => TorState::DegradedReachable, + State::Broken | State::Shutdown => TorState::Bootstrapping, + _ if reachable => TorState::Published, + _ => TorState::Bootstrapping, + } +} + pub async fn wait_until_published( client: &Client, svc: &RunningOnionService, 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/node.rs b/src/node.rs index b7b9fa3..a051f4d 100644 --- a/src/node.rs +++ b/src/node.rs @@ -1,6 +1,7 @@ //! Two-node onion session: host HS, Noise IK, persist plaintext locally. use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Mutex}; use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; @@ -13,7 +14,7 @@ use zeroize::Zeroizing; use crate::dispatch::{self, Kind}; use crate::file; use crate::frame; -use crate::hs::{self, Client, HS_PORT}; +use crate::hs::{self, Client, HS_PORT, TorState}; use crate::loc; use crate::outbox::{ArtiDeliverer, Outbox, OutboxStatus}; use crate::pay; @@ -30,8 +31,27 @@ pub struct RotateResult { pub friends: usize, } +/// What a `flush` actually managed to do, for UI surfacing. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct FlushOutcome { + /// Outbox rows we tried to deliver in this pass. + pub attempted: usize, + /// Rows delivered now — their outbox rows are gone. + pub delivered: usize, + /// Rows still queued or terminally failed after the pass. + pub remaining: usize, +} + +/// A foreground/unlock flush is bounded: the caller is a UI thread and a dead +/// peer's onion can hold a dial open for 20s. Whatever is left stays queued and +/// the retry worker picks it up on its normal schedule. +pub const FLUSH_TIMEOUT: Duration = Duration::from_secs(30); +/// The drain inside `shutdown` gets a shorter budget: teardown must not hang +/// the caller behind a Tor dial. Undelivered rows survive in sqlite. +pub const SHUTDOWN_FLUSH_TIMEOUT: Duration = Duration::from_secs(10); + struct HsHandle { - _svc: Arc, + svc: Arc, rend: tokio::task::JoinHandle<()>, } @@ -61,7 +81,17 @@ pub struct Node { incoming_limit: Mutex, inbox: Mutex, outbox: Arc, - _outbox_worker: WorkerHandle, + worker: Mutex>, + /// Set by `shutdown`. Checked before any operation that would touch Tor or + /// the store, so a stopped node fails cleanly instead of dialing. + stopped: AtomicBool, + /// Has this node's onion service ever crossed the reachability bar (status + /// `Running`/`DegradedReachable`, or a successful probe of our own onion)? + /// Arti's combined status can stay `Bootstrapping` for minutes *after* the + /// descriptor is downloadable, so without this the UI would keep saying + /// "starting" long past the point where friends can reach us. Cleared when + /// `rotate` hard-cuts the service. + onion_reachable: AtomicBool, } impl Node { @@ -113,7 +143,9 @@ impl Node { incoming_limit: Mutex::new(TokenBucket::default()), inbox: Mutex::new(inbox), outbox: Arc::clone(&outbox), - _outbox_worker: WorkerHandle(outbox.spawn_worker()), + worker: Mutex::new(Some(WorkerHandle(outbox.spawn_worker()))), + stopped: AtomicBool::new(false), + onion_reachable: AtomicBool::new(false), }); // Unlock trigger: flush anything queued by a previous run now, in the // background, rather than waiting out its backoff. @@ -122,10 +154,14 @@ impl Node { // while combined status is still Bootstrapping. let rend = spawn_rend(Arc::clone(&node), rend); *node.hs.lock().map_err(|e| e.to_string())? = Some(HsHandle { - _svc: Arc::clone(&svc), + svc: Arc::clone(&svc), rend, }); hs::wait_until_published(&node.client, &svc, &onion).await?; + // Published by the same bar `wait_until_published` uses — a probe + // success counts, which is the whole reason `tor_state` tracks it + // separately from Arti's (slower, flappier) combined status. + node.onion_reachable.store(true, Ordering::SeqCst); node.store .lock() .map_err(|e| e.to_string())? @@ -134,6 +170,141 @@ impl Node { Ok(node) } + /// Observable onion/Tor lifecycle state: `Bootstrapping` / `Published` / + /// `DegradedReachable` / `Stopped`. + /// + /// Read-only and cheap (one mutex + one status read, no I/O), so a UI or a + /// foreground-service notification can poll it instead of guessing from a + /// timer. A poisoned handle is reported as `Stopped` rather than panicking: + /// the node is unusable either way, and the caller is often a UI thread. + pub fn tor_state(&self) -> TorState { + let stopped = self.stopped.load(Ordering::SeqCst); + let reachable = self.onion_reachable.load(Ordering::SeqCst); + match self.hs.lock() { + Ok(guard) => match guard.as_ref() { + Some(h) => hs::tor_state_of(h.svc.status().state(), stopped, reachable), + // Between `rotate`'s hard cut and the new service being + // installed there is no handle; before the first publish there + // is none either. Both are "not serving *yet*" unless we stopped. + None if stopped => TorState::Stopped, + None => TorState::Bootstrapping, + }, + Err(_) => TorState::Stopped, + } + } + + /// Drain the outbox: one delivery attempt for every outstanding row, now, + /// ignoring its retry schedule. Then checkpoint the WAL. + /// + /// This is the "deliver what is deliverable before we lose the process" + /// call. Bounded by [`FLUSH_TIMEOUT`] because a dead peer's onion holds a + /// dial for ~20s and the caller is usually a UI thread. Rows that could not + /// be delivered stay queued and are picked up by the retry worker on its + /// normal backoff. + pub async fn flush(&self) -> Result { + self.ensure_running()?; + let outcome = self.drain(FLUSH_TIMEOUT).await?; + self.checkpoint(); + Ok(outcome) + } + + /// Stop the node. + /// + /// Order matters: drain the outbox while the Tor client is still alive, + /// then drop the onion service (its rendezvous task is aborted and the v3 + /// service goes down), then abort the retry worker so nothing dials after + /// this, then checkpoint the WAL. + /// + /// Idempotent: the flag is swapped first, so a second call — or a call + /// racing another teardown — returns `Ok(())` without touching anything + /// twice. Every other method on a stopped node returns a clean `Err`, never + /// a panic. A process killed outright never gets here at all, which is why + /// [`flush`](Self::flush) exists. + pub async fn shutdown(&self) -> Result<(), String> { + if self.stopped.swap(true, Ordering::SeqCst) { + return Ok(()); + } + // Bounded: teardown must not hang behind a Tor dial. Undelivered rows + // survive in sqlite and are retried on the next unlock. + match self.drain(SHUTDOWN_FLUSH_TIMEOUT).await { + Ok(o) if o.remaining > 0 => { + eprintln!("shutdown: {} outbox row(s) still pending", o.remaining) + } + Ok(_) => {} + Err(e) => eprintln!("shutdown: drain failed: {e}"), + } + match self.hs.lock() { + Ok(mut g) => *g = None, + Err(_) => eprintln!("shutdown: onion-service lock poisoned"), + } + match self.worker.lock() { + Ok(mut g) => drop(g.take()), + Err(_) => eprintln!("shutdown: outbox-worker lock poisoned"), + } + self.checkpoint(); + Ok(()) + } + + /// One bounded pass over every outstanding outbox row. + /// + /// A timeout cancels the pass mid-flight, which can leave a row in + /// `sending`; `Outbox::reset_stale` requeues those on the next unlock, the + /// same recovery the parent uses for a process that died mid-attempt. + async fn drain(&self, budget: Duration) -> Result { + let attempted = match tokio::time::timeout(budget, self.outbox.flush_all(unix_now())).await { + Ok(Ok(rows)) => Some(rows), + Ok(Err(e)) => return Err(e), + Err(_) => { + eprintln!("outbox: drain hit its {budget:?} budget, undelivered rows stay queued"); + None + } + }; + let delivered = attempted + .as_ref() + .map(|rows| { + rows.iter() + .filter(|(_, s)| matches!(s, OutboxStatus::Sent)) + .count() + }) + .unwrap_or(0); + Ok(FlushOutcome { + // `None` means the pass was cancelled: we know how many rows are + // still queued, not how many were started. + attempted: attempted.as_ref().map(Vec::len).unwrap_or(0), + delivered, + remaining: self.pending_rows()?, + }) + } + + /// Rows the outbox still holds for every friend, queued or terminally + /// failed. A message absent here was delivered. + fn pending_rows(&self) -> Result { + let friends = self.list_friends()?; + let mut n = 0usize; + for f in &friends { + n += self.outbox.pending(&f.pubkey)?.len(); + } + Ok(n) + } + + /// Checkpoint the sqlite WAL into the main db file and truncate it. + /// + /// Best effort on purpose: WAL replay on open recovers everything committed, + /// so this is about leaving less to replay (and less on disk) if the + /// process is killed right after teardown — not about correctness. + fn checkpoint(&self) { + if let Err(e) = checkpoint_wal(&self.home) { + eprintln!("wal checkpoint: {e}"); + } + } + + fn ensure_running(&self) -> Result<(), String> { + if self.stopped.load(Ordering::SeqCst) { + return Err("node is stopped — open the identity again".to_string()); + } + Ok(()) + } + pub fn onion(&self) -> String { self.onion.lock().map(|g| g.clone()).unwrap_or_default() } @@ -434,6 +605,7 @@ impl Node { } async fn send_once(&self, friend_pk: &[u8], plaintext: &[u8]) -> Result<(), String> { + self.ensure_running()?; let (onion, prekey) = { let f = self.friend(friend_pk)?; if f.prekey.len() != 32 { @@ -447,6 +619,7 @@ impl Node { /// Dial a peer's onion. Success is evidence the peer is up, which is one of /// the outbox retry triggers. pub async fn connect_onion(&self, onion: &str) -> Result<(), String> { + self.ensure_running()?; tokio::time::timeout( Duration::from_secs(20), self.client.connect((onion, HS_PORT)), @@ -466,6 +639,7 @@ impl Node { } pub async fn rotate(self: &Arc) -> Result { + self.ensure_running()?; let old_nick = self .store .lock() @@ -482,12 +656,16 @@ impl Node { let onion = hs::onion_string(&svc)?; // ponytail: hard-cut old HS before waiting; keeping both stalled ow1 at Bootstrapping. *self.hs.lock().map_err(|e| e.to_string())? = None; + // The new service is not reachable until it publishes: the locator in + // flight is dead until then, so do not carry the old verdict over. + self.onion_reachable.store(false, Ordering::SeqCst); let rend = spawn_rend(Arc::clone(self), rend); *self.hs.lock().map_err(|e| e.to_string())? = Some(HsHandle { - _svc: Arc::clone(&svc), + svc: Arc::clone(&svc), rend, }); hs::wait_until_published(&self.client, &svc, &onion).await?; + self.onion_reachable.store(true, Ordering::SeqCst); { let store = self.store.lock().map_err(|e| e.to_string())?; store.set_onion(&onion).map_err(|e| e.to_string())?; @@ -549,6 +727,7 @@ impl Node { /// backoff. A real protocol error (signature mismatch, unknown/short/oversize /// frame) still fails immediately and is never retried. pub async fn send(&self, friend_pk: &[u8], plaintext: &[u8]) -> Result { + self.ensure_running()?; self.outbox.send(friend_pk, plaintext).await } @@ -857,6 +1036,49 @@ fn spawn_flush_friend(outbox: Arc, friend_pk: Vec) { }); } +/// Checkpoint the sqlite WAL into the main db file and truncate it. +/// +/// `Store` owns the write connection and deliberately does not lend it out, and +/// a checkpoint is a property of the *database*, not of one connection — so a +/// short-lived second connection to the same file is the least invasive way to +/// reach it from the node without widening `Store`'s API. +/// +/// That works because the connection needs no passphrase: it moves +/// already-committed pages, it does not decrypt them. It stops working the +/// moment the store is SQLCipher-encrypted (PR #43), because the key lives only +/// inside `Store` and a second connection cannot read the file at all. That case +/// is detected and reported as a skip rather than a failure: nothing is lost +/// (sqlite folds the WAL into the db when the last connection closes) — the +/// explicit truncation just has to move inside `Store` to happen here. +fn checkpoint_wal(home: &Path) -> Result<(), String> { + let db = home.join("onionwire.db"); + if !db.exists() { + return Ok(()); + } + let conn = rusqlite::Connection::open(&db).map_err(|e| format!("open {}: {e}", db.display()))?; + let (busy, log, checkpointed): (i64, i64, i64) = conn + .query_row("PRAGMA wal_checkpoint(TRUNCATE)", [], |row| { + Ok((row.get(0)?, row.get(1)?, row.get(2)?)) + }) + .map_err(|e| { + let msg = e.to_string(); + if msg.contains("not a database") { + // SQLCipher store: no key here, so this connection sees noise. + format!("store is SQLCipher-encrypted — skipped ({msg})") + } else { + format!("wal_checkpoint: {msg}") + } + })?; + if busy != 0 { + // Another connection is reading/writing: pages are still safe in the + // WAL, they just were not moved this time. + return Err(format!( + "busy ({checkpointed}/{log} pages moved, another connection active)" + )); + } + Ok(()) +} + fn next_hs_nickname(cur: &str) -> String { let n = cur .strip_prefix("ow") @@ -899,3 +1121,57 @@ pub fn dir_contains_bytes(dir: &Path, needle: &[u8]) -> bool { } false } + +#[cfg(test)] +mod lifecycle_tests { + //! Offline half of the shutdown contract. The live-Tor half lives in + //! `tests/tor_lifecycle.rs` (ignored) — everything here runs in CI. + + use super::*; + + /// `checkpoint_wal` reaches the database through a *second* connection, + /// because `Store` owns the write one. That assumption is the whole reason + /// the helper can live in `node.rs`, so prove it against a real WAL. + #[test] + fn checkpoint_wal_truncates_a_live_wal() { + let root = tempfile::tempdir().expect("tempdir"); + let home = root.path(); + let db = home.join("onionwire.db"); + let conn = rusqlite::Connection::open(&db).expect("open db"); + let mode: String = conn + .query_row("PRAGMA journal_mode = WAL", [], |r| r.get(0)) + .expect("wal mode"); + assert_eq!(mode.to_lowercase(), "wal"); + conn.execute_batch("CREATE TABLE t (id INTEGER PRIMARY KEY, v BLOB);") + .expect("create table"); + for _ in 0..64 { + conn.execute("INSERT INTO t (v) VALUES (?1)", rusqlite::params![vec![7u8; 512]]) + .expect("insert"); + } + + let wal = home.join("onionwire.db-wal"); + let before = std::fs::metadata(&wal).expect("wal file").len(); + assert!(before > 0, "expected pending WAL frames, got {before}"); + + checkpoint_wal(home).expect("checkpoint"); + + let after = std::fs::metadata(&wal).map(|m| m.len()).unwrap_or(0); + assert_eq!(after, 0, "WAL not truncated ({before} bytes before)"); + + // The rows are still there — a checkpoint moves pages, it never drops + // committed data. + let n: i64 = conn + .query_row("SELECT COUNT(*) FROM t", [], |r| r.get(0)) + .expect("count"); + assert_eq!(n, 64); + } + + /// A home directory with no store yet is not an error: `shutdown` and + /// `flush` are safe to call on a node whose db was never created (tests, + /// wiped installs). + #[test] + fn checkpoint_wal_is_a_no_op_without_a_database() { + let root = tempfile::tempdir().expect("tempdir"); + checkpoint_wal(root.path()).expect("no db, no error"); + } +} 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 1a65f37..6e580bb 100644 --- a/src/tui.rs +++ b/src/tui.rs @@ -1,6 +1,7 @@ +use std::collections::HashMap; use std::io::{self, IsTerminal}; use std::sync::{Arc, mpsc}; -use std::time::Duration; +use std::time::{Duration, SystemTime, UNIX_EPOCH}; use ratatui::crossterm::event::{self, Event, KeyCode, KeyEvent, KeyEventKind, KeyModifiers}; use ratatui::layout::{Constraint, Layout, Rect}; @@ -8,11 +9,13 @@ 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::outbox::DEFAULT_MAX_ATTEMPTS; use crate::qr::{self, QrPayload}; use crate::sanitize; -use crate::store::{Friend, FriendProfile}; +use crate::store::{Friend, FriendProfile, Message, OutboxEntry, OutboxStatus}; const C_ACCENT: Color = Color::Rgb(232, 165, 75); const C_TEXT: Color = Color::Rgb(196, 214, 176); @@ -116,6 +119,202 @@ pub fn empty_friend_chat_text() -> &'static str { "no messages\ntype below, Enter sends" } +// --------------------------------------------------------------------------- +// Delivery state (outbox) +// +// The outbox is the only source of per-message state: `Queued` / `Sending` / +// `Failed` rows are what `Node::outbox_pending` still holds, and a row is +// deleted the moment the send crosses the circuit — so an outbound message with +// no row is `Sent`. No parallel state model, no new wire prefix. +// --------------------------------------------------------------------------- + +/// Longest short-form failure reason shown in a chat row. +pub const FAIL_REASON_BUDGET: usize = 24; + +/// Marker glyph for one delivery state. ASCII chrome falls back to `ok` for the +/// wordless delivered state; `queued` / `sending` / `failed` already carry their +/// word, so their glyph is dropped rather than invented. +pub fn delivery_glyph(status: &OutboxStatus) -> &'static str { + let ascii = ascii_chrome(); + match status { + OutboxStatus::Sent => { + if ascii { + "ok" + } else { + "✓" + } + } + OutboxStatus::Queued => { + if ascii { + "" + } else { + "◷" + } + } + OutboxStatus::Sending => { + if ascii { + "" + } else { + "»" + } + } + OutboxStatus::Failed(_) => { + if ascii { + "" + } else { + "✗" + } + } + } +} + +/// Next-attempt age for a queued row, from the absolute `next_attempt_at` the +/// outbox stores. +pub fn retry_in_text(next_in_secs: i64) -> String { + if next_in_secs <= 0 { + "retry now".to_string() + } else if next_in_secs < 60 { + format!("retry {next_in_secs}s") + } else { + format!("retry {}m", (next_in_secs + 59) / 60) + } +} + +/// Transport failure text, short form: sanitized, tail of the `a: b: c` chain, +/// capped at `budget` cells so one peer's error cannot blow out the row. +pub fn short_send_reason(why: &str, budget: usize) -> String { + let clean = sanitize::display_text(why.as_bytes()); + let tail = clean.rsplit(": ").next().unwrap_or("").trim(); + let text = if tail.is_empty() { clean.trim() } else { tail }; + truncate_chars(text, budget) +} + +/// One row's delivery marker, straight from the outbox state. +pub fn delivery_tag(status: &OutboxStatus, attempts: u32, next_in_secs: i64) -> String { + let glyph = delivery_glyph(status); + let body = match status { + OutboxStatus::Sent => String::new(), + OutboxStatus::Queued => format!( + "queued (try {attempts}/{DEFAULT_MAX_ATTEMPTS}, {})", + retry_in_text(next_in_secs) + ), + OutboxStatus::Sending => "sending".to_string(), + OutboxStatus::Failed(why) => { + format!("failed: {}", short_send_reason(why, FAIL_REASON_BUDGET)) + } + }; + match (glyph.is_empty(), body.is_empty()) { + (_, true) => glyph.to_string(), + (true, false) => body, + (false, false) => format!("{glyph} {body}"), + } +} + +/// Footer summary derived from the outbox rows of the selected friend. +#[derive(Debug, Default, Clone, PartialEq, Eq)] +pub struct OutboxSummary { + /// `Queued` + `Sending`: rows the worker may still deliver. + pub queued: usize, + /// Terminal failures — these never retry. + pub failed: usize, + /// First terminal failure, for the fail-closed footer copy. + pub first_error: Option, +} + +impl OutboxSummary { + /// Footer note, or `None` when nothing is outstanding. Any terminal failure + /// keeps a `send failed` statement so the fail-closed copy stays visible. + pub fn note(&self) -> Option { + let reason = || { + short_send_reason( + self.first_error.as_deref().unwrap_or("unknown"), + FAIL_REASON_BUDGET, + ) + }; + match (self.queued, self.failed) { + (0, 0) => None, + (queued, 0) => Some(format!("{queued} queued")), + (0, 1) => Some(format!("send failed: {}", reason())), + (0, failed) => Some(format!("send failed: {} ({failed} failed)", reason())), + (queued, _) => Some(format!("{queued} queued, send failed: {}", reason())), + } + } +} + +/// Chat transcript with per-message delivery state, plus the footer summary. +/// +/// Pending rows are matched to messages by body, newest send first: an +/// outstanding retry is the most recent send of that text, and the outbox holds +/// no message id the UI could join on. +pub fn chat_with_delivery( + msgs: &[Message], + pending: &[OutboxEntry], + now: i64, +) -> (Vec, OutboxSummary) { + let mut summary = OutboxSummary::default(); + for entry in pending { + match &entry.status { + OutboxStatus::Failed(why) => { + summary.failed += 1; + summary.first_error.get_or_insert_with(|| why.clone()); + } + _ => summary.queued += 1, + } + } + if msgs.is_empty() { + return ( + empty_friend_chat_text() + .lines() + .map(str::to_string) + .collect(), + summary, + ); + } + + let mut by_body: HashMap<&[u8], Vec<&OutboxEntry>> = HashMap::new(); + for entry in pending { + by_body + .entry(entry.body.as_slice()) + .or_default() + .push(entry); + } + let mut tags: Vec> = vec![None; msgs.len()]; + for (i, msg) in msgs.iter().enumerate().rev() { + if msg.dir != "out" { + continue; + } + if let Some(rows) = by_body.get_mut(msg.plaintext.as_slice()) + && let Some(entry) = rows.pop() + { + tags[i] = Some(delivery_tag( + &entry.status, + entry.attempts, + entry.next_attempt_at - now, + )); + } + } + + let lines = msgs + .iter() + .enumerate() + .map(|(i, msg)| { + let side = if msg.dir == "out" { "you" } else { "them" }; + let body = sanitize::display_text(&msg.plaintext); + let tag = match tags[i].clone() { + Some(tag) => tag, + None if msg.dir == "out" => delivery_tag(&OutboxStatus::Sent, 0, 0), + None => String::new(), + }; + if tag.is_empty() { + format!("{side}: {body}") + } else { + format!("{side}: {body} {tag}") + } + }) + .collect(); + (lines, summary) +} + /// Paste overlay copy. Error keeps the resubmit hint. pub fn paste_screen_text(buf: &str, err: Option<&str>) -> String { let hint = match err { @@ -761,6 +960,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 +1111,7 @@ enum Screen { Passphrase { kind: BackupKind, path: String, - first: Option, - buf: String, + entry: PassphraseEntry, }, Quit { prompt: QuitPrompt, @@ -929,6 +1199,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 +1361,7 @@ impl App { self.screen = Screen::Passphrase { kind, path: path.clone(), - first: None, - buf: String::new(), + entry: PassphraseEntry::new(), }; } } @@ -1101,25 +1371,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 +1428,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 +1544,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), }; } } @@ -1449,11 +1713,13 @@ impl App { let (tx, rx) = mpsc::channel(); self.status_note = Some("sending".into()); std::mem::drop(self.rt.spawn(async move { - // send() now reports `Sent`/`Queued`; surfacing `queued` in the - // footer is a follow-up card, so this arm keeps today's wording. + // `send()` reports `Sent` when the circuit took it and `Queued` when + // the peer's onion is unreachable. The footer then reads the real + // row count from the outbox, so this note is only the first word. let note = match node.send(&pk, &body).await { - Ok(_) => "sent".to_string(), - Err(e) => format!("send failed: {e}"), + Ok(OutboxStatus::Sent) => "sent".to_string(), + Ok(_) => "queued".to_string(), + Err(e) => format!("send failed: {}", short_send_reason(&e, FAIL_REASON_BUDGET)), }; let _ = tx.send(note); })); @@ -1487,9 +1753,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 { @@ -1563,38 +1829,22 @@ impl App { } f.render_stateful_widget(roster, panes[0], &mut roster_state); - let chat_lines = self.chat_lines(); - let inner_h = panes[1].height.saturating_sub(2); - let nlines = chat_lines.len(); - let max_scroll = nlines.saturating_sub(inner_h as usize) as u16; - let scroll = self.chat_scroll.min(max_scroll); - let overflow = nlines > inner_h as usize && inner_h > 0; - let chat_title = { - let name = self.friends.get(self.selected).map(|friend| { - friend - .petname - .as_deref() - .unwrap_or(&friend.fingerprint) - .to_string() - }); - let mut t = match name { - Some(n) => format!("chat {n}"), - None => "chat".to_string(), - }; - if overflow { - let end = (scroll as usize + inner_h as usize).min(nlines); - t.push_str(&format!(" {}-{end}/{nlines}", scroll as usize + 1)); - } - let mark = if self.focus == Pane::Chat { "> " } else { " " }; - format!("{mark}{t}") - }; - let chat_text = chat_lines.join("\n"); - let chat = Paragraph::new(chat_text) - .style(style_text()) - .wrap(Wrap { trim: false }) - .scroll((scroll, 0)) - .block(self.pane_block(&chat_title, Pane::Chat)); - f.render_widget(chat, panes[1]); + let (chat_lines, summary) = self.chat_view(); + let chat_name = self.friends.get(self.selected).map(|friend| { + friend + .petname + .as_deref() + .unwrap_or(&friend.fingerprint) + .to_string() + }); + draw_chat( + f, + panes[1], + &chat_lines, + chat_name.as_deref(), + self.focus == Pane::Chat, + self.chat_scroll, + ); let mark = if self.focus == Pane::Composer { "> " @@ -1618,62 +1868,108 @@ impl App { cols[3], ); - let footer = self.footer_line(area.width); + let footer = self.footer_line(area.width, &summary); f.render_widget(Paragraph::new(footer).style(style_dim()), cols[4]); } - fn footer_line(&self, width: u16) -> String { + fn footer_line(&self, width: u16, summary: &OutboxSummary) -> String { + // The outbox is the source of truth while anything is outstanding; the + // transient note still covers "sending", "sent file x", "invoice sent". + let note = summary.note().or_else(|| self.status_note.clone()); status_footer( width, &self.me_fp, &self.me_onion, - self.status_note.as_deref(), + note.as_deref(), footer_hints(&self.screen), ) } - fn chat_lines(&self) -> Vec { + fn chat_view(&self) -> (Vec, OutboxSummary) { let Some(friend) = self.friends.get(self.selected) else { - return vec![ - "no friends yet".into(), - "F3 paste an invite to add one".into(), - ]; + return ( + vec![ + "no friends yet".into(), + "F3 paste an invite to add one".into(), + ], + OutboxSummary::default(), + ); }; match self.node.list_messages(&friend.pubkey) { - Ok(msgs) if msgs.is_empty() => empty_friend_chat_text() - .lines() - .map(str::to_string) - .collect(), - Ok(msgs) => msgs - .iter() - .map(|m| { - let side = if m.dir == "out" { "you" } else { "them" }; - format!("{side}: {}", sanitize::display_text(&m.plaintext)) - }) - .collect(), - Err(e) => vec![e], + Ok(msgs) => { + let pending = self.node.outbox_pending(&friend.pubkey).unwrap_or_default(); + chat_with_delivery(&msgs, &pending, unix_now_secs()) + } + Err(e) => (vec![e], OutboxSummary::default()), } } fn pane_block<'a>(&self, title: &'a str, pane: Pane) -> Block<'a> { - let focused = self.focus == pane; - let border = if focused { - style_accent() - } else { - style_border() - }; - let title_style = if focused { - style_accent().add_modifier(Modifier::BOLD) - } else { - style_dim() - }; - apply_chrome_borders(Block::default()) - .border_style(border) - .title(title) - .title_style(title_style) + pane_block_for(title, self.focus == pane) } } +/// Pane chrome without an `App`: focus is accent border + bold title, never +/// color alone (the `> ` marks come from the callers). +fn pane_block_for(title: &str, focused: bool) -> Block<'_> { + let border = if focused { + style_accent() + } else { + style_border() + }; + let title_style = if focused { + style_accent().add_modifier(Modifier::BOLD) + } else { + style_dim() + }; + apply_chrome_borders(Block::default()) + .border_style(border) + .title(title) + .title_style(title_style) +} + +fn unix_now_secs() -> i64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|d| d.as_secs() as i64) + .unwrap_or(0) +} + +/// Real chat-pane renderer: `App::draw_main` calls this, so width, wrap and +/// delivery-marker behaviour are testable without constructing a `Node`. +pub fn draw_chat( + f: &mut Frame, + area: Rect, + lines: &[String], + name: Option<&str>, + focused: bool, + scroll: u16, +) { + let inner_h = area.height.saturating_sub(2); + let nlines = lines.len(); + let max_scroll = nlines.saturating_sub(inner_h as usize) as u16; + let scroll = scroll.min(max_scroll); + let overflow = nlines > inner_h as usize && inner_h > 0; + let mut title = match name { + Some(n) => format!("chat {n}"), + None => "chat".to_string(), + }; + if overflow { + let end = (scroll as usize + inner_h as usize).min(nlines); + title.push_str(&format!(" {}-{end}/{nlines}", scroll as usize + 1)); + } + let mark = if focused { "> " } else { " " }; + let title = format!("{mark}{title}"); + f.render_widget( + Paragraph::new(lines.join("\n")) + .style(style_text()) + .wrap(Wrap { trim: false }) + .scroll((scroll, 0)) + .block(pane_block_for(&title, focused)), + area, + ); +} + /// Status bar: never drop a non-empty `status_note`. Always keep `TOR`, `me:`, `? help`. pub fn status_footer( width: u16, @@ -1689,7 +1985,7 @@ pub fn status_footer( let mut note = status_note.unwrap_or("").trim().to_string(); if !note.is_empty() && color_mode() == ColorMode::None - && (note.starts_with("send failed") || note == "fingerprint mismatch") + && (note.contains("send failed") || note == "fingerprint mismatch") && !note.starts_with("! ") { note = format!("! {note}"); @@ -2017,3 +2313,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/src/wallet.rs b/src/wallet.rs index 1917cd7..85271c1 100644 --- a/src/wallet.rs +++ b/src/wallet.rs @@ -42,8 +42,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, @@ -55,10 +65,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") { // The URL can carry `user:pass@` in its userinfo: keep it in a // wiping buffer, not a bare `String`. @@ -71,23 +88,41 @@ impl Wallet { match parse_http_url(url.trim(), login.as_ref().map(|v| v.as_str())) { 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() } @@ -107,7 +142,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!({ @@ -115,10 +153,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( @@ -189,6 +253,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, Zeroizing)> { let (user, pass) = login.split_once(':').ok_or_else(credentials_required)?; if user.is_empty() || pass.is_empty() { @@ -455,6 +530,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/hs.rs b/tests/hs.rs index 334620c..d6fb620 100644 --- a/tests/hs.rs +++ b/tests/hs.rs @@ -69,6 +69,101 @@ fn broken_or_shutdown_never_ready() { assert!(!hs::hs_is_ready(State::Shutdown, true)); } +#[test] +fn tor_state_maps_every_arti_status() { + // The four states the Android UI branches on, derived from the same status + // union `hs_is_ready` reads. + assert_eq!( + hs::tor_state_of(State::Running, false, false), + hs::TorState::Published + ); + assert_eq!( + hs::tor_state_of(State::DegradedReachable, false, false), + hs::TorState::DegradedReachable + ); + assert_eq!( + hs::tor_state_of(State::Bootstrapping, false, false), + hs::TorState::Bootstrapping + ); + assert_eq!( + hs::tor_state_of(State::DegradedUnreachable, false, false), + hs::TorState::Bootstrapping + ); + // A freshly launched service reports Shutdown before its publish reactor + // starts. Mapping that to Stopped would make a live node look dead for the + // first seconds after unlock — caught on a real Tor network. + assert_eq!( + hs::tor_state_of(State::Shutdown, false, false), + hs::TorState::Bootstrapping + ); + // Arti reads `Broken` while the HsDir retry loop is still going; a dead + // service surfaces as an error from `wait_until_published`, not as a state + // the UI has to poll for. + assert_eq!( + hs::tor_state_of(State::Broken, false, false), + hs::TorState::Bootstrapping + ); +} + +#[test] +fn reachable_statuses_report_published_while_arti_says_bootstrapping() { + // `wait_until_published` returns on a successful probe while Arti's + // combined status is still Bootstrapping (see `hs_is_ready`). Reporting + // Bootstrapping there would keep the UI saying "starting" for minutes after + // friends can actually reach us. + assert_eq!( + hs::tor_state_of(State::Bootstrapping, false, true), + hs::TorState::Published + ); + assert_eq!( + hs::tor_state_of(State::DegradedUnreachable, false, true), + hs::TorState::Published + ); + // Broken stays Broken, reachable or not: `hs_is_ready` refuses it too. + assert_eq!( + hs::tor_state_of(State::Broken, false, true), + hs::TorState::Bootstrapping + ); +} + +#[test] +fn stopped_outranks_whatever_arti_reports() { + // A node that has been told to stop is Stopped even if Arti's status cache + // still says Running, and even if it was reachable a moment ago: the flag + // is set before the service is dropped. + for state in [ + State::Running, + State::DegradedReachable, + State::DegradedUnreachable, + State::Bootstrapping, + State::Broken, + State::Shutdown, + ] { + for reachable in [false, true] { + assert_eq!( + hs::tor_state_of(state, true, reachable), + hs::TorState::Stopped, + "wrong state for {state:?} (reachable={reachable}) on a stopped node" + ); + } + } +} + +#[test] +fn ready_states_are_the_published_ones() { + // Published/degraded must not drift from the readiness bar: anything + // `hs_is_ready` accepts without a probe is a state the UI calls up. + let ready = [State::Running, State::DegradedReachable]; + for state in ready { + assert!(hs::hs_is_ready(state, false), "{state:?} must be ready"); + assert_ne!( + hs::tor_state_of(state, false, false), + hs::TorState::Bootstrapping, + "{state:?} is ready but reported as still coming up" + ); + } +} + #[test] fn hs_log_label_is_not_the_full_v3_onion() { // Public v3 address; checksum is valid so HsId::from_str works. diff --git a/tests/tor_lifecycle.rs b/tests/tor_lifecycle.rs new file mode 100644 index 0000000..c74b081 --- /dev/null +++ b/tests/tor_lifecycle.rs @@ -0,0 +1,96 @@ +//! Lifecycle: a node stops when told to, says so, and refuses further work +//! with an error instead of panicking. +//! +//! Needs a live Tor network to publish the onion service, so `cargo test` skips +//! it. Run it on a networked machine with: +//! +//! ```text +//! cargo test --test tor_lifecycle -- --ignored --nocapture +//! ``` +//! +//! The offline half of this contract — the Arti-status projection, the WAL +//! checkpoint, and the SDK's typed error after shutdown — runs in the normal +//! suite (`tests/hs.rs`, `src/node.rs`, `crates/onionwire-sdk/src/lib.rs`). + +use onionwire::node::{FlushOutcome, Node}; +use onionwire::hs::TorState; + +#[tokio::test(flavor = "multi_thread")] +#[ignore = "needs live Tor network"] +async fn shutdown_stops_the_node_and_later_calls_are_typed_errors() { + let _ = tracing_subscriber::fmt() + .with_env_filter( + tracing_subscriber::EnvFilter::try_from_default_env().unwrap_or_else(|_| "info".into()), + ) + .with_test_writer() + .try_init(); + + let root = tempfile::tempdir().expect("tempdir"); + let home = root.path().join("alice"); + unsafe { + std::env::set_var("ONIONWIRE_STORE_PASSPHRASE", "onionwire-test"); + } + + let node = Node::start(home.clone()).await.expect("start"); + + // `start` returns only after `wait_until_published`, so the node is + // reachable by the time a caller can call this — which must not read as + // `Stopped` or `Bootstrapping`. `DegradedReachable` is the honest answer + // when Arti says the service is degraded. + // + // This caught a real bug: `tor_state()` originally projected Arti's raw + // combined status, which is still `Bootstrapping` after a *successful* + // probe (that mismatch is what the 360s publish wait exists for), and which + // reads `Shutdown` on a service that has not started its reactor yet — so a + // live node reported `Stopped`. See `onion_reachable` in `src/node.rs`. + let started_state = node.tor_state(); + assert!( + matches!( + started_state, + TorState::Published | TorState::DegradedReachable + ), + "start returned Ok but tor_state() is {started_state:?}" + ); + + // A flush with nothing queued is a no-op that reports it, not an error. + let drained: FlushOutcome = node.flush().await.expect("flush on a live node"); + assert_eq!(drained.remaining, 0, "empty outbox: {drained:?}"); + + node.shutdown().await.expect("shutdown"); + + assert_eq!( + node.tor_state(), + TorState::Stopped, + "tor_state must report Stopped after shutdown" + ); + + // Second shutdown: idempotent at the node level — no panic, no repeat work. + node.shutdown().await.expect("shutdown is idempotent"); + + let err = node + .flush() + .await + .expect_err("flush after shutdown must be an error"); + assert!(err.contains("stopped"), "flush error was {err:?}"); + + let err = node + .send(&[0u8; 32], b"after shutdown") + .await + .expect_err("send after shutdown must be an error"); + assert!(err.contains("stopped"), "send error was {err:?}"); + + // `RotateResult` is not `Debug`, so match on the error instead of + // `expect_err`. + let err = node + .rotate() + .await + .err() + .expect("rotate after shutdown must be an error"); + assert!(err.contains("stopped"), "rotate error was {err:?}"); + + // The store file survives the checkpoint: stopping is not wiping. + assert!( + home.join("onionwire.db").exists(), + "shutdown must not delete the store" + ); +} \ No newline at end of file diff --git a/tests/tui_spec.rs b/tests/tui_spec.rs index 2310487..5715085 100644 --- a/tests/tui_spec.rs +++ b/tests/tui_spec.rs @@ -1,10 +1,13 @@ //! Spec implementation tests for docs/TUI.md (this card). //! Does not own `tests/tui_frames.rs` (PR #23). +use onionwire::Message; +use onionwire::outbox::{OutboxEntry, OutboxStatus}; use onionwire::qr; use onionwire::tui::{ - 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, + OutboxSummary, alert_line, ascii_chrome, chat_with_delivery, delivery_tag, draw_chat, + draw_share, draw_text_overlay, empty_friend_chat_text, help_overlay_text, main_footer_hints, + main_header_line, paste_screen_text, retry_in_text, roster_col_width, short_send_reason, status_footer, wrap_invite, }; use ratatui::Frame; @@ -376,3 +379,376 @@ fn ascii_switch_80x24_frame_is_pure_ascii() { println!("===== AFTER ascii share 80x24 =====\n{screen}"); unsafe { std::env::remove_var("ONIONWIRE_ASCII") }; } + +// --------------------------------------------------------------------------- +// Outbox delivery state (card t_d9a5b065) +// +// States come from the outbox API (`Outbox::pending` → `Queued` / `Sending` / +// `Failed`; delivered rows are deleted, so absence means `Sent`). No new wire +// prefix, no parallel state model. +// --------------------------------------------------------------------------- + +fn out_msg(body: &str) -> Message { + Message { + dir: "out".into(), + plaintext: body.as_bytes().to_vec(), + } +} + +fn in_msg(body: &str) -> Message { + Message { + dir: "in".into(), + plaintext: body.as_bytes().to_vec(), + } +} + +fn pending_row( + body: &str, + status: OutboxStatus, + attempts: u32, + next_in: i64, + now: i64, +) -> OutboxEntry { + OutboxEntry { + id: 1, + friend_pk: vec![9u8; 32], + message_id: 1, + body: body.as_bytes().to_vec(), + attempts, + next_attempt_at: now + next_in, + created_at: now, + status, + last_error: None, + } +} + +fn queued_row(body: &str, attempts: u32, next_in: i64, now: i64) -> OutboxEntry { + pending_row(body, OutboxStatus::Queued, attempts, next_in, now) +} + +fn sending_row(body: &str, now: i64) -> OutboxEntry { + pending_row(body, OutboxStatus::Sending, 1, 0, now) +} + +fn failed_row(body: &str, why: &str, now: i64) -> OutboxEntry { + pending_row(body, OutboxStatus::Failed(why.into()), 8, 0, now) +} + +/// Marker is everything after the two-space separator the render helper uses. +fn marker_of(line: &str) -> &str { + line.rsplit(" ").next().unwrap_or("") +} + +/// Force the non-ASCII (unicode glyph) path. Caller holds `ASCII_ENV`. +fn force_unicode_mode() { + unsafe { + std::env::remove_var("ONIONWIRE_ASCII"); + std::env::remove_var("NO_COLOR"); + } +} + +#[test] +fn queued_and_delivered_messages_render_different_markers() { + let guard = ASCII_ENV.lock().expect("ascii env lock"); + force_unicode_mode(); + let _guard = guard; + let now = 1_700_000_000; + let msgs = vec![out_msg("ping"), out_msg("pong")]; + let pending = vec![queued_row("pong", 2, 45, now)]; + + let (lines, summary) = chat_with_delivery(&msgs, &pending, now); + + assert!( + lines[0].contains('✓'), + "delivered row lost its mark: {:?}", + lines[0] + ); + assert!(!lines[0].contains("queued"), "{:?}", lines[0]); + assert!( + lines[1].contains('◷'), + "queued row lost its glyph: {:?}", + lines[1] + ); + assert!(lines[1].contains("queued"), "{:?}", lines[1]); + assert!( + lines[1].contains("try 2/8"), + "attempt count missing: {:?}", + lines[1] + ); + assert!( + lines[1].contains("retry 45s"), + "retry age missing: {:?}", + lines[1] + ); + assert_ne!( + marker_of(&lines[0]), + marker_of(&lines[1]), + "queued and delivered must not share a marker" + ); + assert_eq!(summary.queued, 1); + assert_eq!(summary.failed, 0); +} + +#[test] +fn delivery_markers_have_exercised_ascii_fallbacks() { + let _guard = ASCII_ENV.lock().expect("ascii env lock"); + unsafe { + std::env::set_var("ONIONWIRE_ASCII", "1"); + std::env::remove_var("NO_COLOR"); + } + let now = 500; + let msgs = vec![ + out_msg("alpha"), + out_msg("beta"), + out_msg("gamma"), + out_msg("delta"), + in_msg("epsilon"), + ]; + let pending = vec![ + failed_row("alpha", "connect peer.onion:80: connection timed out", now), + queued_row("beta", 1, 30, now), + sending_row("gamma", now), + ]; + + let (lines, summary) = chat_with_delivery(&msgs, &pending, now); + for line in &lines { + assert!( + line.is_ascii(), + "ASCII fallback missing, non-ASCII in {line:?}" + ); + } + assert_eq!(marker_of(&lines[0]), "failed: connection timed out"); + assert_eq!(marker_of(&lines[1]), "queued (try 1/8, retry 30s)"); + assert_eq!(marker_of(&lines[2]), "sending"); + assert_eq!(marker_of(&lines[3]), "ok", "delivered fallback is `ok`"); + assert_eq!(lines[4], "them: epsilon", "inbound rows carry no state"); + assert_eq!(summary.queued, 2, "queued + sending are both outstanding"); + assert_eq!(summary.failed, 1); + + unsafe { std::env::remove_var("ONIONWIRE_ASCII") }; +} + +#[test] +fn retry_age_and_failure_reason_are_short_forms() { + assert_eq!(retry_in_text(45), "retry 45s"); + assert_eq!(retry_in_text(59), "retry 59s"); + assert_eq!(retry_in_text(60), "retry 1m"); + assert_eq!(retry_in_text(720), "retry 12m"); + assert_eq!(retry_in_text(0), "retry now"); + assert_eq!(retry_in_text(-30), "retry now"); + + assert_eq!( + short_send_reason("connect abcdef.onion:80: connection timed out", 24), + "connection timed out" + ); + let long = short_send_reason("a-really-long-failure-description-here", 12); + assert!(long.chars().count() <= 12, "{long:?}"); + assert!( + long.contains('…') || long.contains("..."), + "truncation marker missing: {long:?}" + ); + assert_eq!(short_send_reason("nope", 24), "nope"); +} + +#[test] +fn delivery_tag_reads_the_outbox_status_enum() { + let guard = ASCII_ENV.lock().expect("ascii env lock"); + force_unicode_mode(); + let _guard = guard; + assert_eq!(delivery_tag(&OutboxStatus::Sent, 0, 0), "✓"); + assert_eq!( + delivery_tag(&OutboxStatus::Queued, 3, 120), + "◷ queued (try 3/8, retry 2m)" + ); + assert_eq!(delivery_tag(&OutboxStatus::Sending, 1, 0), "» sending"); + assert_eq!( + delivery_tag(&OutboxStatus::Failed("connect x:80: nope".into()), 8, 0), + "✗ failed: nope" + ); +} + +#[test] +fn footer_summary_counts_queued_and_keeps_fail_closed() { + let none = OutboxSummary::default(); + assert_eq!(none.note(), None); + + let queued = OutboxSummary { + queued: 2, + failed: 0, + first_error: None, + }; + assert_eq!(queued.note().as_deref(), Some("2 queued")); + + let failed = OutboxSummary { + queued: 0, + failed: 1, + first_error: Some("connect peer.onion:80: connection timed out".into()), + }; + let note = failed.note().expect("failed rows must produce a note"); + assert!(note.starts_with("send failed:"), "{note:?}"); + assert!(note.contains("connection timed out"), "{note:?}"); + + let mixed = OutboxSummary { + queued: 3, + failed: 1, + first_error: Some("connect peer.onion:80: connection timed out".into()), + }; + let mixed_note = mixed.note().expect("mixed rows must produce a note"); + assert!(mixed_note.contains("3 queued"), "{mixed_note:?}"); + assert!(mixed_note.contains("send failed"), "{mixed_note:?}"); + + // Fail-closed copy stays visible in the real footer at the 80-col floor. + let line = status_footer(80, FP, ONION, Some(¬e), main_footer_hints()); + assert!( + line.chars().count() <= 80, + "{} {line:?}", + line.chars().count() + ); + assert!(line.contains("send failed"), "footer dropped it: {line:?}"); + assert!(line.contains("TOR") && line.contains("? help"), "{line:?}"); + + let queued_line = status_footer(80, FP, ONION, queued.note().as_deref(), main_footer_hints()); + assert!(queued_line.contains("2 queued"), "{queued_line:?}"); + assert!(queued_line.chars().count() <= 80); + + // `! ` ornament (colour off) still lands on the derived failing note. + let _guard = ASCII_ENV.lock().expect("ascii env lock"); + unsafe { std::env::set_var("NO_COLOR", "1") }; + let no_color = status_footer(80, FP, ONION, Some(¬e), main_footer_hints()); + assert!(no_color.contains("! send failed"), "{no_color:?}"); + unsafe { std::env::remove_var("NO_COLOR") }; +} + +/// The card's width criterion: draw the real helpers at the documented floor +/// (80x24) and prove nothing in the chat/footer region exceeds the width, and +/// that an over-long row wraps in the pane instead of being clipped. +#[test] +fn chat_and_footer_rows_fit_80x24_and_wrap_instead_of_clipping() { + let guard = ASCII_ENV.lock().expect("ascii env lock"); + force_unicode_mode(); + let _guard = guard; + let now = 1_700_000_000; + let long = "this is a very long chat line that should wrap inside the chat pane instead of running off the right edge of an 80-column terminal and colliding with the roster border"; + let msgs = vec![out_msg("ok"), in_msg("pong"), out_msg(long)]; + let pending = vec![queued_row(long, 3, 45, now)]; + + let (lines, summary) = chat_with_delivery(&msgs, &pending, now); + for line in lines.iter().take(2) { + assert!( + line.chars().count() <= 80, + "short row wider than 80: {} {line:?}", + line.chars().count() + ); + } + let footer = status_footer( + 80, + FP, + ONION, + summary.note().as_deref(), + main_footer_hints(), + ); + assert!(footer.chars().count() <= 80, "{footer:?}"); + + let backend = TestBackend::new(80, 24); + let mut terminal = Terminal::new(backend).expect("terminal"); + terminal + .draw(|f| { + let area = f.area(); + let cols = Layout::vertical([Constraint::Min(3), Constraint::Length(1)]).split(area); + draw_chat(f, cols[0], &lines, Some("alice"), true, 0); + f.render_widget(Paragraph::new(footer.clone()), cols[1]); + }) + .expect("draw"); + + let buf = terminal.backend().buffer(); + let mut screen = String::new(); + for y in 0..24u16 { + for x in 0..80u16 { + screen.push_str(buf[(x, y)].symbol()); + } + screen.push('\n'); + } + for (y, row) in screen.lines().enumerate() { + assert!( + row.chars().count() <= 80, + "80x24 chat/footer row {y} wider than the terminal: {} {row:?}", + row.chars().count() + ); + } + assert!( + screen.contains('◷'), + "queued glyph missing from frame:\n{screen}" + ); + assert!(screen.contains("queued"), "queued word missing:\n{screen}"); + assert!(screen.contains('✓'), "delivered glyph missing:\n{screen}"); + assert!( + screen.contains("with the roster border"), + "long row was clipped, not wrapped:\n{screen}" + ); + assert!( + screen.contains("1 queued"), + "footer summary missing:\n{screen}" + ); + println!("===== AFTER outbox 80x24 (real draw_chat + status_footer) =====\n{screen}"); +} + +/// The renderer consumes the real outbox API, not a hand-written fixture: a +/// genuine unreachable-onion send leaves a `Queued` row, and that row is what +/// the chat line and the footer note are built from. +#[tokio::test] +async fn renders_a_queued_row_from_a_real_outbox_send() { + use onionwire::Store; + use onionwire::outbox::{BoxFut, Deliverer, Outbox}; + use std::sync::Arc; + + struct Dead; + impl Deliverer for Dead { + fn deliver<'a>( + &'a self, + _onion: &'a str, + _pinned_id: &'a [u8], + _prekey: &'a [u8], + _plaintext: &'a [u8], + ) -> BoxFut<'a, Result<(), String>> { + Box::pin(async { Err("connect dead.onion:80: timed out".to_string()) }) + } + } + + let dir = tempfile::tempdir().expect("tempdir"); + let store = Store::open_at_with_passphrase(dir.path(), "tui-spec-pass").expect("open store"); + let pk = [1u8; 32]; + store + .upsert_friend(&pk, "dead.onion", None) + .expect("friend"); + store.set_friend_prekey(&pk, &[7u8; 32]).expect("prekey"); + let store = Arc::new(std::sync::Mutex::new(store)); + let outbox = Outbox::new(Arc::clone(&store), Arc::new(Dead)); + + assert_eq!( + outbox.send(&pk, b"queued for a dead peer").await, + Ok(OutboxStatus::Queued) + ); + let pending = outbox.pending(&pk).expect("pending rows"); + assert_eq!(pending.len(), 1, "one queued row"); + let msgs = store + .lock() + .expect("store lock") + .list_messages(&pk) + .expect("messages"); + + let now = pending[0].next_attempt_at - 45; + let (lines, summary) = chat_with_delivery(&msgs, &pending, now); + assert_eq!(lines.len(), 1); + assert!( + lines[0].contains("queued (try 1/8, retry 45s)"), + "real outbox row did not render: {:?}", + lines[0] + ); + assert_eq!(summary.note().as_deref(), Some("1 queued")); + + // And once a send crosses the circuit the row is gone, so the same message + // renders as delivered. + let (delivered, summary) = chat_with_delivery(&msgs, &[], now); + assert!(delivered[0].contains('✓'), "{:?}", delivered[0]); + assert_eq!(summary.note(), None); +} 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() } 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()); +}