wallet: answer the Digest challenge on the connection that issued it
All checks were successful
ci / test (pull_request) Successful in 5m37s
ci / sdk (pull_request) Successful in 1m21s
ci / fuzz (pull_request) Successful in 4m52s
android-ci / android (pull_request) Successful in 12m15s

monero-wallet-rpc (epee) keeps its Digest nonce per TCP connection: the
`http_server_auth` lives inside `http_custom_handler`, which is created per
connection, so its nonce starts empty and any request without a valid
`Authorization` field mints a fresh one. The client opened a *second* connection
for the authenticated retry, presenting a nonce that socket never issued — so a
real wallet RPC answered 401 forever, however correct the login was. That is the
`wallet RPC HTTP HTTP/1.1 401 Unauthorized` the TUI and Android showed; the
canned mocks replayed the challenge on any socket, so they stayed green.

- `post_digest`/`http_digest`: one `TcpStream` for the challenge and the retry,
  no `Connection: close` on the challenge (epee closes the socket with the 401
  when the request asks for it), `read_one_response` honouring `Content-Length`
  (a keep-alive response never ends in EOF; with no length the body ends at EOF,
  which is what keeps the 1 MiB cap meaningful for an open RPC).
- A 401 after our *own* challenge now reads: the login does not match the
  child's `--rpc-login`.
- Mocks in `tests/wallet.rs` and `src/node.rs` model the per-connection nonce:
  `serve_one_conn`/`serve_rpc_conns`. Two tests pin it — one RPC call uses one
  connection, and a nonce presented on another connection is refused.
- `docs/WALLET.md`: what a 401 means and why it is not the flow.

Verified end-to-end against `monero-wallet-rpc` v0.18.5.1 (`--rpc-login`,
`--offline`, real wallet open): unfixed tree → `wallet RPC HTTP HTTP/1.1 401
Unauthorized`; fixed tree → `connected: true` with the wallet's real address.
This commit is contained in:
sirius 2026-09-20 09:17:05 -04:00
commit cb411da813
No known key found for this signature in database
4 changed files with 435 additions and 161 deletions

View file

