Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 30 additions & 1 deletion crates/buzz-test-client/src/acceptance/fake_relay.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ use nostr::{Event, PublicKey};
use serde_json::{json, Value};
use tokio::net::TcpListener;
use tokio::sync::mpsc;
use tokio_tungstenite::tungstenite::handshake::server::{Request, Response};
use tokio_tungstenite::tungstenite::http::HeaderMap;
use tokio_tungstenite::tungstenite::Message;

use super::{AUTH_REQUIRED, PUBKEY_MISMATCH};
Expand Down Expand Up @@ -72,6 +74,10 @@ struct Shared {
events: Mutex<Vec<Event>>,
/// Live subscriptions: subscription id and the connection to send to.
live: Mutex<Vec<(String, Outbox)>>,
/// The headers of every WebSocket upgrade, in order.
upgrades: Mutex<Vec<HeaderMap>>,
/// The `relay` tag of every AUTH event, in order.
auth_relays: Mutex<Vec<String>>,
}

/// A running scripted relay.
Expand All @@ -86,6 +92,16 @@ impl FakeRelay {
pub fn events(&self) -> Vec<Event> {
self.shared.events.lock().unwrap().clone()
}

/// The headers of every WebSocket upgrade so far, in order.
pub fn upgrades(&self) -> Vec<HeaderMap> {
self.shared.upgrades.lock().unwrap().clone()
}

/// The `relay` tag of every AUTH event so far, in order.
pub fn auth_relays(&self) -> Vec<String> {
self.shared.auth_relays.lock().unwrap().clone()
}
}

