diff --git a/docs/THREAT_MODEL.md b/docs/THREAT_MODEL.md index 006ee1f..ac04975 100644 --- a/docs/THREAT_MODEL.md +++ b/docs/THREAT_MODEL.md @@ -115,7 +115,17 @@ the app does not pick a public remote node for them. - **Loopback** — same privacy as (1); the user owns `monerod`. - **`.onion`** — chain traffic over Tor through a localhost SOCKS5 listener the app provides for the wallet child (not the messenger’s Arti - `connect()`, and not a C-tor fallback for chat). Tor hides the transport. + `connect()`, and not a C-tor fallback for chat). That listener is the + bundled `arti` **binary** run as a child (`arti proxy -p `) — a + second, separate Tor client with its own state and cache dirs, because + `arti-client` 0.46 exposes no SOCKS listener API. It is TCP loopback only + (`arti proxy -p` binds `127.0.0.1`/`::1`; arti 2.6.0 / `tor-config` 0.46 + have no Unix-socket listen target — arti#1965), and the port is usable by + any local process at the user's privilege level: it is an app-private port, + not an access-controlled one. The app gates the spawn on the unlocked store + and waits ≤20s for the listener to accept before starting the wallet child, + so a dead proxy fails visibly instead of hanging. The SOCKS child stops + with the wallet child. Tor hides the transport. The daemon operator still sees the wallet’s addresses during sync. The host is the trust boundary. - **Clearnet** — only if the user typed it. Not a default, not implied. @@ -145,7 +155,11 @@ That socket is the app talking to the wallet process, not to the chain. **Chain** traffic is the wallet child’s connection to a Monero daemon. It is off unless the user opted into a wallet and chose a chain source: spawned local `monerod` (loopback), or a daemon address they entered. A `.onion` daemon is -reached through a localhost SOCKS5 proxy used only by that wallet child. A +reached through a localhost SOCKS5 proxy used only by that wallet child: the +bundled `arti` binary run as `arti proxy -p `, whose `--proxy` target is +`127.0.0.1` and whose `.onion` name travels inside the SOCKS request (Monero's +SOCKS5 client sends the domain-name form, so no local DNS runs on it). The +messenger's in-process Arti client is never handed to the wallet child. A clearnet daemon address is an explicit user choice — a clearnet socket they asked for — not the messenger path and not a hidden default. diff --git a/docs/WALLET.md b/docs/WALLET.md index 4be32f5..a86f22c 100644 --- a/docs/WALLET.md +++ b/docs/WALLET.md @@ -33,6 +33,8 @@ export an env var: - **`monerod`** is spawned too when the chain source is *local*: `--non-interactive --data-dir --rpc-bind-ip 127.0.0.1 --rpc-bind-port 18081`. One box, one daemon: the wallet child dials it at `127.0.0.1:18081`. +- **`arti`** is spawned as a SOCKS child only when the chain source is a + `.onion` daemon: `arti proxy -p ` (see below). - `--trusted-daemon` is never passed. A remote daemon stays untrusted. - The wallet dir is created `0700` and the wallet file is kept `0600` — it is a spend authority. @@ -67,14 +69,58 @@ ChainSource::Remote { host, port } a daemon address you typed sync, and (on Android) the daemon not always running. 2. **A daemon address you supply** — becomes `--daemon-address` on the wallet child. Loopback if you already run `monerod`. `.onion` if you want chain - traffic over Tor — that needs a SOCKS proxy for the wallet child and is **not - implemented here**: configuring a `.onion` host today fails with a clear error - instead of silently dialling clearnet. Clearnet only if you type it — your ISP - sees Monero-node traffic; it is never a default. + traffic over Tor (see *Chain traffic over Tor* below). Clearnet only if you + type it — your ISP sees Monero-node traffic; it is never a default. The port is a convention, not a constant: restricted RPC on `18089` is common, but you supply it. +### Chain traffic over Tor (`.onion` daemons) + +A `.onion` daemon cannot be dialled directly, and OnionWire does not fall back +to a clearnet resolve. The wallet child is an external C++ binary, so it reaches +Tor the only way it can: through a SOCKS proxy the app provides. + +- The app runs the **bundled `arti` binary** as a child: + `arti proxy -p `. `arti-client` 0.46 has no SOCKS + listener API — the SOCKS listener lives in the `arti` *binary* — so this is a + second, separate Tor client, not the messenger's in-process one. There is no + C-tor and no system `tor`. +- The listener is **TCP loopback only**. `arti proxy -p ` binds localhost + (`127.0.0.1` and `::1`) and nothing else, and there is nothing safer to + prefer: `arti` 2.6.0 / `tor-config` 0.46 have no Unix-socket listen target + (`Listen` is IP-only; arti's own port record calls AF_UNIX future work, + arti#1965). The port is app-private in practice, but any local process with + user-level access can also use it — that is the honest statement of the + boundary, not a claim of access control. +- The wallet child is then spawned with + `--proxy socks5://127.0.0.1:` **and** `--daemon-address :`. + The `socks5://` scheme is explicit: Monero's `--proxy` defaults to SOCKS4a for + a bare `host:port` (`docs/proxies.md` in the Monero tree). The `.onion` name + goes to the proxy inside the SOCKS request — Monero's SOCKS5 client uses the + domain-name form — so **no local DNS** runs on the onion target. +- The SOCKS child gets **its own state and cache dirs** + (`$ONIONWIRE_HOME/wallet/arti-socks/{state,cache}`). The messenger's Arti + state is not shared with it. +- Starting it is gated on the same credential material as everything else: the + SOCKS child is only spawned from `WalletChild::start(&store)`, which needs the + already-unlocked store. +- The app waits **up to 20s** for the SOCKS listener to accept a connection + before it spawns the wallet child. A dead proxy is a visible error, not a + wallet screen that hangs dialling a daemon. Arti binds its listener before it + bootstraps, so this is a listener check, not a Tor-bootstrap check. +- The SOCKS child stops with the wallet child; a killed wallet child leaves no + orphaned listener behind. + +**Tor hides the transport, not the host.** The daemon operator still sees the +wallet's addresses (and the transaction set it is scanning) during sync. A +`.onion` address protects the path between you and that operator, nothing more. + +The TUI copy for a chain source says this in one line +(`WalletChild::chain_copy`): `.onion` → "over Tor … the daemon operator still +sees your addresses during sync"; clearnet → "the daemon operator and your ISP +see the traffic". + ### Readiness, and why it is not a guess `chain_ready()` asks the wallet RPC `get_info` and requires **`synchronized == diff --git a/src/wallet_child.rs b/src/wallet_child.rs index 12f96df..44dc937 100644 --- a/src/wallet_child.rs +++ b/src/wallet_child.rs @@ -9,15 +9,26 @@ //! * The RPC credentials are generated once, sealed with the store data key and //! kept in the encrypted SQLCipher store. They are never a plaintext file. //! * The chain source is the user's explicit choice ([`ChainSource`]) — never a -//! compiled-in public node. A `.onion` daemon needs a SOCKS proxy, which is a -//! separate card: here it is refused with a clear error. +//! compiled-in public node. +//! * A `.onion` daemon is reached through a SOCKS child: the bundled `arti` +//! binary run as `arti proxy -p `, with **TCP loopback only** (arti +//! 2.6.0 / tor-config 0.46 have no AF_UNIX listener — `Listen` is IP-only and +//! arti's `port_info` says AF_UNIX is future work, arti#1965). The wallet +//! child is then pointed at it with `--proxy socks5://127.0.0.1:` +//! *and* `--daemon-address :`. The messenger's in-process +//! `arti-client` is never handed to the wallet child, and C-tor is never +//! used. +//! * The two Tor clients do not share state: the SOCKS child gets its own +//! `state_dir`/`cache_dir` under the wallet dir. //! * `--trusted-daemon` is never passed: a remote daemon is untrusted. use std::fs; +use std::net::{Ipv4Addr, SocketAddr, TcpStream}; use std::os::unix::fs::PermissionsExt; use std::path::{Path, PathBuf}; use std::process::{Child, Command}; use std::sync::Mutex; +use std::time::{Duration, Instant}; use rand::RngCore; use zeroize::Zeroizing; @@ -32,6 +43,26 @@ pub const DEFAULT_MONEROD_RPC_PORT: u16 = 18081; /// Name of the `monero-wallet-rpc` binary when the caller does not point at one. pub const DEFAULT_WALLET_RPC_BIN: &str = "monero-wallet-rpc"; +/// Name of the `arti` binary the SOCKS child runs when the caller does not +/// point at one. `arti proxy -p `; there is no in-process SOCKS listener. +pub const DEFAULT_ARTI_BIN: &str = "arti"; + +/// How long the app waits for the SOCKS listener to accept a connection before +/// it gives up and reports the failure instead of spawning a wallet child that +/// can only hang. Arti binds its listener before it bootstraps (bootstrap is +/// on-demand), so this is a listener budget, not a Tor-bootstrap budget. +pub const SOCKS_READY_TIMEOUT: Duration = Duration::from_secs(20); + +/// Per-attempt connect budget for the SOCKS readiness probe. +pub const SOCKS_PROBE_TIMEOUT: Duration = Duration::from_millis(500); + +/// Gap between readiness-probe attempts. +pub const SOCKS_PROBE_INTERVAL: Duration = Duration::from_millis(100); + +/// The scheme Monero's `--proxy` needs for SOCKS5. A bare `host:port` means +/// SOCKS4a (docs/proxies.md), which is *not* what this app asks for. +pub const SOCKS5_SCHEME: &str = "socks5://"; + /// Errors from wallet child setup and lifecycle. #[derive(Debug)] pub struct ChildError(String); @@ -46,13 +77,22 @@ impl std::error::Error for ChildError {} type Result = std::result::Result; -/// The app-owned wallet child pair (`monerod` when local, `monero-wallet-rpc`). +/// The app-owned wallet child set (`monerod` when local, `arti proxy` when the +/// daemon is a `.onion`, `monero-wallet-rpc` always unless `None`). pub struct WalletChild { source: ChainSource, wallet_rpc_bin: PathBuf, + arti_bin: PathBuf, wallet_dir: PathBuf, wallet_filename: String, + /// Pinned SOCKS listen port. `None` (the default) means a random free + /// loopback port, exactly like the wallet RPC port. + socks_port: Option, + /// Readiness budget for the SOCKS listener. Tests shrink it; production + /// uses [`SOCKS_READY_TIMEOUT`]. + socks_ready_timeout: Duration, monerod: Mutex>, + socks: Mutex>, wallet_rpc: Mutex>, } @@ -75,9 +115,13 @@ impl WalletChild { Ok(Self { source, wallet_rpc_bin: PathBuf::from(DEFAULT_WALLET_RPC_BIN), + arti_bin: PathBuf::from(DEFAULT_ARTI_BIN), wallet_dir, wallet_filename, + socks_port: None, + socks_ready_timeout: SOCKS_READY_TIMEOUT, monerod: Mutex::new(None), + socks: Mutex::new(None), wallet_rpc: Mutex::new(None), }) } @@ -88,6 +132,26 @@ impl WalletChild { self } + /// Point at a specific `arti` binary (explicit config, tests). + pub fn with_arti_bin(mut self, bin: PathBuf) -> Self { + self.arti_bin = bin; + self + } + + /// Pin the SOCKS listen port instead of taking a random free loopback one. + /// Loopback only either way: `arti proxy -p ` binds `127.0.0.1` and + /// `::1` and nothing else. + pub fn with_socks_port(mut self, port: u16) -> Self { + self.socks_port = Some(port); + self + } + + /// Shrink the SOCKS readiness budget (tests). + pub fn with_socks_ready_timeout(mut self, budget: Duration) -> Self { + self.socks_ready_timeout = budget; + self + } + /// The user's chain-source choice. `None` is receive-only: no child at all. pub fn chain_source(&self) -> &ChainSource { &self.source @@ -106,11 +170,18 @@ impl WalletChild { !matches!(self.source, ChainSource::None) } + /// Does this host name a Tor onion service? Only `.onion` daemons need the + /// SOCKS child; a loopback or clearnet host the user typed does not. + pub fn is_onion_host(host: &str) -> bool { + host.trim().to_ascii_lowercase().ends_with(".onion") + } + /// Is a tracked child still alive? Polls the process table; an exited child /// is reaped here so a later `stop` is a no-op. pub fn running(&self) -> bool { let _ = self.reap_exited(); self.monerod.lock().map(|g| g.is_some()).unwrap_or(false) + || self.socks.lock().map(|g| g.is_some()).unwrap_or(false) || self.wallet_rpc.lock().map(|g| g.is_some()).unwrap_or(false) } @@ -123,7 +194,7 @@ impl WalletChild { fn reap_exited(&self) -> bool { let mut exited = false; - for slot in [&self.monerod, &self.wallet_rpc] { + for slot in [&self.monerod, &self.socks, &self.wallet_rpc] { let Ok(mut guard) = slot.lock() else { continue; }; @@ -139,6 +210,88 @@ impl WalletChild { exited } + /// The exact argv used to spawn `arti` as the SOCKS child: `arti proxy -p + /// `, with its *own* state and cache dirs so the two Tor clients in + /// one app never share state silently. + /// + /// `-p` is the arti CLI's `socks-port` argument (arti 2.6.0 `src/lib.rs`); + /// it binds localhost only (`Listen::new_localhost`, tor-config 0.46 + /// `listen.rs`: "We interpret standalone ports to be localhost + /// addresses" — `[::1, 127.0.0.1]`). There is no Unix-socket listen target + /// to prefer: `Listen` is IP-only and arti's `port_info` says AF_UNIX is + /// future work (arti#1965). + pub fn arti_proxy_argv( + bin: &Path, + port: u16, + state_dir: &Path, + cache_dir: &Path, + ) -> Vec { + vec![ + bin.display().to_string(), + "proxy".into(), + "-p".into(), + port.to_string(), + "-o".into(), + format!("storage.state_dir=\"{}\"", state_dir.display()), + "-o".into(), + format!("storage.cache_dir=\"{}\"", cache_dir.display()), + ] + } + + /// The `--proxy` value the wallet child is given. `socks5://` is explicit + /// on purpose: Monero's `--proxy` defaults to SOCKS4a for a bare + /// `host:port` (`docs/proxies.md`). + pub fn socks_proxy_url(port: u16) -> String { + format!("{SOCKS5_SCHEME}127.0.0.1:{port}") + } + + /// Wait for the SOCKS listener to accept a connection, with an explicit + /// budget so a dead proxy fails visibly instead of hanging the wallet + /// screen. + /// + /// This proves the *listener* is up (arti binds before it bootstraps); + /// it does not prove the Tor circuit works. It also does not resolve the + /// `.onion` name locally — the name travels inside the SOCKS request. + pub fn socks_listener_ready(port: u16, budget: Duration) -> Result<()> { + let addr = SocketAddr::from((Ipv4Addr::LOCALHOST, port)); + let deadline = Instant::now() + budget; + let mut last = None; + while Instant::now() <= deadline { + match TcpStream::connect_timeout(&addr, SOCKS_PROBE_TIMEOUT) { + Ok(_) => return Ok(()), + Err(e) => last = Some(e), + } + std::thread::sleep(SOCKS_PROBE_INTERVAL); + } + Err(ChildError(format!( + "SOCKS proxy on 127.0.0.1:{port} did not accept a connection within {}s \ + ({}) — not spawning a wallet child against a dead proxy", + budget.as_secs_f32(), + last.map(|e| e.to_string()).unwrap_or_default() + ))) + } + + /// The honest one-liner a UI can show for the configured chain source. A + /// `.onion` daemon buys transport privacy, not host privacy: the daemon + /// operator still sees the wallet's addresses during sync. + pub fn chain_copy(source: &ChainSource) -> String { + match source { + ChainSource::None => "receive-only: no daemon, no chain traffic".into(), + ChainSource::Local { .. } => { + "local monerod on this box (loopback): no Tor, no remote operator".into() + } + ChainSource::Remote { host, port } if Self::is_onion_host(host) => format!( + "remote {host}:{port} over Tor (SOCKS5 on loopback, never clearnet) — Tor hides \ + the transport, not the host: the daemon operator still sees your addresses \ + during sync" + ), + ChainSource::Remote { host, port } => format!( + "remote {host}:{port} over clearnet, because you typed it — the daemon operator \ + and your ISP see the traffic" + ), + } + } + /// The `--daemon-address` for each chain source. A local source is the /// loopback daemon this struct owns; a remote one is exactly what the user /// typed. @@ -181,12 +334,18 @@ impl WalletChild { /// The exact argv used to spawn `monero-wallet-rpc`. Digest login is /// mandatory and the bind is loopback; `--trusted-daemon` is deliberately /// absent. + /// + /// `socks_proxy` is the wallet child's `--proxy` target. It is only passed + /// for a `.onion` daemon, and it is always a `socks5://127.0.0.1:` + /// string: the wallet child talks plain SOCKS5 to the app's own `arti proxy` + /// child. The messenger's in-process Arti client is never handed to it. pub fn wallet_rpc_argv( bin: &Path, port: u16, login: &str, wallet_dir: &Path, daemon_address: Option<&str>, + socks_proxy: Option<&str>, ) -> Vec { let mut argv = vec![ bin.display().to_string(), @@ -203,30 +362,38 @@ impl WalletChild { argv.push("--daemon-address".into()); argv.push(addr.to_string()); } + if let Some(proxy) = socks_proxy { + argv.push("--proxy".into()); + argv.push(proxy.to_string()); + } argv } /// Start the children (idempotent per source) and hand back the loopback /// client the app should talk to. /// - /// `None` -> `Ok(None)`: receive-only, nothing is spawned. + /// `None` -> `Ok(None)`: receive-only, nothing is spawned. The `Store` is + /// what gates every spawn: the SOCKS child, like the wallet child, is only + /// reachable through an unlocked store. pub fn start(&self, store: &Store) -> Result> { if !self.is_enabled() { return Ok(None); } - if let ChainSource::Remote { host, .. } = &self.source - && host.trim().to_ascii_lowercase().ends_with(".onion") - { - return Err(ChildError( - "remote .onion daemon needs a SOCKS proxy — configure the local/remote \ - chain source instead (separate card)" - .into(), - )); - } if self.running() { return Err(ChildError("wallet child already running".into())); } + match self.start_children(store) { + Ok(client) => Ok(client), + Err(e) => { + // A failure after the SOCKS child came up must not leave the + // listener (or monerod) orphaned behind the error. + let _ = self.stop(); + Err(e) + } + } + } + fn start_children(&self, store: &Store) -> Result> { // Local chain source: own monerod first, so the wallet child has a // daemon to dial. if let ChainSource::Local { @@ -244,6 +411,16 @@ impl WalletChild { *guard = Some(child); } + // A `.onion` daemon is only reachable through SOCKS. The app bundles the + // `arti` binary as that proxy; it must be up before the wallet child + // starts, or the wallet child sits there failing to dial its daemon. + let socks_proxy = match &self.source { + ChainSource::Remote { host, .. } if Self::is_onion_host(host) => { + Some(self.start_socks_proxy()?) + } + _ => None, + }; + let (user, pass) = self.creds(store)?; let port = Self::pick_port()?; let login = format!("{user}:{}", pass.as_str()); @@ -254,6 +431,7 @@ impl WalletChild { &login, &self.wallet_dir, daemon.as_deref(), + socks_proxy.as_deref(), ); let child = spawn(&argv, "monero-wallet-rpc")?; { @@ -275,10 +453,43 @@ impl WalletChild { })) } - /// Stop both children. Idempotent, and tolerant of a child that already - /// exited on its own. + /// Spawn `arti proxy -p ` and hand back its wallet-child-facing + /// `--proxy` value. + /// + /// Its state and cache live under the wallet dir, not in the messenger's + /// Arti state dir: the two Tor clients in this app do not share state. + fn start_socks_proxy(&self) -> Result { + let port = match self.socks_port { + Some(p) => p, + None => Self::pick_port()?, + }; + let state_dir = self.wallet_dir.join("arti-socks").join("state"); + let cache_dir = self.wallet_dir.join("arti-socks").join("cache"); + for dir in [state_dir.parent(), Some(&state_dir), Some(&cache_dir)] + .into_iter() + .flatten() + { + create_dir_700(dir).map_err(|e| ChildError(format!("arti dir: {e}")))?; + } + let argv = Self::arti_proxy_argv(&self.arti_bin, port, &state_dir, &cache_dir); + let child = spawn(&argv, "arti proxy")?; + { + let mut guard = self + .socks + .lock() + .map_err(|e| ChildError(format!("socks lock: {e}")))?; + *guard = Some(child); + } + Self::socks_listener_ready(port, self.socks_ready_timeout)?; + Ok(Self::socks_proxy_url(port)) + } + + /// Stop every child. Idempotent, and tolerant of a child that already + /// exited on its own. The wallet child goes first so no wallet RPC can be + /// mid-request against the chain, then the SOCKS listener, then `monerod`. pub fn stop(&self) -> Result<()> { kill_slot(&self.wallet_rpc, "monero-wallet-rpc")?; + kill_slot(&self.socks, "arti proxy")?; kill_slot(&self.monerod, "monerod")?; Ok(()) } @@ -457,6 +668,15 @@ mod tests { dir } + /// Fake children live in their own dir: `Store::open_at*` already creates + /// `/arti` and `/cache` (the app's Arti state), so a fake `arti` + /// at the home root would collide with that directory. + fn fake_dir(dir: &Path) -> PathBuf { + let path = dir.join("fake-bins"); + fs::create_dir_all(&path).unwrap(); + path + } + fn open_store(dir: &Path) -> Store { Store::open_at_with_passphrase(dir, "child-test-pass").expect("open store") } @@ -512,27 +732,370 @@ mod tests { fn none_source_is_disabled_and_starts_nothing() { let dir = tmp_dir("none"); let store = open_store(&dir); - let child = WalletChild::new(ChainSource::None, dir.join("wallet"), None).unwrap(); + let arti_log = dir.join("arti.argv"); + let child = WalletChild::new(ChainSource::None, dir.join("wallet"), None) + .unwrap() + .with_arti_bin(fake_bin(&fake_dir(&dir), "arti", &arti_log)); assert!(!child.is_enabled()); assert!(child.start(&store).unwrap().is_none()); assert!(!child.running()); + assert!( + !arti_log.exists(), + "receive-only must not spawn the SOCKS child" + ); + } + + /// A live listener for the readiness gate to dial. `arti proxy -p ` + /// binds localhost only, so 127.0.0.1 is exactly what the gate probes. + fn held_loopback_port() -> (std::net::TcpListener, u16) { + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let port = listener.local_addr().unwrap().port(); + (listener, port) + } + + fn freed_loopback_port() -> u16 { + held_loopback_port().1 + } + + /// A fake child that also records its pid, so a test can prove the process + /// is gone after `stop` — an orphaned SOCKS listener is the failure mode. + fn fake_bin_with_pid(dir: &Path, name: &str, log: &Path, pid_file: &Path) -> PathBuf { + let path = dir.join(name); + let mut f = fs::File::create(&path).unwrap(); + writeln!(f, "#!/bin/sh").unwrap(); + writeln!(f, "echo $$ > '{}'", pid_file.display()).unwrap(); + writeln!(f, ": > '{}'", log.display()).unwrap(); + writeln!( + f, + "for a in \"$@\"; do printf '%s\\n' \"$a\" >> '{}'; done", + log.display() + ) + .unwrap(); + writeln!(f, "sleep 30").unwrap(); + drop(f); + let mut perms = fs::metadata(&path).unwrap().permissions(); + perms.set_mode(0o700); + fs::set_permissions(&path, perms).unwrap(); + path + } + + /// Poll for the child's pid file: the script writes it after exec. + fn child_pid(pid_file: &Path) -> u32 { + for _ in 0..60 { + if let Ok(raw) = fs::read_to_string(pid_file) + && let Ok(pid) = raw.trim().parse::() + { + return pid; + } + std::thread::sleep(std::time::Duration::from_millis(50)); + } + panic!("child never wrote {}", pid_file.display()); + } + + /// The process must actually be gone, not merely dropped from a slot. + fn wait_for_process_exit(pid: u32) { + let proc_dir = PathBuf::from(format!("/proc/{pid}")); + for _ in 0..60 { + if !proc_dir.exists() { + return; + } + std::thread::sleep(std::time::Duration::from_millis(50)); + } + panic!("pid {pid} is still alive — orphaned child"); + } + + fn pairs(argv: &[String]) -> Vec<(String, String)> { + argv.windows(2) + .map(|w| (w[0].clone(), w[1].clone())) + .collect() } #[test] - fn onion_remote_daemon_is_refused_without_a_socks_proxy() { - let dir = tmp_dir("onion"); + fn arti_proxy_argv_binds_a_loopback_port_and_isolates_state() { + let dir = tmp_dir("arti-argv"); + let bin = PathBuf::from("/opt/arti/arti"); + let state = dir.join("wallet").join("arti-socks").join("state"); + let cache = dir.join("wallet").join("arti-socks").join("cache"); + let argv = WalletChild::arti_proxy_argv(&bin, 45123, &state, &cache); + assert_eq!(argv[0], bin.display().to_string()); + assert_eq!(argv[1], "proxy"); + assert!( + pairs(&argv).contains(&("-p".into(), "45123".into())), + "{argv:?}" + ); + // `-p` binds localhost only (arti's `socks-port` arg); there is no + // Unix-socket listen target in arti 2.6.0 / tor-config 0.46. + assert!(!argv.iter().any(|a| a == "--port"), "{argv:?}"); + assert!( + argv.iter() + .any(|a| a.contains(&state.display().to_string())), + "the SOCKS child gets its own state dir: {argv:?}" + ); + assert!( + argv.iter() + .any(|a| a.contains(&cache.display().to_string())), + "the SOCKS child gets its own cache dir: {argv:?}" + ); + } + + #[test] + fn onion_remote_points_the_wallet_child_at_the_socks_proxy_and_the_onion() { + let dir = tmp_dir("onion-argv"); + let bin = PathBuf::from("/opt/monero/monero-wallet-rpc"); + let proxy = WalletChild::socks_proxy_url(45678); + let argv = WalletChild::wallet_rpc_argv( + &bin, + 39127, + "owuser:owpass", + &dir, + Some("abcdefghijklmnop.onion:18089"), + Some(&proxy), + ); + let pairs = pairs(&argv); + assert!( + pairs.contains(&("--proxy".into(), "socks5://127.0.0.1:45678".into())), + "{argv:?}" + ); + assert!( + argv.iter().any(|a| a.contains("127.0.0.1:45678")), + "the literal loopback:port the card asks for: {argv:?}" + ); + assert!( + pairs.contains(&( + "--daemon-address".into(), + "abcdefghijklmnop.onion:18089".into() + )), + "{argv:?}" + ); + // The wallet child speaks plain SOCKS5 to loopback. It never gets the + // messenger's in-process Arti client, and the daemon stays untrusted. + assert!(!argv.iter().any(|a| a == "--trusted-daemon"), "{argv:?}"); + } + + #[test] + fn onion_detection_is_case_insensitive_and_needs_the_suffix() { + assert!(WalletChild::is_onion_host("abcdefgh.onion")); + assert!(WalletChild::is_onion_host("ABCDEFGH.ONION")); + assert!(WalletChild::is_onion_host(" abcdefgh.onion ")); + assert!(!WalletChild::is_onion_host("onion.example.com")); + assert!(!WalletChild::is_onion_host("127.0.0.1")); + assert!(!WalletChild::is_onion_host("node.onion.example.com")); + } + + #[test] + fn chain_copy_says_tor_hides_the_transport_not_the_host() { + let onion = WalletChild::chain_copy(&ChainSource::Remote { + host: "abcdefghijklmnop.onion".into(), + port: 18089, + }); + assert!(onion.contains("Tor"), "{onion}"); + assert!( + onion.contains("hides the transport, not the host"), + "{onion}" + ); + assert!( + onion.contains("operator still sees your addresses"), + "{onion}" + ); + + let clearnet = WalletChild::chain_copy(&ChainSource::Remote { + host: "node.example.com".into(), + port: 18089, + }); + assert!(clearnet.contains("clearnet"), "{clearnet}"); + assert!(!clearnet.contains("Tor"), "{clearnet}"); + + let local = WalletChild::chain_copy(&local_source( + Path::new("/tmp"), + PathBuf::from("/usr/bin/monerod"), + )); + assert!(local.contains("local monerod"), "{local}"); + assert_eq!( + WalletChild::chain_copy(&ChainSource::None), + "receive-only: no daemon, no chain traffic" + ); + } + + /// The readiness gate is real code, not a stub: it accepts a listener that + /// is up and gives up with a typed error, inside its budget, when nothing + /// is listening. + #[test] + fn socks_listener_ready_accepts_a_live_listener_and_times_out_without_one() { + let (held, port) = held_loopback_port(); + assert!( + WalletChild::socks_listener_ready(port, Duration::from_millis(200)).is_ok(), + "a live listener must pass" + ); + drop(held); + + let started = std::time::Instant::now(); + let err = WalletChild::socks_listener_ready(port, Duration::from_millis(200)) + .unwrap_err() + .to_string(); + assert!(err.contains("SOCKS"), "{err}"); + assert!(err.contains(&port.to_string()), "{err}"); + assert!( + started.elapsed() < Duration::from_secs(5), + "the probe must honour its budget, took {:?}", + started.elapsed() + ); + } + + /// The spawn path: a `.onion` remote starts `arti proxy -p ` first, + /// the wallet child is pointed at it, and stopping the wallet child takes + /// the SOCKS listener with it. + #[test] + fn onion_remote_start_spawns_the_socks_child_then_stops_it_with_the_wallet() { + let dir = tmp_dir("onion-start"); let store = open_store(&dir); + let arti_log = dir.join("arti.argv"); + let arti_pid = dir.join("arti.pid"); + let rpc_log = dir.join("wallet-rpc.argv"); + let rpc_pid = dir.join("wallet-rpc.pid"); + + // The gate dials 127.0.0.1:; the test holds that port open so the + // gate passes without a real arti binary. The gate itself is covered by + // `socks_listener_ready_*` above. + let (held, socks_port) = held_loopback_port(); + let child = WalletChild::new( ChainSource::Remote { host: "abcdefghijklmnop.onion".into(), - port: 18081, + port: 18089, }, dir.join("wallet"), None, ) - .unwrap(); + .unwrap() + .with_arti_bin(fake_bin_with_pid( + &fake_dir(&dir), + "arti", + &arti_log, + &arti_pid, + )) + .with_wallet_rpc_bin(fake_bin_with_pid( + &dir, + "monero-wallet-rpc", + &rpc_log, + &rpc_pid, + )) + .with_socks_port(socks_port); + + let client = child.start(&store).unwrap().expect("enabled child"); + assert!(child.running(), "both children must be tracked"); + assert!(client.url().contains("127.0.0.1"), "{}", client.url()); + + let arti_argv = wait_for_argv(&arti_log); + // The fake logs only the arguments (`$@`), not argv[0]. + assert_eq!(arti_argv[0], "proxy", "{arti_argv:?}"); + assert!( + pairs(&arti_argv).contains(&("-p".into(), socks_port.to_string())), + "{arti_argv:?}" + ); + + let rpc_argv = wait_for_argv(&rpc_log); + let rpc_pairs = pairs(&rpc_argv); + assert!( + rpc_pairs.contains(&("--proxy".into(), format!("socks5://127.0.0.1:{socks_port}"))), + "{rpc_argv:?}" + ); + assert!( + rpc_pairs.contains(&( + "--daemon-address".into(), + "abcdefghijklmnop.onion:18089".into() + )), + "{rpc_argv:?}" + ); + + let arti_proc = child_pid(&arti_pid); + let rpc_proc = child_pid(&rpc_pid); + drop(held); + + child.stop().unwrap(); + assert!(!child.running()); + wait_for_process_exit(arti_proc); + wait_for_process_exit(rpc_proc); + } + + /// A wallet child that cannot dial its daemon must not be spawned at all: + /// a dead SOCKS proxy is a visible error, not a hung wallet screen. + #[test] + fn onion_remote_start_fails_visibly_when_the_socks_proxy_never_listens() { + let dir = tmp_dir("onion-dead-proxy"); + let store = open_store(&dir); + let arti_pid = dir.join("arti.pid"); + let arti_log = dir.join("arti.argv"); + let rpc_log = dir.join("wallet-rpc.argv"); + let port = freed_loopback_port(); + + let child = WalletChild::new( + ChainSource::Remote { + host: "abcdefghijklmnop.onion".into(), + port: 18089, + }, + dir.join("wallet"), + None, + ) + .unwrap() + .with_arti_bin(fake_bin_with_pid( + &fake_dir(&dir), + "arti", + &arti_log, + &arti_pid, + )) + .with_wallet_rpc_bin(fake_bin(&fake_dir(&dir), "monero-wallet-rpc", &rpc_log)) + .with_socks_port(port) + .with_socks_ready_timeout(Duration::from_millis(300)); + let err = child.start(&store).unwrap_err().to_string(); - assert!(err.contains("SOCKS"), "got {err}"); + assert!(err.contains("SOCKS"), "{err}"); + assert!(err.contains(&port.to_string()), "{err}"); + assert!( + !rpc_log.exists(), + "no wallet child may be spawned against a dead proxy" + ); + assert!(!child.running(), "a failed start leaves nothing running"); + wait_for_process_exit(child_pid(&arti_pid)); + } + + /// A loopback or clearnet daemon the user typed never gets a proxy, and + /// never starts the SOCKS child: `--proxy` is for `.onion` only. + #[test] + fn loopback_and_clearnet_remotes_carry_no_proxy_and_spawn_no_socks_child() { + for host in ["127.0.0.1", "node.example.com"] { + let dir = tmp_dir(&format!("nosocks-{}", host.replace('.', "-"))); + let store = open_store(&dir); + let arti_log = dir.join("arti.argv"); + let rpc_log = dir.join("wallet-rpc.argv"); + let child = WalletChild::new( + ChainSource::Remote { + host: host.into(), + port: 18089, + }, + dir.join("wallet"), + None, + ) + .unwrap() + .with_arti_bin(fake_bin(&fake_dir(&dir), "arti", &arti_log)) + .with_wallet_rpc_bin(fake_bin( + &fake_dir(&dir), + "monero-wallet-rpc", + &rpc_log, + )); + + child.start(&store).unwrap().expect("enabled child"); + let rpc_argv = wait_for_argv(&rpc_log); + assert!( + pairs(&rpc_argv).contains(&("--daemon-address".into(), format!("{host}:18089"))), + "{rpc_argv:?}" + ); + assert!( + !rpc_argv.iter().any(|a| a == "--proxy"), + "no SOCKS for {host}: {rpc_argv:?}" + ); + assert!(!arti_log.exists(), "no SOCKS child for {host}"); + child.stop().unwrap(); + } } #[test] @@ -564,6 +1127,7 @@ mod tests { "owuser:owpass", &dir, Some("127.0.0.1:18081"), + None, ); let pairs: Vec<(&str, &str)> = argv .windows(2)