diff --git a/docs/WALLET.md b/docs/WALLET.md index 6e431e2..054c48c 100644 --- a/docs/WALLET.md +++ b/docs/WALLET.md @@ -283,6 +283,14 @@ OnionWire refuses an RPC that answers HTTP 200 without a Digest challenge, and refuses URLs without credentials. Prefer `ONIONWIRE_WALLET_RPC_LOGIN` over userinfo in the URL. Do not log the password. +`monero-wallet-rpc` mints its Digest nonce **per TCP connection** (epee's +`http_custom_handler` owns the auth state), so the challenge and the +authenticated retry have to ride the same socket — a retry on a fresh connection +is refused with 401 no matter how correct the login is. OnionWire does exactly +that. A `wallet RPC HTTP HTTP/1.1 401 Unauthorized` status therefore means one +thing: the login does not match the child's `--rpc-login`. Regenerate the child +(and its sealed creds) rather than retrying. + ## The spend-authority warning An OnionWire instance pointed at a **spend-capable** `monero-wallet-rpc` is a diff --git a/src/node.rs b/src/node.rs index 15e7220..fcc8015 100644 --- a/src/node.rs +++ b/src/node.rs @@ -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 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 = 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 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:secret@127.0.0.1:{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 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:secret@127.0.0.1:{port}")).expect("wallet url") } diff --git a/src/wallet.rs b/src/wallet.rs index 226dab0..7195691 100644 --- a/src/wallet.rs +++ b/src/wallet.rs @@ -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> { - 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)> { + 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)> { + 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> { - 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> { 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> { + 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) -> Result { + 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 { + buf.windows(4).position(|w| w == b"\r\n\r\n") +} + +fn content_length(head: &str) -> Option { + 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 { let text = std::str::from_utf8(raw).ok()?; let line = text.lines().next()?; diff --git a/tests/wallet.rs b/tests/wallet.rs index 3007ab9..da8e8f3 100644 --- a/tests/wallet.rs +++ b/tests/wallet.rs @@ -248,6 +248,81 @@ async fn oversized_rpc_response_is_err() { ); } +/// The Digest challenge is bound to the **connection** that answered 401, the +/// way epee does it: `http_custom_handler` owns the `http_server_auth`, whose +/// nonce starts empty, so a nonce is only ever valid on the socket that received +/// it. A client that retries on a fresh socket presents a nonce that socket +/// never issued and is refused again — the real `monero-wallet-rpc` 401 this +/// suite reproduces. One socket serves requests until it closes; the mock closes +/// after an authenticated reply, because the client asks for `Connection: close` +/// there and epee honours it. +async fn serve_one_conn( + mut sock: tokio::net::TcpStream, + reply: Arc String + Send + Sync>, + log: Option>>>, + delay: Option, + raw_reply: bool, +) { + let mut nonce: Option = None; + while let Some(req) = read_http_request(&mut sock).await { + if let Some(log) = &log { + log.lock().expect("log").push(req.clone()); + } + let sent = authorization_nonce(&req); + if sent.is_some() && sent == nonce { + assert!(req.contains("Authorization: Digest"), "missing digest auth: {req}"); + assert!(req.contains("username=\"ow\""), "missing user: {req}"); + assert!(req.contains("response=\""), "missing response: {req}"); + if let Some(d) = delay { + tokio::time::sleep(d).await; + } + let answer = reply(&rpc_method(&req)); + // `raw_reply` servers hand back a whole HTTP response (some tests + // bake their own status line); the default is a JSON-RPC body. + let wire = if raw_reply { + answer + } else { + http_200_body(&answer) + }; + let _ = sock.write_all(wire.as_bytes()).await; + return; + } + let fresh = next_nonce(); + let _ = sock.write_all(digest_401(&fresh).as_bytes()).await; + nonce = Some(fresh); + } +} + +/// Accept loop for [`serve_one_conn`]. +async fn serve_rpc_conns( + listener: TcpListener, + reply: Arc String + Send + Sync>, + log: Option>>>, + delay: Option, +) { + serve_rpc_conns_with(listener, reply, log, delay, false).await +} + +/// [`serve_rpc_conns`] with the reply contract spelled out: `raw_reply` means the +/// closure returns a complete HTTP response, otherwise a JSON-RPC body. +async fn serve_rpc_conns_with( + listener: TcpListener, + reply: Arc String + Send + Sync>, + log: Option>>>, + delay: Option, + raw_reply: bool, +) { + while let Ok((sock, _)) = listener.accept().await { + tokio::spawn(serve_one_conn( + sock, + Arc::clone(&reply), + log.clone(), + delay, + raw_reply, + )); + } +} + /// 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( @@ -255,21 +330,62 @@ async fn serve_recording( log: Arc>>, reply: Arc 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; + serve_rpc_conns(listener, reply, Some(log), None).await +} + +/// Read one whole request: its head, then `Content-Length` body bytes. `None` +/// when the peer closed. +async fn read_http_request(sock: &mut tokio::net::TcpStream) -> Option { + let mut buf = Vec::new(); + let mut tmp = [0u8; 4096]; + let head_end = loop { + if let Some(i) = find_head_end(&buf) { + break i; + } + match sock.read(&mut tmp).await { + Ok(0) | Err(_) => return None, + Ok(n) => buf.extend_from_slice(&tmp[..n]), + } + }; + let head = String::from_utf8_lossy(&buf[..head_end]).to_string(); + let want = content_length(&head).unwrap_or(0); + while buf.len() < head_end + 4 + want { + match sock.read(&mut tmp).await { + Ok(0) | Err(_) => break, + Ok(n) => buf.extend_from_slice(&tmp[..n]), } } + Some(String::from_utf8_lossy(&buf).to_string()) +} + +fn find_head_end(buf: &[u8]) -> Option { + buf.windows(4).position(|w| w == b"\r\n\r\n") +} + +fn content_length(head: &str) -> Option { + 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() + }) +} + +/// The `nonce` a request's `Authorization` field answers. +fn authorization_nonce(req: &str) -> Option { + let head = req.split("\r\n\r\n").next().unwrap_or(req); + let line = head + .lines() + .find(|l| l.to_ascii_lowercase().starts_with("authorization:"))?; + let rest = line.split_once("nonce=")?.1; + Some(rest.trim_start_matches('"').split('"').next()?.to_string()) +} + +/// A fresh server nonce per 401, so a stale one never passes by luck. +fn next_nonce() -> String { + use std::sync::atomic::{AtomicUsize, Ordering}; + static NEXT: AtomicUsize = AtomicUsize::new(1); + format!("nonce{:016x}", NEXT.fetch_add(1, Ordering::Relaxed)) } fn rpc_method(req: &str) -> String { @@ -588,28 +704,106 @@ fn from_env_reads_no_spend_flag() { 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() +fn digest_401(nonce: &str) -> String { + format!( + "HTTP/1.1 401 Unauthorized\r\nWWW-Authenticate: Digest realm=\"monero-rpc\", nonce=\"{nonce}\", qop=\"auth\", algorithm=MD5\r\nContent-Length: 0\r\n\r\n" + ) } +/// Answers the Digest challenge on one connection with `ok` — a complete HTTP +/// response — to every method. async fn serve_digest_then(listener: TcpListener, ok: String) { - let (mut sock, _) = listener.accept().await.expect("accept"); - let mut buf = vec![0u8; 8192]; - let _ = sock.read(&mut buf).await; - sock.write_all(digest_401().as_bytes()).await.expect("401"); - drop(sock); + serve_rpc_conns_with(listener, Arc::new(move |_| ok.clone()), None, None, true).await +} - let (mut sock, _) = listener.accept().await.expect("accept2"); - buf.fill(0); - let n = sock.read(&mut buf).await.unwrap_or(0); - let req = String::from_utf8_lossy(&buf[..n]); - assert!( - req.contains("Authorization: Digest"), - "missing digest auth: {req}" +/// The digest retry must ride the socket that issued the challenge. epee binds +/// the nonce to the connection, so the pre-fix shape — challenge on one socket, +/// authenticated retry on another — is refused with 401 forever. That is the +/// `wallet RPC HTTP HTTP/1.1 401 Unauthorized` the TUI and Android showed while +/// this suite stayed green against a mock that replayed the challenge on any +/// socket. +#[tokio::test] +async fn digest_retry_rides_the_connection_that_issued_the_challenge() { + use std::sync::atomic::{AtomicUsize, Ordering}; + + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let port = listener.local_addr().unwrap().port(); + let conns = Arc::new(AtomicUsize::new(0)); + let counted = Arc::clone(&conns); + tokio::spawn(async move { + while let Ok((sock, _)) = listener.accept().await { + counted.fetch_add(1, Ordering::SeqCst); + tokio::spawn(serve_one_conn( + sock, + Arc::new(|_: &str| { + rpc_result( + r#"{"address":"4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"}"#, + ) + }), + None, + None, + false, + )); + } + }); + + let got = recording_wallet(port) + .get_address() + .await + .expect("a same-socket digest retry must be accepted"); + assert!(got.starts_with('4'), "got {got}"); + assert_eq!( + conns.load(Ordering::SeqCst), + 1, + "one RPC call must use one connection: challenge and retry share it" + ); +} + +/// The flip side, pinned at the socket level: the nonce belongs to the +/// connection that minted it, so the same digest on a second connection is +/// refused. Without this the mock could silently go back to accepting the +/// cross-connection retry and stop catching the bug. +#[tokio::test] +async fn the_mock_refuses_a_digest_presented_on_another_connection() { + use tokio::net::TcpStream; + + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let port = listener.local_addr().unwrap().port(); + tokio::spawn(serve_rpc_conns( + listener, + Arc::new(|_: &str| rpc_result("{}")), + None, + None, + )); + + let body = r#"{"jsonrpc":"2.0","id":"0","method":"get_version","params":{}}"#; + let plain = format!( + "POST /json_rpc HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\nContent-Type: application/json\r\nContent-Length: {}\r\n\r\n{body}", + body.len() + ); + + let mut first = TcpStream::connect(("127.0.0.1", port)).await.unwrap(); + first.write_all(plain.as_bytes()).await.unwrap(); + let raw = read_http_request(&mut first).await.expect("the 401"); + assert!(raw.starts_with("HTTP/1.1 401"), "got {raw}"); + let nonce = raw + .split_once("nonce=\"") + .and_then(|(_, rest)| rest.split('"').next()) + .expect("a challenge nonce") + .to_string(); + drop(first); + + let answered = format!( + "POST /json_rpc HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nAuthorization: Digest username=\"ow\", realm=\"monero-rpc\", nonce=\"{nonce}\", uri=\"/json_rpc\", algorithm=MD5, response=\"deadbeef\"\r\n\r\n{body}", + body.len() + ); + let mut second = TcpStream::connect(("127.0.0.1", port)).await.unwrap(); + second.write_all(answered.as_bytes()).await.unwrap(); + let raw = read_http_request(&mut second).await.expect("the second 401"); + assert!( + raw.starts_with("HTTP/1.1 401"), + "a nonce from another connection must not be accepted: {raw}" ); - assert!(req.contains("username=\"ow\""), "missing user: {req}"); - assert!(req.contains("response=\""), "missing response: {req}"); - sock.write_all(ok.as_bytes()).await.expect("200"); } #[tokio::test] @@ -628,23 +822,18 @@ async fn mock_digest_auth_accepted() { /// Answers the Digest challenge, then holds the reply for `delay`. Lets a test /// prove which call classes get which budget. async fn serve_delayed(listener: TcpListener, delay: std::time::Duration) { - while let Ok((mut sock, _)) = listener.accept().await { - 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(); - if !req.contains("Authorization:") { - let _ = sock.write_all(digest_401().as_bytes()).await; - continue; - } - tokio::time::sleep(delay).await; - let body = match rpc_method(&req).as_str() { + serve_rpc_conns( + listener, + Arc::new(|method: &str| match method { "get_info" => synced_info(), _ => rpc_result( r#"{"address":"4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"}"#, ), - }; - let _ = sock.write_all(http_200_body(&body).as_bytes()).await; - } + }), + None, + Some(delay), + ) + .await } const SPEND_ADDR: &str = "8BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB";