diff --git a/src/wallet.rs b/src/wallet.rs index c5cf04f..a31990a 100644 --- a/src/wallet.rs +++ b/src/wallet.rs @@ -1,5 +1,4 @@ use std::path::PathBuf; -use std::sync::atomic::{AtomicBool, Ordering}; use std::time::Duration; use rand::RngCore; @@ -364,16 +363,12 @@ pub fn readiness(configured: bool, connected: bool, no_spend: bool, is_tip: bool Readiness::Ready } -/// What a redacted credential renders as. One spelling everywhere: the -/// existing `Debug` pins and the URL accessor must agree. -pub(crate) const REDACTED: &str = ""; - /// Display copy, not a log line: drop the secret if some lower layer put it in /// the message, and keep it short enough for a status line. pub(crate) fn redact(msg: &str, secret: &str) -> String { let mut out = msg.trim().to_string(); if !secret.is_empty() { - out = out.replace(secret, REDACTED); + out = out.replace(secret, ""); } const MAX: usize = 120; if out.chars().count() > MAX { @@ -383,51 +378,6 @@ pub(crate) fn redact(msg: &str, secret: &str) -> String { out } -/// [`redact`] for a whole `user:pass` login: drop the pair first (so no -/// `user:` survives), then the password half on its own, in case a -/// lower layer printed only that. Every error/status string built from a -/// [`WalletConfig`] goes through here. -pub(crate) fn redact_login(msg: &str, login: &str) -> String { - let login = login.trim(); - if login.is_empty() { - return redact(msg, ""); - } - let pass = login.split_once(':').map(|(_, p)| p).unwrap_or(login); - redact(&redact(msg, login), pass) -} - -/// The URL with its userinfo replaced, for anything that prints a wallet -/// endpoint: `http://:@127.0.0.1:/json_rpc`. A URL -/// with no userinfo is returned unchanged. -pub(crate) fn redact_url(url: &str) -> String { - match (url.find("://"), url.find('@')) { - (Some(scheme), Some(at)) if at > scheme + 3 => { - format!( - "{}://{REDACTED}:{REDACTED}@{}", - &url[..scheme], - &url[at + 1..] - ) - } - _ => url.to_string(), - } -} - -/// The one-shot notice for a login taken from the environment. Environment is -/// readable through `/proc`, inherited by children, and lands in shell history, -/// so the store is the preferred channel (`Wallet::for_boot` already tries it -/// first). `true` only on the call that actually printed. -static ENV_LOGIN_WARNED: AtomicBool = AtomicBool::new(false); - -fn warn_env_login_once() -> bool { - if ENV_LOGIN_WARNED.swap(true, Ordering::SeqCst) { - return false; - } - eprintln!( - "ONIONWIRE_WALLET_RPC_LOGIN: environment is readable by other processes and lands in shell history; put it in the wallet setup screen instead" - ); - true -} - #[derive(Clone)] struct Endpoint { host: String, @@ -437,25 +387,14 @@ struct Endpoint { pass: Zeroizing, } -impl Endpoint { - /// The URL with both halves of the login replaced, for any log line, error - /// string or status row: - /// `http://:@127.0.0.1:/json_rpc`. - pub(crate) fn redacted(&self) -> String { - format!( - "http://{REDACTED}:{REDACTED}@{}{}", - host_header(&self.host, self.port), - self.path - ) - } -} - -/// `Debug` goes through [`Endpoint::redacted`]: a `{:?}` must never be the one -/// place the login survives. impl std::fmt::Debug for Endpoint { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("Endpoint") - .field("url", &self.redacted()) + .field("host", &self.host) + .field("port", &self.port) + .field("path", &self.path) + .field("user", &self.user) + .field("pass", &"") .finish() } } @@ -585,13 +524,7 @@ impl Wallet { .map(|v| Zeroizing::new(v.trim().to_string())) .filter(|v| !v.is_empty()); match parse_http_url(url.trim(), login.as_ref().map(|v| v.as_str())) { - Ok(endpoint) => { - // Store wins (see `for_boot`); this path only runs when - // no usable stored config exists, so the login really is - // coming from the environment. - warn_env_login_once(); - Self::new(Some(endpoint), no_spend) - } + Ok(endpoint) => Self::new(Some(endpoint), no_spend), Err(e) => { eprintln!("ONIONWIRE_WALLET_RPC: {e}"); Self::new(None, no_spend) @@ -613,7 +546,7 @@ impl Wallet { return Err(Error("wallet RPC endpoint required".into())); } let ep = parse_http_url(cfg.rpc_url.trim(), Some(cfg.rpc_login.as_str())) - .map_err(|e| Error(redact_login(&e.to_string(), cfg.rpc_login.as_str())))?; + .map_err(|e| Error(redact(&e.to_string(), cfg.secret())))?; Ok(Self::new(Some(ep), cfg.no_spend)) } @@ -699,7 +632,7 @@ impl Wallet { return PingResult { ok: false, status: "not connected".into(), - error: Some(redact_login(&e.to_string(), cfg.rpc_login.as_str())), + error: Some(redact(&e.to_string(), cfg.secret())), }; } }; @@ -721,13 +654,12 @@ impl Wallet { /// Display-safe copy of an error: no RPC password, short enough for a line. fn sanitize(&self, msg: &str) -> String { - // Both halves of `user:pass`, not just the password: an error that - // names the URL's userinfo must not survive as `user:`. - let login = match self.endpoint.as_ref() { - Some(ep) => Zeroizing::new(format!("{}:{}", ep.user, ep.pass.as_str())), - None => Zeroizing::new(String::new()), - }; - redact_login(msg, login.as_str()) + let pass = self + .endpoint + .as_ref() + .map(|e| e.pass.as_str()) + .unwrap_or(""); + redact(msg, pass) } /// Set both RPC budgets. The timeout is a property of the backend, not a @@ -1866,70 +1798,3 @@ fn hex_val(c: u8) -> Option { _ => None, } } - -#[cfg(test)] -mod tests { - use super::*; - use std::sync::Mutex; - - /// The env is process-wide; these are the only lib tests that touch it. - static ENV_LOCK: Mutex<()> = Mutex::new(()); - - #[test] - fn redacting_an_error_drops_the_whole_login_not_just_the_password() { - let msg = "dial http://ow:hunter2@127.0.0.1:18083 failed for ow:hunter2"; - let out = redact_login(msg, "ow:hunter2"); - assert!(!out.contains("hunter2"), "{out}"); - assert!(!out.contains("ow:hunter2"), "{out}"); - assert!(out.contains("127.0.0.1:18083"), "{out}"); - } - - #[test] - fn redacted_url_keeps_the_endpoint_and_drops_the_userinfo() { - assert_eq!( - redact_url("http://ow:hunter2@127.0.0.1:18083/json_rpc"), - "http://:@127.0.0.1:18083/json_rpc" - ); - assert_eq!( - redact_url("http://127.0.0.1:18083/json_rpc"), - "http://127.0.0.1:18083/json_rpc" - ); - } - - #[test] - fn wallet_debug_prints_no_login() { - let w = Wallet::from_url("http://ow:hunter2@127.0.0.1:18083").unwrap(); - let dbg = format!("{w:?}"); - assert!(!dbg.contains("hunter2"), "{dbg}"); - assert!(!dbg.contains("ow:hunter2"), "{dbg}"); - assert!(dbg.contains("127.0.0.1"), "{dbg}"); - } - - #[test] - fn env_login_warns_once_per_process_and_not_for_a_stored_config() { - let _guard = ENV_LOCK.lock().unwrap(); - ENV_LOGIN_WARNED.store(false, Ordering::SeqCst); - // The one-shot gate itself: the first call prints, later ones do not. - assert!(warn_env_login_once(), "first env login must warn"); - assert!(!warn_env_login_once(), "warning is once per process"); - ENV_LOGIN_WARNED.store(false, Ordering::SeqCst); - - unsafe { - std::env::set_var("ONIONWIRE_WALLET_RPC", "http://127.0.0.1:18083"); - std::env::set_var("ONIONWIRE_WALLET_RPC_LOGIN", "ow:hunter2"); - } - let _ = Wallet::from_env(); - let warned_from_env = ENV_LOGIN_WARNED.load(Ordering::SeqCst); - unsafe { std::env::remove_var("ONIONWIRE_WALLET_RPC_LOGIN") }; - assert!(warned_from_env, "an env login must warn"); - - // The store is the preferred channel; `for_boot` takes it and never - // reaches the env path, so no warning. - ENV_LOGIN_WARNED.store(false, Ordering::SeqCst); - let cfg = WalletConfig::new("http://127.0.0.1:18083", "ow:hunter2", false); - let _ = Wallet::for_boot(Some(&cfg)); - let warned_from_store = ENV_LOGIN_WARNED.load(Ordering::SeqCst); - unsafe { std::env::remove_var("ONIONWIRE_WALLET_RPC") }; - assert!(!warned_from_store, "a stored login must not warn"); - } -} diff --git a/src/wallet_child.rs b/src/wallet_child.rs index 2e797ac..6fa7e5b 100644 --- a/src/wallet_child.rs +++ b/src/wallet_child.rs @@ -22,13 +22,6 @@ //! * 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. -//! * Residual, and not fixable while the child is a spawned `monero-wallet-rpc`: -//! `--rpc-login` is visible in `/proc//cmdline` to same-uid processes -//! because `monero-wallet-rpc` offers no other credential channel. The -//! mitigation is a loopback-only bind, a strong generated login, and never -//! handing the child a remote daemon. The login is also never rendered: the -//! client's `url()` carries it for `Wallet::from_url`, while `Debug` and -//! [`WalletClient::redacted_url`] show `http://:@127.0.0.1:`. //! * The in-process daemon is *not* a child: it is a value owned by this struct, //! and dropping it shuts the node down. It still binds the same loopback RPC //! port, so everything downstream of `--daemon-address` is unchanged. @@ -1067,23 +1060,12 @@ impl WalletChildStatus { /// The loopback client built from the generated URL — the production path when /// the app owns the child. Never `ONIONWIRE_WALLET_RPC`, never anything but /// numeric loopback. -#[derive(Clone)] +#[derive(Debug, Clone)] pub struct WalletClient { url: String, no_spend: bool, } -/// Hand-written: `url` carries the generated login, so a derived `Debug` would -/// turn any `{:?}` — a log line, a panic message, an assert — into a leak. -impl std::fmt::Debug for WalletClient { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.debug_struct("WalletClient") - .field("url", &self.redacted_url()) - .field("no_spend", &self.no_spend) - .finish() - } -} - impl WalletClient { /// Build the [`Wallet`] this child serves. The chain-side RPC budget is the /// wallet backend's default (see `CHAIN_RPC_TIMEOUT`), because a first sync @@ -1094,18 +1076,11 @@ impl WalletClient { .with_no_spend(self.no_spend) } - /// The loopback URL. Carries the generated creds — do not log it; use - /// [`WalletClient::redacted_url`] for anything a human or a log can see. + /// The loopback URL. Carries the generated creds — do not log it. pub fn url(&self) -> &str { &self.url } - /// The same endpoint with both halves of the login replaced: - /// `http://:@127.0.0.1:/json_rpc`. - pub fn redacted_url(&self) -> String { - wallet::redact_url(&self.url) - } - pub fn no_spend(&self) -> bool { self.no_spend } @@ -2080,26 +2055,6 @@ mod tests { rest.split('@').next().expect("userinfo").to_string() } - /// The client dials with creds in the URL, but nothing that renders it may - /// repeat them: `Debug` and `redacted_url` are the display surfaces. - #[test] - fn wallet_client_debug_and_redacted_url_hide_the_login() { - let client = WalletClient { - url: "http://alice:s3cret@127.0.0.1:18083/json_rpc".into(), - no_spend: false, - }; - let dbg = format!("{client:?}"); - assert!(!dbg.contains("s3cret"), "{dbg}"); - assert!(!dbg.contains("alice:s3cret"), "{dbg}"); - assert!(dbg.contains("127.0.0.1"), "{dbg}"); - assert_eq!( - client.redacted_url(), - "http://:@127.0.0.1:18083/json_rpc" - ); - // The dial still needs the real userinfo — redaction is for display. - assert!(client.url().contains("alice:s3cret")); - } - #[test] fn pick_port_is_free_loopback_and_bindable() { let port = WalletChild::pick_port().unwrap(); diff --git a/tests/wallet.rs b/tests/wallet.rs index 92723b0..1337439 100644 --- a/tests/wallet.rs +++ b/tests/wallet.rs @@ -101,33 +101,6 @@ fn password_absent_from_url_errors() { ); } -/// A 401 on the authenticated retry means the login is wrong. That copy is -/// rendered in the TUI/Android status line, so it must not echo either half of -/// the credential — not the password, not `user:pass`, not a URL with userinfo. -#[tokio::test] -async fn ping_401_error_carries_no_credential() { - let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); - let addr = listener.local_addr().unwrap(); - // Answer the authenticated retry with another 401: the digest was built - // from this connection's own challenge, so this is a wrong login. - let reply: Arc String + Send + Sync> = - Arc::new(|_| digest_401("refused-again")); - tokio::spawn(serve_rpc_conns_with(listener, reply, None, None, true)); - - let pass = "s3cretPASS"; - let login = format!("ow:{pass}"); - let res = Wallet::ping(&format!("http://127.0.0.1:{}", addr.port()), login.as_str()).await; - assert!(!res.ok, "a refused digest must not report connected"); - let err = res.error.expect("failure carries a reason"); - println!("401 ping error: {err}"); - assert!(!err.contains(pass), "password leaked in error: {err}"); - assert!(!err.contains(&login), "login leaked in error: {err}"); - assert!( - !err.contains(&format!("://{login}@")), - "URL userinfo leaked in error: {err}" - ); -} - #[tokio::test] async fn mock_get_address_parses_string() { let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();