Merge branch 'main' into onionwire/t_fb6ffa87-strengthen-and-version-the-store-backup
Some checks failed
ci / sdk (pull_request) Has been cancelled
ci / test (pull_request) Has been cancelled

This commit is contained in:
sirius 2026-10-26 16:13:01 +00:00
commit 4cf0a09ceb
13 changed files with 1661 additions and 99 deletions

View file

@ -54,9 +54,10 @@ pub fn verify(identity_pk: &[u8], loc: &Loc) -> bool {
let signature = Signature::from_bytes(&sig);
vk.verify(&sign_msg_v2(&loc.onion, loc.ts), &signature)
.is_ok()
|| vk
.verify(&sign_msg_v1(&loc.onion, loc.ts), &signature)
.is_ok()
|| (crate::pay::legacy_sigs()
&& vk
.verify(&sign_msg_v1(&loc.onion, loc.ts), &signature)
.is_ok())
}
pub fn encode(loc: &Loc) -> Vec<u8> {

View file

@ -1,9 +1,47 @@
use ed25519_dalek::{Signature, Signer, SigningKey, Verifier, VerifyingKey};
use sha3::{Digest, Keccak256};
use std::cell::Cell;
use zeroize::Zeroizing;
pub type Result<T> = std::result::Result<T, Error>;
/// Legacy signature acceptance.
///
/// Every signed frame is **emitted** in its domain-tagged form. Inbound, the
/// historical untagged / LF-joined layout (and the `onionwire:v1` invite
/// string) is still accepted so a mixed-version fleet keeps working; that
/// fallback is gated on this one switch. Set it to `false` to fail closed on
/// legacy signatures for every frame that reads it — `loc`, the invite string,
/// `inv`, `rcp`, and `tip`. (`prf` is not yet gated; see `docs/PROTOCOL.md`.)
pub const LEGACY_SIGS: bool = true;
thread_local! {
/// Per-thread override for tests. `None` follows [`LEGACY_SIGS`].
static LEGACY_SIGS_OVERRIDE: Cell<Option<bool>> = const { Cell::new(None) };
}
/// Whether legacy (pre-domain-tag) signatures are accepted inbound.
pub fn legacy_sigs() -> bool {
LEGACY_SIGS_OVERRIDE
.with(|o| o.get())
.unwrap_or(LEGACY_SIGS)
}
/// Run `f` with legacy acceptance forced to `on`, then restore the previous
/// thread state. A test hook, not a runtime setting: production code reads the
/// switch through [`legacy_sigs`] only.
#[doc(hidden)]
pub fn with_legacy_sigs<R>(on: bool, f: impl FnOnce() -> R) -> R {
struct Restore(Option<bool>);
impl Drop for Restore {
fn drop(&mut self) {
LEGACY_SIGS_OVERRIDE.with(|o| o.set(self.0));
}
}
let _restore = Restore(LEGACY_SIGS_OVERRIDE.with(|o| o.replace(Some(on))));
f()
}
#[derive(Debug)]
pub struct Error(String);
@ -202,11 +240,12 @@ pub fn verify_invoice(identity_pk: &[u8], inv: &Invoice) -> bool {
identity_pk,
&inv_sign_msg_v2(&inv.amount_atomic, &inv.address, &inv.memo, inv.ts),
&inv.sig,
) || verify_bytes(
identity_pk,
&inv_sign_msg_v1(&inv.amount_atomic, &inv.address, &inv.memo, inv.ts),
&inv.sig,
)
) || (legacy_sigs()
&& verify_bytes(
identity_pk,
&inv_sign_msg_v1(&inv.amount_atomic, &inv.address, &inv.memo, inv.ts),
&inv.sig,
))
}
pub fn encode_invoice(inv: &Invoice) -> Vec<u8> {
@ -273,11 +312,12 @@ pub fn verify_receipt(identity_pk: &[u8], rcp: &Receipt) -> bool {
identity_pk,
&rcp_sign_msg_v2(&rcp.txid, &rcp.amount_atomic, &rcp.address, rcp.ts),
&rcp.sig,
) || verify_bytes(
identity_pk,
&rcp_sign_msg_v1(&rcp.txid, &rcp.amount_atomic, &rcp.address, rcp.ts),
&rcp.sig,
)
) || (legacy_sigs()
&& verify_bytes(
identity_pk,
&rcp_sign_msg_v1(&rcp.txid, &rcp.amount_atomic, &rcp.address, rcp.ts),
&rcp.sig,
))
}
pub fn encode_receipt(rcp: &Receipt) -> Vec<u8> {
@ -339,6 +379,20 @@ fn check_tip_fields(txid: &str, amount_atomic: &str, address: &str, memo: &str)
Ok(())
}
fn tip_sign_msg_v2(txid: &str, amount_atomic: &str, address: &str, memo: &str, ts: i64) -> Vec<u8> {
tagged(
b"onionwire-tip-v1",
&[
txid.as_bytes(),
amount_atomic.as_bytes(),
address.as_bytes(),
memo.as_bytes(),
ts.to_string().as_bytes(),
],
)
}
/// Historical untagged form. Accept-only, and only while [`LEGACY_SIGS`] is on.
fn tip_sign_msg_v1(txid: &str, amount_atomic: &str, address: &str, memo: &str, ts: i64) -> Vec<u8> {
let mut msg = Vec::from(txid.as_bytes());
msg.push(b'\n');
@ -361,7 +415,10 @@ pub fn sign_tip(
ts: i64,
) -> Result<Tip> {
check_tip_fields(txid, amount_atomic, address, memo)?;
let sig = sign_bytes(identity_sk, &tip_sign_msg_v1(txid, amount_atomic, address, memo, ts))?;
let sig = sign_bytes(
identity_sk,
&tip_sign_msg_v2(txid, amount_atomic, address, memo, ts),
)?;
Ok(Tip {
txid: txid.to_string(),
amount_atomic: amount_atomic.to_string(),
@ -378,9 +435,26 @@ pub fn verify_tip(identity_pk: &[u8], tip: &Tip) -> bool {
}
verify_bytes(
identity_pk,
&tip_sign_msg_v1(&tip.txid, &tip.amount_atomic, &tip.address, &tip.memo, tip.ts),
&tip_sign_msg_v2(
&tip.txid,
&tip.amount_atomic,
&tip.address,
&tip.memo,
tip.ts,
),
&tip.sig,
)
) || (legacy_sigs()
&& verify_bytes(
identity_pk,
&tip_sign_msg_v1(
&tip.txid,
&tip.amount_atomic,
&tip.address,
&tip.memo,
tip.ts,
),
&tip.sig,
))
}
pub fn encode_tip(tip: &Tip) -> Vec<u8> {

View file

@ -101,6 +101,11 @@ pub fn decode(raw: &str) -> Result<QrPayload> {
if kem_ascii.is_some() {
return Err(Error("unknown field".into()));
}
// A v1 invite only ever carries a legacy signature: with legacy
// acceptance off it fails closed here, before any verify.
if !crate::pay::legacy_sigs() {
return Err(Error("legacy invite signatures disabled".into()));
}
let ok_tagged = vk
.verify(&sign_msg_v1_tagged(&k, &onion, &spk), &signature)
.is_ok();

View file

@ -1,4 +1,5 @@
use std::path::PathBuf;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::Duration;
use rand::RngCore;
@ -363,12 +364,16 @@ 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 = "<redacted>";
/// 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, REDACTED);
}
const MAX: usize = 120;
if out.chars().count() > MAX {
@ -378,6 +383,51 @@ pub(crate) fn redact(msg: &str, secret: &str) -> String {
out
}
/// [`redact`] for a whole `user:pass` login: drop the pair first (so no
/// `user:<redacted>` 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://<redacted>:<redacted>@127.0.0.1:<port>/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,
@ -387,14 +437,25 @@ struct Endpoint {
pass: Zeroizing<String>,
}
impl Endpoint {
/// The URL with both halves of the login replaced, for any log line, error
/// string or status row:
/// `http://<redacted>:<redacted>@127.0.0.1:<port>/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("host", &self.host)
.field("port", &self.port)
.field("path", &self.path)
.field("user", &self.user)
.field("pass", &"<redacted>")
.field("url", &self.redacted())
.finish()
}
}
@ -524,7 +585,13 @@ 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) => Self::new(Some(endpoint), no_spend),
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)
}
Err(e) => {
eprintln!("ONIONWIRE_WALLET_RPC: {e}");
Self::new(None, no_spend)
@ -546,7 +613,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(&e.to_string(), cfg.secret())))?;
.map_err(|e| Error(redact_login(&e.to_string(), cfg.rpc_login.as_str())))?;
Ok(Self::new(Some(ep), cfg.no_spend))
}
@ -632,7 +699,7 @@ impl Wallet {
return PingResult {
ok: false,
status: "not connected".into(),
error: Some(redact(&e.to_string(), cfg.secret())),
error: Some(redact_login(&e.to_string(), cfg.rpc_login.as_str())),
};
}
};
@ -654,12 +721,13 @@ impl Wallet {
/// Display-safe copy of an error: no RPC password, short enough for a line.
fn sanitize(&self, msg: &str) -> String {
let pass = self
.endpoint
.as_ref()
.map(|e| e.pass.as_str())
.unwrap_or("");
redact(msg, pass)
// Both halves of `user:pass`, not just the password: an error that
// names the URL's userinfo must not survive as `user:<redacted>`.
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())
}
/// Set both RPC budgets. The timeout is a property of the backend, not a
@ -1798,3 +1866,70 @@ fn hex_val(c: u8) -> Option<u8> {
_ => 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:[email protected]: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:[email protected]:18083/json_rpc"),
"http://<redacted>:<redacted>@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:[email protected]: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");
}
}

View file

@ -22,6 +22,13 @@
//! * 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/<pid>/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://<redacted>:<redacted>@127.0.0.1:<port>`.
//! * 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.
@ -1060,12 +1067,23 @@ 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(Debug, Clone)]
#[derive(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
@ -1076,11 +1094,18 @@ impl WalletClient {
.with_no_spend(self.no_spend)
}
/// The loopback URL. Carries the generated creds — do not log it.
/// The loopback URL. Carries the generated creds — do not log it; use
/// [`WalletClient::redacted_url`] for anything a human or a log can see.
pub fn url(&self) -> &str {
&self.url
}
/// The same endpoint with both halves of the login replaced:
/// `http://<redacted>:<redacted>@127.0.0.1:<port>/json_rpc`.
pub fn redacted_url(&self) -> String {
wallet::redact_url(&self.url)
}
pub fn no_spend(&self) -> bool {
self.no_spend
}
@ -2055,6 +2080,26 @@ 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:[email protected]: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://<redacted>:<redacted>@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();