wallet: answer the Digest challenge on the connection that issued it
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:
parent
b805bd4ad9
commit
cb411da813
4 changed files with 435 additions and 161 deletions
275
tests/wallet.rs
275
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<dyn Fn(&str) -> String + Send + Sync>,
|
||||
log: Option<Arc<Mutex<Vec<String>>>>,
|
||||
delay: Option<std::time::Duration>,
|
||||
raw_reply: bool,
|
||||
) {
|
||||
let mut nonce: Option<String> = 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<dyn Fn(&str) -> String + Send + Sync>,
|
||||
log: Option<Arc<Mutex<Vec<String>>>>,
|
||||
delay: Option<std::time::Duration>,
|
||||
) {
|
||||
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<dyn Fn(&str) -> String + Send + Sync>,
|
||||
log: Option<Arc<Mutex<Vec<String>>>>,
|
||||
delay: Option<std::time::Duration>,
|
||||
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<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;
|
||||
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<String> {
|
||||
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<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()
|
||||
})
|
||||
}
|
||||
|
||||
/// The `nonce` a request's `Authorization` field answers.
|
||||
fn authorization_nonce(req: &str) -> Option<String> {
|
||||
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";
|
||||
|
|
|
|||
Loading…
Reference in a new issue