/// Starts a relay that follows `script` on a free local port.
Expand All @@ -96,6 +112,8 @@ pub async fn start(script: Script) -> FakeRelay {
script,
events: Mutex::new(Vec::new()),
live: Mutex::new(Vec::new()),
upgrades: Mutex::new(Vec::new()),
auth_relays: Mutex::new(Vec::new()),
});
let accept = shared.clone();
tokio::spawn(async move {
Expand All @@ -106,9 +124,17 @@ pub async fn start(script: Script) -> FakeRelay {
FakeRelay { url, shared }
}

// The handshake callback's `Result<Response, ErrorResponse>` is fixed by tungstenite.
#[allow(clippy::result_large_err)]
async fn serve(tcp: tokio::net::TcpStream, shared: Arc<Shared>) {
// A plain HTTP request (the NIP-11 fetch) fails the upgrade; that is fine.
let Ok(ws) = tokio_tungstenite::accept_async(tcp).await else {
let upgrade =
tokio_tungstenite::accept_hdr_async(tcp, |request: &Request, response: Response| {
let headers = request.headers().clone();
shared.upgrades.lock().unwrap().push(headers);
Ok(response)
});
let Ok(ws) = upgrade.await else {
return;
};
let (mut sink, mut stream) = ws.split();
Expand All @@ -134,6 +160,9 @@ async fn serve(tcp: tokio::net::TcpStream, shared: Arc<Shared>) {
match msg.first().and_then(Value::as_str) {
Some("AUTH") => {
let event: Event = serde_json::from_value(msg[1].clone()).unwrap();
let relay = event.tags.iter().find(|t| t.kind().to_string() == "relay");
let relay = relay.and_then(|t| t.content()).unwrap_or_default();
shared.auth_relays.lock().unwrap().push(relay.to_owned());
authed = Some(event.pubkey);
send(&out, json!(["OK", event.id.to_hex(), true, ""]));
}
Expand Down
190 changes: 160 additions & 30 deletions crates/buzz-test-client/src/acceptance/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,10 @@ pub const CHECKS: [&str; 8] = [
pub struct Config {
/// The relay's WebSocket URL (`wss://…` or `ws://…`).
pub relay_url: String,
/// A plaintext `host:port` to dial instead of the URL's host, such as the
/// relay's in-cluster service. `relay_url` still names the relay: it
/// supplies the `Host` header, the NIP-42 relay tag and the community.
pub connect_addr: Option<String>,
/// The identity the probe authenticates and signs as.
pub keys: Keys,
/// A file holding a NIP-FI assertion for `keys`. It is read again before
Expand Down Expand Up @@ -278,13 +282,13 @@ async fn relay_info(cfg: &Config) -> (CheckReport, Option<String>) {
let mut check = Check::new("relay_info", cfg.stage_timeout);
let result = check
.stage("nip11", async {
let url = http_url(&cfg.relay_url)?;
let response = reqwest::Client::new()
.get(url)
let response = nip11_request(cfg)?
.header("Accept", "application/nostr+json")
.send()
.await?
.error_for_status()?;
.await?;
if !response.status().is_success() {
bail!("NIP-11 request answered {}", response.status());
}
let info: serde_json::Value = response.json().await?;
if !info["supported_nips"].is_array() {
bail!("not a NIP-11 document: no supported_nips");
Expand All @@ -301,14 +305,7 @@ async fn relay_info(cfg: &Config) -> (CheckReport, Option<String>) {
async fn connect_auth(cfg: &Config) -> (CheckReport, Option<NostrWsConnection>) {
let mut check = Check::new("connect_auth", cfg.stage_timeout);
let result = async {
let mut conn = check
.stage("ws_connect", async {
Ok(
NostrWsConnection::connect_with_headers(&cfg.relay_url, upgrade_headers(cfg)?)
.await?,
)
})
.await?;
let mut conn = check.stage("ws_connect", open(cfg)).await?;
check
.stage("nip42_auth", async {
Ok(conn.authenticate(&cfg.keys, None).await?)
Expand Down Expand Up @@ -384,13 +381,9 @@ async fn fanout(cfg: &Config, conn: &mut NostrWsConnection, channel: &str) -> Ch
let result = async {
let mut listener = check
.stage("connect_second", async {
Ok(NostrWsConnection::connect_authenticated_with_headers(
&cfg.relay_url,
&cfg.keys,
None,
upgrade_headers(cfg)?,
)
.await?)
let mut conn = open(cfg).await?;
conn.authenticate(&cfg.keys, None).await?;
Ok(conn)
})
.await?;
let result = fanout_on(&mut check, cfg, conn, &mut listener, channel).await;
Expand Down Expand Up @@ -534,9 +527,7 @@ async fn access_control(cfg: &Config, conn: &mut NostrWsConnection, channel: &st
check
.stage("unauthenticated_rejected", async {
let event = message(&cfg.keys, channel, "acceptance unauthenticated")?;
let mut anon =
NostrWsConnection::connect_with_headers(&cfg.relay_url, upgrade_headers(cfg)?)
.await?;
let mut anon = open(cfg).await?;
let outcome = anon.send_event(event).await;
let _ = anon.disconnect().await;
denied(outcome, AUTH_REQUIRED)
Expand All @@ -560,13 +551,9 @@ async fn cleanup(cfg: &Config, channel: &str) -> CheckReport {
let result = async {
let mut conn = check
.stage("connect", async {
Ok(NostrWsConnection::connect_authenticated_with_headers(
&cfg.relay_url,
&cfg.keys,
None,
upgrade_headers(cfg)?,
)
.await?)
let mut conn = open(cfg).await?;
conn.authenticate(&cfg.keys, None).await?;
Ok(conn)
})
.await?;
let result = check
Expand Down Expand Up @@ -681,6 +668,37 @@ pub fn read_secret_file(path: &Path, what: &str, max_bytes: u64) -> anyhow::Resu
Ok(text.to_owned())
}

/// Opens a connection to the relay without authenticating, at
/// `cfg.connect_addr` when one is set.
async fn open(cfg: &Config) -> anyhow::Result<NostrWsConnection> {
let headers = upgrade_headers(cfg)?;
Ok(match &cfg.connect_addr {
Some(addr) => NostrWsConnection::connect_to_addr(&cfg.relay_url, addr, headers).await?,
None => NostrWsConnection::connect_with_headers(&cfg.relay_url, headers).await?,
})
}

/// The NIP-11 request for the relay. With `cfg.connect_addr` it goes to that
/// address over plain HTTP, with the relay URL's host as the `Host` header,
/// so the relay serves the same community's document. Like the WebSocket
/// connections, it then uses no proxy and follows no redirect: either could
/// reach another deployment and report its version.
fn nip11_request(cfg: &Config) -> anyhow::Result<reqwest::RequestBuilder> {
let url = http_url(&cfg.relay_url)?;
let Some(addr) = &cfg.connect_addr else {
return Ok(reqwest::Client::new().get(url));
};
let client = reqwest::Client::builder()
.no_proxy()
.redirect(reqwest::redirect::Policy::none())
.build()?;
let host = &url[url::Position::BeforeHost..url::Position::AfterPort];
let target = &url[url::Position::BeforePath..url::Position::AfterQuery];
Ok(client
.get(format!("http://{addr}{target}"))
.header(reqwest::header::HOST, host))
}

/// The relay's HTTP base for `ws_url`: `wss` becomes `https`, `ws` `http`.
fn http_url(ws_url: &str) -> anyhow::Result<url::Url> {
let mut url = url::Url::parse(ws_url).with_context(|| format!("parse {ws_url}"))?;
Expand Down Expand Up @@ -725,6 +743,7 @@ mod tests {
fn config(relay_url: String) -> Config {
Config {
relay_url,
connect_addr: None,
keys: Keys::generate(),
assertion_file: None,
stage_timeout: Duration::from_secs(2),
Expand Down Expand Up @@ -830,6 +849,117 @@ mod tests {
std::fs::remove_dir_all(dir).unwrap();
}

/// With a connect address the probe dials it, but every upgrade and
/// AUTH still names the relay URL, so the relay serves that community.
#[tokio::test]
async fn connect_addr_dials_the_address_and_keeps_the_relay_url() {
let dir = std::env::temp_dir().join(format!("acceptance-{}", uuid::Uuid::new_v4()));
std::fs::create_dir_all(&dir).unwrap();
let assertion = dir.join("assertion");
std::fs::write(&assertion, "header.payload.signature").unwrap();
let relay = fake_relay::start(fake_relay::Script::default()).await;
let mut cfg = config("wss://relay.invalid".into());
cfg.connect_addr = Some(relay.url.trim_start_matches("ws://").to_owned());
cfg.assertion_file = Some(assertion);
let report = run(&cfg).await;
std::fs::remove_dir_all(dir).unwrap();

assert_all_pass_but_relay_info(&report);
let upgrades = relay.upgrades();
assert!(!upgrades.is_empty());
for headers in &upgrades {
assert_eq!(headers["host"], "relay.invalid", "{headers:?}");
assert_eq!(
headers["nostr-federated-identity"], "Bearer header.payload.signature",
"{headers:?}"
);
}
let relays = relay.auth_relays();
assert!(!relays.is_empty());
assert!(
relays.iter().all(|r| r == "wss://relay.invalid"),
"{relays:?}"
);
}

/// Serves one HTTP request with `head` (status line and headers) and
/// `body`. Returns the address and the request it received, lowercased.
async fn one_http_response(
head: &'static str,
body: &'static str,
) -> (String, tokio::task::JoinHandle<String>) {
use tokio::io::{AsyncReadExt, AsyncWriteExt};

let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap().to_string();
let server = tokio::spawn(async move {
let (mut tcp, _) = listener.accept().await.unwrap();
let mut request = Vec::new();
while !request.ends_with(b"\r\n\r\n") {
let mut byte = [0];
tcp.read_exact(&mut byte).await.unwrap();
request.push(byte[0]);
}
let response = format!(
"{head}\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}",
body.len()
);
tcp.write_all(response.as_bytes()).await.unwrap();
String::from_utf8(request).unwrap().to_ascii_lowercase()
});
(addr, server)
}

/// With a connect address the NIP-11 fetch goes to it over plain HTTP,
/// with the relay URL's path and query, and its host and port as the
/// `Host` header.
#[tokio::test]
async fn nip11_goes_to_the_connect_addr_with_the_relay_host() {
let (addr, server) = one_http_response(
"HTTP/1.1 200 OK\r\ncontent-type: application/nostr+json",
r#"{"supported_nips":[1,11],"version":"1.2.3"}"#,
)
.await;
let mut cfg = config("wss://relay.invalid:8443/relay?route=probe".into());
cfg.connect_addr = Some(addr);
let (report, version) = relay_info(&cfg).await;

assert_eq!(report.result, Outcome::Success, "{report:?}");
assert_eq!(version.as_deref(), Some("1.2.3"));
let request = server.await.unwrap();
assert!(
request.starts_with("get /relay?route=probe http/1.1\r\n"),
"{request}"
);
assert!(
request.contains("\r\nhost: relay.invalid:8443\r\n"),
"{request}"
);
}

/// With a connect address the NIP-11 fetch follows no redirect: one to
/// another host fails the check and reports no version.
#[tokio::test]
async fn nip11_at_the_connect_addr_does_not_follow_a_redirect() {
let (addr, server) = one_http_response(
"HTTP/1.1 301 Moved Permanently\r\nlocation: http://127.0.0.1:9/",
"",
)
.await;
let mut cfg = config("wss://relay.invalid".into());
cfg.connect_addr = Some(addr);
let (report, version) = relay_info(&cfg).await;

assert_eq!(report.result, Outcome::Failure, "{report:?}");
assert_eq!(report.failed_stage, Some("nip11"));
assert!(
report.error.as_deref().unwrap().contains("301"),
"{report:?}"
);
assert_eq!(version, None);
server.await.unwrap();
}

#[test]
fn http_url_maps_websocket_schemes() {
assert_eq!(
Expand Down
7 changes: 7 additions & 0 deletions crates/buzz-test-client/src/bin/acceptance.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
//!
//! Usage:
//! buzz-acceptance --relay-url wss://relay.example
//! [--connect-addr relay.internal:80]
//! [--private-key <key> | --private-key-file <path>] [--assertion-file <path>]
//! [--statsd-addr 127.0.0.1:8125] [--tag env:staging]...

Expand Down Expand Up @@ -32,6 +33,11 @@ struct Cli {
/// The relay's WebSocket URL.
#[arg(long, env = "BUZZ_RELAY_URL")]
relay_url: String,
/// Plaintext `host:port` to dial instead of the relay URL's host, such as
/// the relay's in-cluster service. The URL still sets the `Host` header
/// and the NIP-42 relay tag.
#[arg(long, env = "BUZZ_ACCEPTANCE_CONNECT_ADDR")]
Comment thread
TheSentinel454 marked this conversation as resolved.
Resolved
connect_addr: Option<String>,
/// Secret key (hex or nsec) to authenticate and sign as. Without this or
/// a key file the probe uses a new key, which works only on a relay that
/// admits any key.
Expand Down Expand Up @@ -112,6 +118,7 @@ async fn probe(cli: Cli) -> anyhow::Result<bool> {
};
let cfg = Config {
relay_url: cli.relay_url,
connect_addr: cli.connect_addr,
keys,
assertion_file: cli.assertion_file,
stage_timeout: Duration::from_secs(cli.stage_timeout_secs),
Expand Down
5 changes: 3 additions & 2 deletions crates/buzz-test-client/src/loadgen/net.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use std::collections::HashSet;
use std::net::SocketAddr;
use std::time::Duration;

use buzz_ws_client::NostrWsConnection;
use buzz_ws_client::{HeaderMap, NostrWsConnection};
use nostr::{Event, JsonUtil, Keys, Tag};

use super::identity;
Expand Down Expand Up @@ -59,7 +59,8 @@ impl Net {
let attempt = async {
let mut conn = match (&self.connect_addr, &community.host) {
(Some(addr), Some(_)) => {
NostrWsConnection::connect_to_addr(&community.ws_url, addr).await?
NostrWsConnection::connect_to_addr(&community.ws_url, addr, HeaderMap::new())
.await?
}
_ => NostrWsConnection::connect(&community.ws_url).await?,
};
Expand Down
2 changes: 2 additions & 0 deletions crates/buzz-test-client/tests/e2e_acceptance.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ fn relay_url() -> String {
async fn every_acceptance_check_passes_against_a_live_relay() {
let report = acceptance::run(&Config {
relay_url: relay_url(),
connect_addr: None,
keys: Keys::generate(),
assertion_file: None,
stage_timeout: Duration::from_secs(10),
Expand Down Expand Up @@ -61,6 +62,7 @@ fn probe_with_env(args: &[&str], envs: &[(&str, &str)]) -> (Output, Vec<String>)
.env_remove("BUZZ_PRIVATE_KEY_FILE")
.env_remove("BUZZ_ACCEPTANCE_ASSERTION_FILE")
.env_remove("BUZZ_ACCEPTANCE_STATSD_ADDR")
.env_remove("BUZZ_ACCEPTANCE_CONNECT_ADDR")
.env_remove("BUZZ_RELAY_URL")
.envs(envs.iter().copied())
.stdout(Stdio::piped())
Expand Down
Loading
Loading