diff --git a/crates/onionwire-sdk/src/lib.rs b/crates/onionwire-sdk/src/lib.rs index e90c7fa..b81f016 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,76 @@ 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. + /// + /// Idempotent and safe to call twice, including from two threads: the + /// second call is a no-op returning `Ok`. After it, every other method on + /// this handle — including `send` — returns `WireError.Stopped` instead of + /// touching a dead client or panicking. + /// + /// 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 +306,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 +322,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 +359,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 +369,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 +382,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 +409,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/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/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/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