wallet: no-spend mode + view-only detection over RPC
All checks were successful
ci / test (pull_request) Successful in 3m10s
All checks were successful
ci / test (pull_request) Successful in 3m10s
/tip needs monero-wallet-rpc `transfer`, which a view-only wallet cannot do. With ONIONWIRE_WALLET_NO_SPEND=1 (`1`/`true`/`yes`/`on`) `Wallet::transfer` refuses locally, before any RPC dial, and /pay + receipt verification are unchanged. When a transfer does fail, ask the documented signal before surfacing the raw wallet error: `query_key` key_type=spend_key answers WALLET_RPC_ERROR_CODE_WATCH_ONLY (-29) on a view-only wallet (wallet_rpc_server.cpp on_query_key). Both paths return one sentence — "wallet is in view-only/no-spend mode — /tip is disabled; /pay and receipt verification still work". Fail closed: if the probe cannot answer, the wallet's own error stands; no fabricated detection. New docs/WALLET.md: --generate-from-view-key / generate_from_keys watch-only setup, --rpc-login Digest, why loopback still needs auth, the local spend-authority warning, and the detection trade-off (a spend-capable wallet answers the probe with its spend key, which is discarded). Linked from docs/THREAT_MODEL.md.
This commit is contained in:
parent
e6e2a158a8
commit
01b63c4968
4 changed files with 514 additions and 5 deletions
233
tests/wallet.rs
233
tests/wallet.rs
|
|
@ -1,5 +1,7 @@
|
|||
//! M8: optional monero-wallet-rpc JSON client. Mock TCP only — no live monerod.
|
||||
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use ed25519_dalek::SigningKey;
|
||||
use onionwire::pay;
|
||||
use onionwire::wallet::{self, TransferRow, Wallet};
|
||||
|
|
@ -8,6 +10,10 @@ use rand::rngs::OsRng;
|
|||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
use tokio::net::TcpListener;
|
||||
|
||||
/// `ONIONWIRE_WALLET_NO_SPEND` is process-wide; tests that touch env serialize.
|
||||
static ENV_LOCK: Mutex<()> = Mutex::new(());
|
||||
|
||||
|
||||
fn row(txid: &str, amount: &str, address: &str) -> TransferRow {
|
||||
TransferRow {
|
||||
txid: txid.into(),
|
||||
|
|
@ -241,6 +247,233 @@ async fn oversized_rpc_response_is_err() {
|
|||
);
|
||||
}
|
||||
|
||||
/// Records every request the client sends, answers the Digest challenge and
|
||||
/// then replies per RPC method. Lets a test assert on the *request log*.
|
||||
async fn serve_recording(
|
||||
listener: TcpListener,
|
||||
log: Arc<Mutex<Vec<String>>>,
|
||||
reply: Arc<dyn Fn(&str) -> String + Send + Sync>,
|
||||
) {
|
||||
loop {
|
||||
let Ok((mut sock, _)) = listener.accept().await else {
|
||||
return;
|
||||
};
|
||||
let mut buf = vec![0u8; 8192];
|
||||
let n = sock.read(&mut buf).await.unwrap_or(0);
|
||||
let req = String::from_utf8_lossy(&buf[..n]).to_string();
|
||||
log.lock().expect("log").push(req.clone());
|
||||
if req.contains("Authorization:") {
|
||||
let body = reply(&rpc_method(&req));
|
||||
let _ = sock.write_all(http_200_body(&body).as_bytes()).await;
|
||||
} else {
|
||||
let _ = sock.write_all(digest_401().as_bytes()).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn rpc_method(req: &str) -> String {
|
||||
let body = req.split_once("\r\n\r\n").map(|(_, b)| b).unwrap_or(req);
|
||||
serde_json::from_str::<serde_json::Value>(body.trim())
|
||||
.ok()
|
||||
.and_then(|v| v.get("method").and_then(|m| m.as_str()).map(str::to_string))
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
fn http_200_body(body: &str) -> String {
|
||||
format!(
|
||||
"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
|
||||
body.len()
|
||||
)
|
||||
}
|
||||
|
||||
fn rpc_error(code: i64, message: &str) -> String {
|
||||
format!(r#"{{"jsonrpc":"2.0","id":"0","error":{{"code":{code},"message":"{message}"}}}}"#)
|
||||
}
|
||||
|
||||
/// JSON-RPC body only (the server wraps it in an HTTP 200).
|
||||
fn rpc_result(result: &str) -> String {
|
||||
format!(r#"{{"jsonrpc":"2.0","id":"0","result":{result}}}"#)
|
||||
}
|
||||
|
||||
fn recording_wallet(port: u16) -> Wallet {
|
||||
Wallet::from_url(&format!("http://ow:[email protected]:{port}")).expect("url")
|
||||
}
|
||||
|
||||
/// The wallet mock speaks the two methods `/tip` can reach, and refuses the
|
||||
/// local `transfer` before any socket is opened.
|
||||
#[tokio::test]
|
||||
async fn no_spend_mode_refuses_transfer_with_no_rpc_request() {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let port = listener.local_addr().unwrap().port();
|
||||
let log = Arc::new(Mutex::new(Vec::new()));
|
||||
tokio::spawn(serve_recording(
|
||||
listener,
|
||||
Arc::clone(&log),
|
||||
Arc::new(|_| rpc_result(r#"{"tx_hash":"abc123"}"#)),
|
||||
));
|
||||
let w = recording_wallet(port).with_no_spend(true);
|
||||
assert!(w.no_spend());
|
||||
let err = w
|
||||
.transfer(
|
||||
"8BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB",
|
||||
1,
|
||||
)
|
||||
.await
|
||||
.unwrap_err()
|
||||
.to_string();
|
||||
assert!(
|
||||
err.to_ascii_lowercase().contains("view-only"),
|
||||
"got {err}"
|
||||
);
|
||||
tokio::time::sleep(std::time::Duration::from_millis(200)).await;
|
||||
let seen = log.lock().expect("log").clone();
|
||||
assert!(seen.is_empty(), "no RPC request may be made: {seen:?}");
|
||||
// Positive control: the recorder is live, so the emptiness above is real.
|
||||
let _ = w.get_address().await;
|
||||
assert!(!log.lock().expect("log").is_empty(), "recorder saw nothing");
|
||||
}
|
||||
|
||||
/// `/pay` (subaddress) and receipt verification (`get_transfers`) keep working
|
||||
/// with the no-spend flag on — only `transfer` is refused.
|
||||
#[tokio::test]
|
||||
async fn no_spend_mode_keeps_invoice_and_receipt_paths_working() {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let port = listener.local_addr().unwrap().port();
|
||||
let log = Arc::new(Mutex::new(Vec::new()));
|
||||
tokio::spawn(serve_recording(
|
||||
listener,
|
||||
Arc::clone(&log),
|
||||
Arc::new(|method| match method {
|
||||
"create_address" => rpc_result(
|
||||
r#"{"address":"8BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB"}"#,
|
||||
),
|
||||
"get_transfers" => rpc_result(
|
||||
r#"{"in":[{"txid":"deadbeef","amount":5,"address":"8BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB"}],"pending":[]}"#,
|
||||
),
|
||||
_ => rpc_result(r#"{}"#),
|
||||
}),
|
||||
));
|
||||
let w = recording_wallet(port).with_no_spend(true);
|
||||
let created = w.create_address().await.expect("create_address");
|
||||
assert!(created.starts_with('8'), "got {created}");
|
||||
let rows = w.get_transfers().await.expect("get_transfers");
|
||||
assert!(wallet::transfers_match(&rows, "deadbeef", "5", &created));
|
||||
let seen = log.lock().expect("log").clone();
|
||||
assert!(
|
||||
seen.iter()
|
||||
.any(|r| r.contains("\"method\":\"create_address\"")),
|
||||
"recorder must have seen the invoice path: {seen:?}"
|
||||
);
|
||||
assert!(
|
||||
!seen.iter().any(|r| r.contains("\"method\":\"transfer\"")),
|
||||
"transfer must never be dialed in no-spend mode"
|
||||
);
|
||||
}
|
||||
|
||||
/// A view-only wallet refuses `transfer` with its own opaque error. The
|
||||
/// pre-transfer signal is `query_key` key_type=spend_key (Monero answers
|
||||
/// WALLET_RPC_ERROR_CODE_WATCH_ONLY = -29), so /tip must say so plainly.
|
||||
#[tokio::test]
|
||||
async fn view_only_wallet_maps_transfer_failure_to_clear_message() {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let port = listener.local_addr().unwrap().port();
|
||||
let log = Arc::new(Mutex::new(Vec::new()));
|
||||
tokio::spawn(serve_recording(
|
||||
listener,
|
||||
Arc::clone(&log),
|
||||
Arc::new(|method| match method {
|
||||
"query_key" => rpc_error(-29, "The wallet is watch-only. Cannot retrieve spend key."),
|
||||
_ => rpc_error(-18, "No transaction created"),
|
||||
}),
|
||||
));
|
||||
let w = recording_wallet(port);
|
||||
assert!(!w.no_spend());
|
||||
let err = w
|
||||
.transfer(
|
||||
"8BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB",
|
||||
1,
|
||||
)
|
||||
.await
|
||||
.unwrap_err()
|
||||
.to_string();
|
||||
assert!(err.to_ascii_lowercase().contains("view-only"), "got {err}");
|
||||
let seen = log.lock().expect("log").clone();
|
||||
assert!(
|
||||
seen.iter().any(|r| r.contains("\"method\":\"query_key\"")),
|
||||
"must ask the RPC-side signal: {seen:?}"
|
||||
);
|
||||
}
|
||||
|
||||
/// A spend-capable wallet must keep its real error: no fabricated detection.
|
||||
#[tokio::test]
|
||||
async fn spend_capable_wallet_keeps_the_original_transfer_error() {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let port = listener.local_addr().unwrap().port();
|
||||
tokio::spawn(serve_recording(
|
||||
listener,
|
||||
Arc::new(Mutex::new(Vec::new())),
|
||||
Arc::new(|method| match method {
|
||||
"query_key" => rpc_result(r#"{"key":"00112233"}"#),
|
||||
_ => rpc_error(-18, "No transaction created"),
|
||||
}),
|
||||
));
|
||||
let err = recording_wallet(port)
|
||||
.transfer(
|
||||
"8BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB",
|
||||
1,
|
||||
)
|
||||
.await
|
||||
.unwrap_err()
|
||||
.to_string();
|
||||
assert!(err.contains("No transaction created"), "got {err}");
|
||||
assert!(!err.to_ascii_lowercase().contains("view-only"), "got {err}");
|
||||
}
|
||||
|
||||
/// F5 must not regress: an open RPC (HTTP 200, no Digest challenge) is refused.
|
||||
#[tokio::test]
|
||||
async fn open_rpc_without_digest_challenge_is_still_refused() {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let port = listener.local_addr().unwrap().port();
|
||||
let canned = http_200_body(
|
||||
r#"{"jsonrpc":"2.0","id":"0","result":{"address":"4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"}}"#,
|
||||
);
|
||||
tokio::spawn(async move {
|
||||
let (mut sock, _) = listener.accept().await.expect("accept");
|
||||
let mut buf = vec![0u8; 4096];
|
||||
let _ = sock.read(&mut buf).await;
|
||||
let _ = sock.write_all(canned.as_bytes()).await;
|
||||
});
|
||||
let err = recording_wallet(port)
|
||||
.get_address()
|
||||
.await
|
||||
.unwrap_err()
|
||||
.to_string();
|
||||
assert!(err.to_ascii_lowercase().contains("digest"), "got {err}");
|
||||
}
|
||||
|
||||
/// `ONIONWIRE_WALLET_NO_SPEND` is the operator-facing switch.
|
||||
#[test]
|
||||
fn from_env_reads_no_spend_flag() {
|
||||
let _guard = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
|
||||
unsafe {
|
||||
std::env::set_var("ONIONWIRE_WALLET_RPC", "http://ow:[email protected]:18083");
|
||||
std::env::set_var("ONIONWIRE_WALLET_NO_SPEND", "1");
|
||||
}
|
||||
let on = Wallet::from_env();
|
||||
assert!(on.no_spend(), "flag 1 must mean no-spend");
|
||||
unsafe { std::env::set_var("ONIONWIRE_WALLET_NO_SPEND", "true") };
|
||||
assert!(Wallet::from_env().no_spend(), "\"true\" must mean no-spend");
|
||||
for off in ["0", "no", "off"] {
|
||||
unsafe { std::env::set_var("ONIONWIRE_WALLET_NO_SPEND", off) };
|
||||
assert!(!Wallet::from_env().no_spend(), "{off} must be off");
|
||||
}
|
||||
unsafe {
|
||||
std::env::remove_var("ONIONWIRE_WALLET_NO_SPEND");
|
||||
std::env::remove_var("ONIONWIRE_WALLET_RPC");
|
||||
}
|
||||
assert!(!Wallet::from_env().no_spend(), "unset must be off");
|
||||
}
|
||||
|
||||
fn digest_401() -> String {
|
||||
"HTTP/1.1 401 Unauthorized\r\nWWW-Authenticate: Digest realm=\"monero-rpc\", nonce=\"abcnonce\", qop=\"auth\", algorithm=MD5\r\nContent-Length: 0\r\nConnection: close\r\n\r\n".into()
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in a new issue