Skip to content

Commit c692173

Browse files
Elrondclaude
authored andcommitted
acceptance: pin the connect-address NIP-11 request to that address
Review fixes (Legolas on #9830): - With a connect address, the NIP-11 request uses no proxy and follows no redirect, like the WebSocket connections. Either could reach another deployment and report its version. A non-2xx answer fails the check. - The request keeps the relay URL's query as well as its path. - The connect-address run test sets an assertion file and checks that every upgrade carries its bearer header, so dropping the headers on that path fails a test. The fake relay records each upgrade's headers. - New test: a redirect at the connect address fails nip11 with no version. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Signed-off-by: Elrond <28d6302a099e5225b02c4155ac4236e4912603df2ab08dbfc2f4fef08ce598c8@buzz.block.builderlab.xyz>
1 parent 9a41541 commit c692173

2 files changed

Lines changed: 86 additions & 27 deletions

File tree

‎crates/buzz-test-client/src/acceptance/fake_relay.rs‎

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ use serde_json::{json, Value};
1212
use tokio::net::TcpListener;
1313
use tokio::sync::mpsc;
1414
use tokio_tungstenite::tungstenite::handshake::server::{Request, Response};
15+
use tokio_tungstenite::tungstenite::http::HeaderMap;
1516
use tokio_tungstenite::tungstenite::Message;
1617

1718
use super::{AUTH_REQUIRED, PUBKEY_MISMATCH};
@@ -73,8 +74,8 @@ struct Shared {
7374
events: Mutex<Vec<Event>>,
7475
/// Live subscriptions: subscription id and the connection to send to.
7576
live: Mutex<Vec<(String, Outbox)>>,
76-
/// The `Host` header of every WebSocket upgrade, in order.
77-
hosts: Mutex<Vec<String>>,
77+
/// The headers of every WebSocket upgrade, in order.
78+
upgrades: Mutex<Vec<HeaderMap>>,
7879
/// The `relay` tag of every AUTH event, in order.
7980
auth_relays: Mutex<Vec<String>>,
8081
}
@@ -92,9 +93,9 @@ impl FakeRelay {
9293
self.shared.events.lock().unwrap().clone()
9394
}
9495

95-
/// The `Host` header of every WebSocket upgrade so far, in order.
96-
pub fn hosts(&self) -> Vec<String> {
97-
self.shared.hosts.lock().unwrap().clone()
96+
/// The headers of every WebSocket upgrade so far, in order.
97+
pub fn upgrades(&self) -> Vec<HeaderMap> {
98+
self.shared.upgrades.lock().unwrap().clone()
9899
}
99100

100101
/// The `relay` tag of every AUTH event so far, in order.
@@ -111,7 +112,7 @@ pub async fn start(script: Script) -> FakeRelay {
111112
script,
112113
events: Mutex::new(Vec::new()),
113114
live: Mutex::new(Vec::new()),
114-
hosts: Mutex::new(Vec::new()),
115+
upgrades: Mutex::new(Vec::new()),
115116
auth_relays: Mutex::new(Vec::new()),
116117
});
117118
let accept = shared.clone();
@@ -129,9 +130,8 @@ async fn serve(tcp: tokio::net::TcpStream, shared: Arc<Shared>) {
129130
// A plain HTTP request (the NIP-11 fetch) fails the upgrade; that is fine.
130131
let upgrade =
131132
tokio_tungstenite::accept_hdr_async(tcp, |request: &Request, response: Response| {
132-
let host = request.headers().get("host").and_then(|h| h.to_str().ok());
133-
let host = host.unwrap_or_default().to_owned();
134-
shared.hosts.lock().unwrap().push(host);
133+
let headers = request.headers().clone();
134+
shared.upgrades.lock().unwrap().push(headers);
135135
Ok(response)
136136
});
137137
let Ok(ws) = upgrade.await else {

‎crates/buzz-test-client/src/acceptance/mod.rs‎

Lines changed: 77 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -285,8 +285,10 @@ async fn relay_info(cfg: &Config) -> (CheckReport, Option<String>) {
285285
let response = nip11_request(cfg)?
286286
.header("Accept", "application/nostr+json")
287287
.send()
288-
.await?
289-
.error_for_status()?;
288+
.await?;
289+
if !response.status().is_success() {
290+
bail!("NIP-11 request answered {}", response.status());
291+
}
290292
let info: serde_json::Value = response.json().await?;
291293
if !info["supported_nips"].is_array() {
292294
bail!("not a NIP-11 document: no supported_nips");
@@ -678,16 +680,22 @@ async fn open(cfg: &Config) -> anyhow::Result<NostrWsConnection> {
678680

679681
/// The NIP-11 request for the relay. With `cfg.connect_addr` it goes to that
680682
/// address over plain HTTP, with the relay URL's host as the `Host` header,
681-
/// so the relay serves the same community's document.
683+
/// so the relay serves the same community's document. Like the WebSocket
684+
/// connections, it then uses no proxy and follows no redirect: either could
685+
/// reach another deployment and report its version.
682686
fn nip11_request(cfg: &Config) -> anyhow::Result<reqwest::RequestBuilder> {
683687
let url = http_url(&cfg.relay_url)?;
684-
let client = reqwest::Client::new();
685688
let Some(addr) = &cfg.connect_addr else {
686-
return Ok(client.get(url));
689+
return Ok(reqwest::Client::new().get(url));
687690
};
691+
let client = reqwest::Client::builder()
692+
.no_proxy()
693+
.redirect(reqwest::redirect::Policy::none())
694+
.build()?;
688695
let host = &url[url::Position::BeforeHost..url::Position::AfterPort];
696+
let target = &url[url::Position::BeforePath..url::Position::AfterQuery];
689697
Ok(client
690-
.get(format!("http://{addr}{}", url.path()))
698+
.get(format!("http://{addr}{target}"))
691699
.header(reqwest::header::HOST, host))
692700
}
693701

@@ -845,15 +853,27 @@ mod tests {
845853
/// AUTH still names the relay URL, so the relay serves that community.
846854
#[tokio::test]
847855
async fn connect_addr_dials_the_address_and_keeps_the_relay_url() {
856+
let dir = std::env::temp_dir().join(format!("acceptance-{}", uuid::Uuid::new_v4()));
857+
std::fs::create_dir_all(&dir).unwrap();
858+
let assertion = dir.join("assertion");
859+
std::fs::write(&assertion, "header.payload.signature").unwrap();
848860
let relay = fake_relay::start(fake_relay::Script::default()).await;
849861
let mut cfg = config("wss://relay.invalid".into());
850862
cfg.connect_addr = Some(relay.url.trim_start_matches("ws://").to_owned());
863+
cfg.assertion_file = Some(assertion);
851864
let report = run(&cfg).await;
865+
std::fs::remove_dir_all(dir).unwrap();
852866

853867
assert_all_pass_but_relay_info(&report);
854-
let hosts = relay.hosts();
855-
assert!(!hosts.is_empty());
856-
assert!(hosts.iter().all(|h| h == "relay.invalid"), "{hosts:?}");
868+
let upgrades = relay.upgrades();
869+
assert!(!upgrades.is_empty());
870+
for headers in &upgrades {
871+
assert_eq!(headers["host"], "relay.invalid", "{headers:?}");
872+
assert_eq!(
873+
headers["nostr-federated-identity"], "Bearer header.payload.signature",
874+
"{headers:?}"
875+
);
876+
}
857877
let relays = relay.auth_relays();
858878
assert!(!relays.is_empty());
859879
assert!(
@@ -862,10 +882,12 @@ mod tests {
862882
);
863883
}
864884

865-
/// With a connect address the NIP-11 fetch goes to it over plain HTTP,
866-
/// with the relay URL's host and port as the `Host` header.
867-
#[tokio::test]
868-
async fn nip11_goes_to_the_connect_addr_with_the_relay_host() {
885+
/// Serves one HTTP request with `head` (status line and headers) and
886+
/// `body`. Returns the address and the request it received, lowercased.
887+
async fn one_http_response(
888+
head: &'static str,
889+
body: &'static str,
890+
) -> (String, tokio::task::JoinHandle<String>) {
869891
use tokio::io::{AsyncReadExt, AsyncWriteExt};
870892

871893
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
@@ -878,29 +900,66 @@ mod tests {
878900
tcp.read_exact(&mut byte).await.unwrap();
879901
request.push(byte[0]);
880902
}
881-
let body = r#"{"supported_nips":[1,11],"version":"1.2.3"}"#;
882903
let response = format!(
883-
"HTTP/1.1 200 OK\r\ncontent-type: application/nostr+json\r\n\
884-
content-length: {}\r\nconnection: close\r\n\r\n{body}",
904+
"{head}\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}",
885905
body.len()
886906
);
887907
tcp.write_all(response.as_bytes()).await.unwrap();
888908
String::from_utf8(request).unwrap().to_ascii_lowercase()
889909
});
890-
let mut cfg = config("wss://relay.invalid:8443".into());
910+
(addr, server)
911+
}
912+
913+
/// With a connect address the NIP-11 fetch goes to it over plain HTTP,
914+
/// with the relay URL's path and query, and its host and port as the
915+
/// `Host` header.
916+
#[tokio::test]
917+
async fn nip11_goes_to_the_connect_addr_with_the_relay_host() {
918+
let (addr, server) = one_http_response(
919+
"HTTP/1.1 200 OK\r\ncontent-type: application/nostr+json",
920+
r#"{"supported_nips":[1,11],"version":"1.2.3"}"#,
921+
)
922+
.await;
923+
let mut cfg = config("wss://relay.invalid:8443/relay?route=probe".into());
891924
cfg.connect_addr = Some(addr);
892925
let (report, version) = relay_info(&cfg).await;
893926

894927
assert_eq!(report.result, Outcome::Success, "{report:?}");
895928
assert_eq!(version.as_deref(), Some("1.2.3"));
896929
let request = server.await.unwrap();
897-
assert!(request.starts_with("get / http/1.1\r\n"), "{request}");
930+
assert!(
931+
request.starts_with("get /relay?route=probe http/1.1\r\n"),
932+
"{request}"
933+
);
898934
assert!(
899935
request.contains("\r\nhost: relay.invalid:8443\r\n"),
900936
"{request}"
901937
);
902938
}
903939

940+
/// With a connect address the NIP-11 fetch follows no redirect: one to
941+
/// another host fails the check and reports no version.
942+
#[tokio::test]
943+
async fn nip11_at_the_connect_addr_does_not_follow_a_redirect() {
944+
let (addr, server) = one_http_response(
945+
"HTTP/1.1 301 Moved Permanently\r\nlocation: http://127.0.0.1:9/",
946+
"",
947+
)
948+
.await;
949+
let mut cfg = config("wss://relay.invalid".into());
950+
cfg.connect_addr = Some(addr);
951+
let (report, version) = relay_info(&cfg).await;
952+
953+
assert_eq!(report.result, Outcome::Failure, "{report:?}");
954+
assert_eq!(report.failed_stage, Some("nip11"));
955+
assert!(
956+
report.error.as_deref().unwrap().contains("301"),
957+
"{report:?}"
958+
);
959+
assert_eq!(version, None);
960+
server.await.unwrap();
961+
}
962+
904963
#[test]
905964
fn http_url_maps_websocket_schemes() {
906965
assert_eq!(

0 commit comments

Comments
 (0)