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

@ -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()?;