@ -2205,59 +2205,80 @@ mod tests {
.to_string()
}
/// A wallet child that clears the Digest challenge and answers one
/// `transfer` — the two-connection dance `tests/wallet.rs` mocks.
/// Serve a mock wallet RPC whose Digest state is **per connection**, the way
/// epee does it: the nonce is minted by the socket that answered 401 and is
/// valid nowhere else, so a client that retries on a fresh socket is refused
/// forever. `reply` maps a request to its JSON-RPC body. The socket closes
/// after an authenticated reply — the client asks for `Connection: close`
/// there and the real server honours it.
async fn serve_mock_rpc(
listener: tokio::net::TcpListener,
reply: Arc<dyn Fn(&str) -> String + Send + Sync>,
) {
use std::sync::atomic::{AtomicUsize, Ordering};
use tokio::io::{AsyncReadExt, AsyncWriteExt};
static NEXT_NONCE: AtomicUsize = AtomicUsize::new(1);
while let Ok((mut sock, _)) = listener.accept().await {
let reply = Arc::clone(&reply);
tokio::spawn(async move {
let mut nonce: Option<String> = None;
loop {
let mut buf = vec![0u8; 8192];
let Ok(n) = sock.read(&mut buf).await else {
return;
};
if n == 0 {
return;
}
let req = String::from_utf8_lossy(&buf[..n]).to_string();
let answered = req.contains("Authorization:")
&& nonce.as_deref().is_some_and(|held| req.contains(held));
if !answered {
let fresh = format!("nonce{}", NEXT_NONCE.fetch_add(1, Ordering::Relaxed));
let challenge = format!(
"HTTP/1.1 401 Unauthorized\r\nWWW-Authenticate: Digest realm=\"monero-rpc\", nonce=\"{fresh}\", qop=\"auth\", algorithm=MD5\r\nContent-Length: 0\r\n\r\n"
);
if sock.write_all(challenge.as_bytes()).await.is_err() {
return;
}
nonce = Some(fresh);
continue;
}
let body = reply(&req);
let ok = format!(
"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\n\r\n{body}",
body.len()
);
let _ = sock.write_all(ok.as_bytes()).await;
return;
}
});
}
}
/// A loopback wallet RPC that answers what the tip path actually asks for:
/// a digest challenge, then a synced `get_info` for the readiness gate and
/// `tx_hash` for the transfer. The old single-answer mock stopped covering
/// the path when `Wallet::transfer` started probing the chain tip first —
/// it answered `tx_hash` to `get_info` and every tip was refused as unsynced.
async fn mock_wallet() -> Wallet {
use tokio::io::{AsyncReadExt, AsyncWriteExt};
let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
.await
.expect("bind mock wallet");
let port = listener.local_addr().expect("mock wallet addr").port();
tokio::spawn(async move {
// Every call starts unauthenticated, so every call gets one
// challenge — the client retries each request with digest auth.
for _ in 0..8 {
let Ok((mut sock, _)) = listener.accept().await else {
return;
};
let mut buf = vec![0u8; 8192];
let Ok(n) = sock.read(&mut buf).await else {
return;
};
let req = String::from_utf8_lossy(&buf[..n]).to_string();
if !req.contains("Authorization:") {
let _ = sock
.write_all(
b"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",
)
.await;
continue;
}
let body = if req.contains("get_info") {
r#"{"jsonrpc":"2.0","id":"0","result":{"height":100,"target_height":100,"synchronized":true}}"#
} else {
r#"{"jsonrpc":"2.0","id":"0","result":{"tx_hash":"abc123"}}"#
};
let _ = sock
.write_all(
format!(
"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
body.len()
)
.as_bytes(),
)
.await;
let reply: Arc<dyn Fn(&str) -> String + Send + Sync> = Arc::new(|req: &str| {
if req.contains("get_info") {
r#"{"jsonrpc":"2.0","id":"0","result":{"height":100,"target_height":100,"synchronized":true}}"#
.to_string()
} else {
r#"{"jsonrpc":"2.0","id":"0","result":{"tx_hash":"abc123"}}"#.to_string()
}
});
tokio::spawn(serve_mock_rpc(listener, reply));
Wallet::from_url(&format!("http://ow:[email protected]:{port}")).expect("wallet url")
}
/// The payer of a tip must see it in their own chat: `receipt_chat_line` is
/// the recipient's view of the frame that arrived, `tip_chat_line` is what
/// the sender just spent.
@ -2522,60 +2543,34 @@ mod tests {
}
}
/// A loopback wallet RPC that answers the *status* probe: a digest
/// challenge, then `get_address` / `get_balance` / `get_info`, with the
/// chain numbers a syncing daemon reports. [`mock_wallet`] above answers the
/// *transfer* path; this one answers a refresh, which never transfers.
/// A loopback wallet RPC that answers the *status* probe: a digest
/// challenge, then `get_address` / `get_balance` / `get_info`, with the
/// chain numbers a syncing daemon reports. [`mock_wallet`] above answers the
/// *transfer* path; this one answers a refresh, which never transfers.
async fn mock_syncing_wallet(height: u64, target: u64) -> Wallet {
use tokio::io::{AsyncReadExt, AsyncWriteExt};
let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
.await
.expect("bind mock wallet");
let port = listener.local_addr().expect("mock wallet addr").port();
tokio::spawn(async move {
// Every call starts unauthenticated, so every call gets one
// challenge — the client retries each request with digest auth.
for _ in 0..8 {
let Ok((mut sock, _)) = listener.accept().await else {
return;
};
let mut buf = vec![0u8; 8192];
let Ok(n) = sock.read(&mut buf).await else {
return;
};
let req = String::from_utf8_lossy(&buf[..n]).to_string();
if !req.contains("Authorization:") {
let _ = sock
.write_all(
b"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",
)
.await;
continue;
}
let body = if req.contains("get_info") {
format!(
r#"{{"jsonrpc":"2.0","id":"0","result":{{"height":{height},"target_height":{target},"synchronized":true}}}}"#
)
} else if req.contains("get_address") {
format!(
r#"{{"jsonrpc":"2.0","id":"0","result":{{"address":"{addr}"}}}}"#,
addr = xmr_addr()
)
} else {
r#"{"jsonrpc":"2.0","id":"0","result":{"balance":"0"}}"#.to_string()
};
let _ = sock
.write_all(
format!(
"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
body.len()
)
.as_bytes(),
)
.await;
let reply: Arc<dyn Fn(&str) -> String + Send + Sync> = Arc::new(move |req: &str| {
if req.contains("get_info") {
format!(
r#"{{"jsonrpc":"2.0","id":"0","result":{{"height":{height},"target_height":{target},"synchronized":true}}}}"#
)
} else if req.contains("get_address") {
format!(
r#"{{"jsonrpc":"2.0","id":"0","result":{{"address":"{addr}"}}}}"#,
addr = xmr_addr()
)
} else {
r#"{"jsonrpc":"2.0","id":"0","result":{"balance":"0"}}"#.to_string()
}
});
tokio::spawn(serve_mock_rpc(listener, reply));
Wallet::from_url(&format!("http://ow:[email protected]:{port}")).expect("wallet url")
}

View file

@ -848,26 +848,21 @@ impl Wallet {
"params": params,
})
.to_string();
let raw = post_timeout(ep, &build_req(ep, &body, None), budget).await?;
let (challenged, raw) = post_digest(ep, &body, budget).await?;
let status = http_status(&raw).unwrap_or(0);
if status == 200 {
if status == 401 {
// A digest built from *this* connection's own challenge was
// refused, so the login is wrong, not the flow.
return Err(Error(
"wallet RPC digest rejected (HTTP 401) — the login does not match the child's --rpc-login"
.into(),
));
}
if !challenged && status == 200 {
return Err(Error(
"wallet RPC requires digest auth (open RPC refused)".into(),
));
}
if status != 401 {
return parse_json_rpc(&raw);
}
let challenge = www_authenticate(&raw).ok_or_else(|| {
Error("wallet RPC digest required (--rpc-login / HTTP Digest)".into())
})?;
if !challenge.trim().to_ascii_lowercase().starts_with("digest") {
return Err(Error(
"wallet RPC digest required (--rpc-login / HTTP Digest)".into(),
));
}
let auth = digest_authorization(ep, &challenge)?;
let raw = post_timeout(ep, &build_req(ep, &body, Some(&auth)), budget).await?;
parse_json_rpc(&raw)
}
}
@ -996,19 +991,65 @@ fn host_header(host: &str, port: u16) -> String {
const MAX_RPC_BYTES: usize = 1024 * 1024;
async fn post_timeout(ep: &Endpoint, req: &str, budget: Duration) -> Result<Vec<u8>> {
tokio::time::timeout(budget, http_post(ep, req.as_bytes()))
/// One loopback connection: ask for the digest challenge, answer it, and hand
/// back `(was_challenged, final_response)`.
///
/// The retry has to ride the **same socket** as the challenge. epee owns its
/// digest state per connection — `http_custom_handler` holds the
/// `http_server_auth`, whose session starts with an empty nonce and counter 0,
/// and any request without a valid `Authorization` field makes it mint a fresh
/// nonce. A retry that opens a new socket presents a nonce that connection never
/// issued, so `monero-wallet-rpc` answers 401 again, permanently. That is the
/// 401 the TUI and Android showed against a real wallet RPC while a canned mock
/// (which replays the challenge on any socket) stayed green.
async fn post_digest(ep: &Endpoint, body: &str, budget: Duration) -> Result<(bool, Vec<u8>)> {
tokio::time::timeout(budget, http_digest(ep, body))
.await
.map_err(|_| Error("wallet RPC timed out".into()))?
}
fn build_req(ep: &Endpoint, body: &str, authorization: Option<&str>) -> String {
async fn http_digest(ep: &Endpoint, body: &str) -> Result<(bool, Vec<u8>)> {
let mut stream = TcpStream::connect((ep.host.as_str(), ep.port))
.await
.map_err(|e| Error(format!("wallet connect: {e}")))?;
// No `Connection: close` on the challenge: epee closes the socket with the
// 401 when the request asks for it, and the retry needs this connection.
let req = build_req(ep, body, None, false);
stream
.write_all(req.as_bytes())
.await
.map_err(|e| Error(format!("wallet write: {e}")))?;
let raw = read_one_response(&mut stream).await?;
let status = http_status(&raw).unwrap_or(0);
if status != 401 {
return Ok((false, raw));
}
let challenge = www_authenticate(&raw)
.ok_or_else(|| Error("wallet RPC digest required (--rpc-login / HTTP Digest)".into()))?;
if !challenge.trim().to_ascii_lowercase().starts_with("digest") {
return Err(Error(
"wallet RPC digest required (--rpc-login / HTTP Digest)".into(),
));
}
let auth = digest_authorization(ep, &challenge)?;
let req = build_req(ep, body, Some(&auth), true);
stream
.write_all(req.as_bytes())
.await
.map_err(|e| Error(format!("wallet write: {e}")))?;
Ok((true, read_to_eof(&mut stream).await?))
}
fn build_req(ep: &Endpoint, body: &str, authorization: Option<&str>, close: bool) -> String {
let host_hdr = host_header(&ep.host, ep.port);
let mut req = format!(
"POST {} HTTP/1.1\r\nHost: {host_hdr}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n",
"POST {} HTTP/1.1\r\nHost: {host_hdr}\r\nContent-Type: application/json\r\nContent-Length: {}\r\n",
ep.path,
body.len()
);
if close {
req.push_str("Connection: close\r\n");
}
if let Some(auth) = authorization {
req.push_str("Authorization: ");
req.push_str(auth);
@ -1019,32 +1060,73 @@ fn build_req(ep: &Endpoint, body: &str, authorization: Option<&str>) -> String {
req
}
async fn http_post(ep: &Endpoint, req: &[u8]) -> Result<Vec<u8>> {
let mut stream = TcpStream::connect((ep.host.as_str(), ep.port))
.await
.map_err(|e| Error(format!("wallet connect: {e}")))?;
stream
.write_all(req)
.await
.map_err(|e| Error(format!("wallet write: {e}")))?;
/// Read exactly one HTTP response: its head, then `Content-Length` body bytes.
/// epee always emits `Content-Length`, and a keep-alive response never ends in
/// EOF — reading to EOF here would hang on a healthy server.
async fn read_one_response(stream: &mut TcpStream) -> Result<Vec<u8>> {
let mut buf = Vec::new();
let mut tmp = [0u8; 8192];
loop {
let n = stream
.read(&mut tmp)
.await
.map_err(|e| Error(format!("wallet read: {e}")))?;
if n == 0 {
let head_end = loop {
if let Some(i) = find_head_end(&buf) {
break i;
}
if !read_more(stream, &mut buf).await? {
// Closed before a full head: hand back what arrived, the status-line
// parse decides what that means.
return Ok(buf);
}
};
let head = std::str::from_utf8(&buf[..head_end]).unwrap_or_default();
// epee always sends `Content-Length`, but an open (challenge-less) RPC may
// not: with no length the body ends at EOF, so keep reading — the cap below
// is what stops a server that streams forever.
let Some(want) = content_length(head) else {
while read_more(stream, &mut buf).await? {}
return Ok(buf);
};
while buf.len() < head_end + 4 + want {
if !read_more(stream, &mut buf).await? {
break;
}
if buf.len().saturating_add(n) > MAX_RPC_BYTES {
return Err(Error("wallet RPC response too large".into()));
}
buf.extend_from_slice(&tmp[..n]);
}
Ok(buf)
}
async fn read_to_eof(stream: &mut TcpStream) -> Result<Vec<u8>> {
let mut buf = Vec::new();
while read_more(stream, &mut buf).await? {}
Ok(buf)
}
/// One read into `buf`. `false` means the peer closed. Enforces the shared cap.
async fn read_more(stream: &mut TcpStream, buf: &mut Vec<u8>) -> Result<bool> {
let mut tmp = [0u8; 8192];
let n = stream
.read(&mut tmp)
.await
.map_err(|e| Error(format!("wallet read: {e}")))?;
if n == 0 {
return Ok(false);
}
if buf.len().saturating_add(n) > MAX_RPC_BYTES {
return Err(Error("wallet RPC response too large".into()));
}
buf.extend_from_slice(&tmp[..n]);
Ok(true)
}
fn find_head_end(buf: &[u8]) -> Option<usize> {
buf.windows(4).position(|w| w == b"\r\n\r\n")
}
fn content_length(head: &str) -> Option<usize> {
head.lines().skip(1).find_map(|line| {
let (k, v) = line.split_once(':')?;
k.eq_ignore_ascii_case("content-length")
.then(|| v.trim().parse().ok())
.flatten()
})
}
fn http_status(raw: &[u8]) -> Option<u16> {
let text = std::str::from_utf8(raw).ok()?;
let line = text.lines().next()?;