From 9a415414f163f5b72e8c01da72ede81a81bd3b7c Mon Sep 17 00:00:00 2001 From: Elrond <28d6302a099e5225b02c4155ac4236e4912603df2ab08dbfc2f4fef08ce598c8@buzz.block.builderlab.xyz> Date: Fri, 20 Nov 2026 15:33:32 -0500 Subject: [PATCH 1/3] acceptance: dial the relay at a connect address A probe inside the relay's network may not be able to reach the relay's public host. The probe and the chart can now name a plaintext host:port to dial instead: - buzz-acceptance --connect-addr (BUZZ_ACCEPTANCE_CONNECT_ADDR) dials that address for every WebSocket connection and for the NIP-11 fetch. The relay URL still sets the Host header, the NIP-42 relay tag and the NIP-11 Host, so the relay serves the same community. - The chart sets it from acceptance.connectAddr. Empty, the default, keeps dialing the URL. - NostrWsConnection::connect_to_addr takes upgrade headers, so the probe's NIP-FI assertion header goes on this path too. Loadgen passes none. - The fake relay records each upgrade's Host and each AUTH relay tag. New tests pin both and the NIP-11 request's address and Host. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Elrond <28d6302a099e5225b02c4155ac4236e4912603df2ab08dbfc2f4fef08ce598c8@buzz.block.builderlab.xyz> --- .../src/acceptance/fake_relay.rs | 31 ++++- crates/buzz-test-client/src/acceptance/mod.rs | 127 ++++++++++++++---- crates/buzz-test-client/src/bin/acceptance.rs | 7 + crates/buzz-test-client/src/loadgen/net.rs | 5 +- .../buzz-test-client/tests/e2e_acceptance.rs | 1 + crates/buzz-ws-client/src/connection.rs | 25 ++-- deploy/charts/buzz/README.md | 5 + .../buzz/templates/acceptance-cronjob.yaml | 3 + deploy/charts/buzz/tests/acceptance_test.yaml | 11 ++ deploy/charts/buzz/values.schema.json | 1 + deploy/charts/buzz/values.yaml | 4 + 11 files changed, 180 insertions(+), 40 deletions(-) diff --git a/crates/buzz-test-client/src/acceptance/fake_relay.rs b/crates/buzz-test-client/src/acceptance/fake_relay.rs index 13a051be943..c675ada9780 100644 --- a/crates/buzz-test-client/src/acceptance/fake_relay.rs +++ b/crates/buzz-test-client/src/acceptance/fake_relay.rs @@ -11,6 +11,7 @@ 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::Message; use super::{AUTH_REQUIRED, PUBKEY_MISMATCH}; @@ -72,6 +73,10 @@ struct Shared { events: Mutex>, /// Live subscriptions: subscription id and the connection to send to. live: Mutex>, + /// The `Host` header of every WebSocket upgrade, in order. + hosts: Mutex>, + /// The `relay` tag of every AUTH event, in order. + auth_relays: Mutex>, } /// A running scripted relay. @@ -86,6 +91,16 @@ impl FakeRelay { pub fn events(&self) -> Vec { self.shared.events.lock().unwrap().clone() } + + /// The `Host` header of every WebSocket upgrade so far, in order. + pub fn hosts(&self) -> Vec { + self.shared.hosts.lock().unwrap().clone() + } + + /// The `relay` tag of every AUTH event so far, in order. + pub fn auth_relays(&self) -> Vec { + self.shared.auth_relays.lock().unwrap().clone() + } } /// Starts a relay that follows `script` on a free local port. @@ -96,6 +111,8 @@ pub async fn start(script: Script) -> FakeRelay { script, events: Mutex::new(Vec::new()), live: Mutex::new(Vec::new()), + hosts: Mutex::new(Vec::new()), + auth_relays: Mutex::new(Vec::new()), }); let accept = shared.clone(); tokio::spawn(async move { @@ -106,9 +123,18 @@ pub async fn start(script: Script) -> FakeRelay { FakeRelay { url, shared } } +// The handshake callback's `Result` is fixed by tungstenite. +#[allow(clippy::result_large_err)] async fn serve(tcp: tokio::net::TcpStream, shared: Arc) { // 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 host = request.headers().get("host").and_then(|h| h.to_str().ok()); + let host = host.unwrap_or_default().to_owned(); + shared.hosts.lock().unwrap().push(host); + Ok(response) + }); + let Ok(ws) = upgrade.await else { return; }; let (mut sink, mut stream) = ws.split(); @@ -134,6 +160,9 @@ async fn serve(tcp: tokio::net::TcpStream, shared: Arc) { 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, ""])); } diff --git a/crates/buzz-test-client/src/acceptance/mod.rs b/crates/buzz-test-client/src/acceptance/mod.rs index 31079e8213e..2e549dec7de 100644 --- a/crates/buzz-test-client/src/acceptance/mod.rs +++ b/crates/buzz-test-client/src/acceptance/mod.rs @@ -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, /// 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 @@ -278,9 +282,7 @@ async fn relay_info(cfg: &Config) -> (CheckReport, Option) { 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? @@ -301,14 +303,7 @@ async fn relay_info(cfg: &Config) -> (CheckReport, Option) { async fn connect_auth(cfg: &Config) -> (CheckReport, Option) { 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?) @@ -384,13 +379,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; @@ -534,9 +525,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) @@ -560,13 +549,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 @@ -681,6 +666,31 @@ 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 { + 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. +fn nip11_request(cfg: &Config) -> anyhow::Result { + let url = http_url(&cfg.relay_url)?; + let client = reqwest::Client::new(); + let Some(addr) = &cfg.connect_addr else { + return Ok(client.get(url)); + }; + let host = &url[url::Position::BeforeHost..url::Position::AfterPort]; + Ok(client + .get(format!("http://{addr}{}", url.path())) + .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 { let mut url = url::Url::parse(ws_url).with_context(|| format!("parse {ws_url}"))?; @@ -725,6 +735,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), @@ -830,6 +841,66 @@ 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 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()); + let report = run(&cfg).await; + + assert_all_pass_but_relay_info(&report); + let hosts = relay.hosts(); + assert!(!hosts.is_empty()); + assert!(hosts.iter().all(|h| h == "relay.invalid"), "{hosts:?}"); + let relays = relay.auth_relays(); + assert!(!relays.is_empty()); + assert!( + relays.iter().all(|r| r == "wss://relay.invalid"), + "{relays:?}" + ); + } + + /// With a connect address the NIP-11 fetch goes to it over plain HTTP, + /// with the relay URL's host and port as the `Host` header. + #[tokio::test] + async fn nip11_goes_to_the_connect_addr_with_the_relay_host() { + 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 body = r#"{"supported_nips":[1,11],"version":"1.2.3"}"#; + let response = format!( + "HTTP/1.1 200 OK\r\ncontent-type: application/nostr+json\r\n\ + content-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() + }); + let mut cfg = config("wss://relay.invalid:8443".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 / http/1.1\r\n"), "{request}"); + assert!( + request.contains("\r\nhost: relay.invalid:8443\r\n"), + "{request}" + ); + } + #[test] fn http_url_maps_websocket_schemes() { assert_eq!( diff --git a/crates/buzz-test-client/src/bin/acceptance.rs b/crates/buzz-test-client/src/bin/acceptance.rs index 8128778b197..07714e16c5f 100644 --- a/crates/buzz-test-client/src/bin/acceptance.rs +++ b/crates/buzz-test-client/src/bin/acceptance.rs @@ -5,6 +5,7 @@ //! //! Usage: //! buzz-acceptance --relay-url wss://relay.example +//! [--connect-addr relay.internal:80] //! [--private-key | --private-key-file ] [--assertion-file ] //! [--statsd-addr 127.0.0.1:8125] [--tag env:staging]... @@ -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")] + connect_addr: Option, /// 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. @@ -112,6 +118,7 @@ async fn probe(cli: Cli) -> anyhow::Result { }; 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), diff --git a/crates/buzz-test-client/src/loadgen/net.rs b/crates/buzz-test-client/src/loadgen/net.rs index f8971ffc8c7..bfc63bb212f 100644 --- a/crates/buzz-test-client/src/loadgen/net.rs +++ b/crates/buzz-test-client/src/loadgen/net.rs @@ -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; @@ -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?, }; diff --git a/crates/buzz-test-client/tests/e2e_acceptance.rs b/crates/buzz-test-client/tests/e2e_acceptance.rs index 25ca22196d5..c2767f41207 100644 --- a/crates/buzz-test-client/tests/e2e_acceptance.rs +++ b/crates/buzz-test-client/tests/e2e_acceptance.rs @@ -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), diff --git a/crates/buzz-ws-client/src/connection.rs b/crates/buzz-ws-client/src/connection.rs index 918f971f101..ac3034a0884 100644 --- a/crates/buzz-ws-client/src/connection.rs +++ b/crates/buzz-ws-client/src/connection.rs @@ -120,18 +120,22 @@ impl NostrWsConnection { Ok(Self::from_stream(ws, url)) } - /// [`Self::connect`], but opens a plaintext TCP connection to `addr` - /// (`host:port`) instead of resolving the URL's host. + /// [`Self::connect_with_headers`], but opens a plaintext TCP connection to + /// `addr` (`host:port`) instead of resolving the URL's host. /// /// The URL still supplies the `Host` header and NIP-42 relay tag, even when /// it is `wss://`, so a client inside the relay's cluster can reach a /// community through the relay's plaintext service address and still /// authenticate for the community's public URL. - pub async fn connect_to_addr(url: &str, addr: &str) -> Result { + pub async fn connect_to_addr( + url: &str, + addr: &str, + headers: HeaderMap, + ) -> Result { let parsed = url .parse::() .map_err(|e| WsClientError::Url(e.to_string()))?; - let request = upgrade_request(&parsed, HeaderMap::new())?; + let request = upgrade_request(&parsed, headers)?; let tcp = tokio::net::TcpStream::connect(addr) .await .map_err(|e| WsClientError::WebSocket(e.into()))?; @@ -497,7 +501,7 @@ mod tests { }); let url = format!("ws://{addr}"); let _conn = if via_addr { - NostrWsConnection::connect_to_addr(&url, &addr).await + NostrWsConnection::connect_to_addr(&url, &addr, headers).await } else { NostrWsConnection::connect_with_headers(&url, headers).await } @@ -517,10 +521,13 @@ mod tests { async fn caller_user_agent_replaces_default() { let mut headers = HeaderMap::new(); headers.insert(USER_AGENT, HeaderValue::from_static("example/1.0")); - assert_eq!( - upgrade_user_agent(headers, false).await, - Some(HeaderValue::from_static("example/1.0")) - ); + for via_addr in [false, true] { + assert_eq!( + upgrade_user_agent(headers.clone(), via_addr).await, + Some(HeaderValue::from_static("example/1.0")), + "via_addr={via_addr}" + ); + } } /// A relay that answers NIP-42 AUTH by closing with `code`, as the relay diff --git a/deploy/charts/buzz/README.md b/deploy/charts/buzz/README.md index 592eb17204e..ee957d5acd6 100644 --- a/deploy/charts/buzz/README.md +++ b/deploy/charts/buzz/README.md @@ -527,6 +527,11 @@ image predates the probe. - The probe connects to `acceptance.relayUrl`, or to `relayUrl` when that is empty. Each run creates one private channel with a 1 h TTL and deletes it. +- `acceptance.connectAddr` is a plaintext `host:port` the probe dials instead + of the URL's host, for a probe that runs where the public host is not + reachable, such as inside the relay's cluster. The URL still sets the `Host` + header, the NIP-42 relay tag and the NIP-11 request's `Host`, so the relay + serves the same community. - `acceptance.privateKeySecret.name` names a Secret with the probe's key (hex or nsec), or `acceptance.privateKeyFile` names a file an init container writes. Set exactly one: the chart fails to render with neither. diff --git a/deploy/charts/buzz/templates/acceptance-cronjob.yaml b/deploy/charts/buzz/templates/acceptance-cronjob.yaml index 950c64b41a8..5b4e2e72ea6 100644 --- a/deploy/charts/buzz/templates/acceptance-cronjob.yaml +++ b/deploy/charts/buzz/templates/acceptance-cronjob.yaml @@ -77,6 +77,9 @@ spec: fieldRef: fieldPath: status.hostIP - { name: BUZZ_RELAY_URL, value: {{ default .Values.relayUrl $a.relayUrl | quote }} } + {{- with $a.connectAddr }} + - { name: BUZZ_ACCEPTANCE_CONNECT_ADDR, value: {{ . | quote }} } + {{- end }} {{- with $a.statsdAddr }} - { name: BUZZ_ACCEPTANCE_STATSD_ADDR, value: {{ . | quote }} } {{- end }} diff --git a/deploy/charts/buzz/tests/acceptance_test.yaml b/deploy/charts/buzz/tests/acceptance_test.yaml index 156d6e17f1a..f105d15811f 100644 --- a/deploy/charts/buzz/tests/acceptance_test.yaml +++ b/deploy/charts/buzz/tests/acceptance_test.yaml @@ -72,6 +72,11 @@ tests: content: name: BUZZ_ACCEPTANCE_STATSD_ADDR any: true + - notContains: + path: spec.jobTemplate.spec.template.spec.containers[0].env + content: + name: BUZZ_ACCEPTANCE_CONNECT_ADDR + any: true - contains: path: spec.jobTemplate.spec.template.spec.containers[0].env content: @@ -111,6 +116,7 @@ tests: acceptance: enabled: true relayUrl: wss://probe.example.com + connectAddr: relay.internal:80 schedule: "*/10 * * * *" activeDeadlineSeconds: 120 stageTimeoutSeconds: 5 @@ -183,6 +189,11 @@ tests: content: name: BUZZ_RELAY_URL value: wss://probe.example.com + - contains: + path: spec.jobTemplate.spec.template.spec.containers[0].env + content: + name: BUZZ_ACCEPTANCE_CONNECT_ADDR + value: relay.internal:80 - contains: path: spec.jobTemplate.spec.template.spec.containers[0].env content: diff --git a/deploy/charts/buzz/values.schema.json b/deploy/charts/buzz/values.schema.json index 3cd423ed9c2..0f6d11a48c2 100644 --- a/deploy/charts/buzz/values.schema.json +++ b/deploy/charts/buzz/values.schema.json @@ -227,6 +227,7 @@ "successfulJobsHistoryLimit": { "type": "integer", "minimum": 0 }, "failedJobsHistoryLimit": { "type": "integer", "minimum": 0 }, "relayUrl": { "type": "string" }, + "connectAddr": { "type": "string" }, "stageTimeoutSeconds": { "type": "integer", "minimum": 1 }, "privateKeySecret": { "type": "object", diff --git a/deploy/charts/buzz/values.yaml b/deploy/charts/buzz/values.yaml index 40da6029a1f..3680e40d78b 100644 --- a/deploy/charts/buzz/values.yaml +++ b/deploy/charts/buzz/values.yaml @@ -411,6 +411,10 @@ acceptance: successfulJobsHistoryLimit: 1 failedJobsHistoryLimit: 3 relayUrl: "" # empty → relayUrl + # 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. Empty → dial the URL. + connectAddr: "" # A run has 13 serial stage timeouts of this length. Keep activeDeadlineSeconds # above 13 × stageTimeoutSeconds + 30 s plus pull and init time: a run killed # at the deadline sends no metrics. From c692173c4dd195a42bad1824fc0f916de4e74279 Mon Sep 17 00:00:00 2001 From: Elrond <28d6302a099e5225b02c4155ac4236e4912603df2ab08dbfc2f4fef08ce598c8@buzz.block.builderlab.xyz> Date: Fri, 20 Nov 2026 15:41:53 -0500 Subject: [PATCH 2/3] 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 Signed-off-by: Elrond <28d6302a099e5225b02c4155ac4236e4912603df2ab08dbfc2f4fef08ce598c8@buzz.block.builderlab.xyz> --- .../src/acceptance/fake_relay.rs | 18 ++-- crates/buzz-test-client/src/acceptance/mod.rs | 95 +++++++++++++++---- 2 files changed, 86 insertions(+), 27 deletions(-) diff --git a/crates/buzz-test-client/src/acceptance/fake_relay.rs b/crates/buzz-test-client/src/acceptance/fake_relay.rs index c675ada9780..480341b0659 100644 --- a/crates/buzz-test-client/src/acceptance/fake_relay.rs +++ b/crates/buzz-test-client/src/acceptance/fake_relay.rs @@ -12,6 +12,7 @@ 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}; @@ -73,8 +74,8 @@ struct Shared { events: Mutex>, /// Live subscriptions: subscription id and the connection to send to. live: Mutex>, - /// The `Host` header of every WebSocket upgrade, in order. - hosts: Mutex>, + /// The headers of every WebSocket upgrade, in order. + upgrades: Mutex>, /// The `relay` tag of every AUTH event, in order. auth_relays: Mutex>, } @@ -92,9 +93,9 @@ impl FakeRelay { self.shared.events.lock().unwrap().clone() } - /// The `Host` header of every WebSocket upgrade so far, in order. - pub fn hosts(&self) -> Vec { - self.shared.hosts.lock().unwrap().clone() + /// The headers of every WebSocket upgrade so far, in order. + pub fn upgrades(&self) -> Vec { + self.shared.upgrades.lock().unwrap().clone() } /// The `relay` tag of every AUTH event so far, in order. @@ -111,7 +112,7 @@ pub async fn start(script: Script) -> FakeRelay { script, events: Mutex::new(Vec::new()), live: Mutex::new(Vec::new()), - hosts: Mutex::new(Vec::new()), + upgrades: Mutex::new(Vec::new()), auth_relays: Mutex::new(Vec::new()), }); let accept = shared.clone(); @@ -129,9 +130,8 @@ async fn serve(tcp: tokio::net::TcpStream, shared: Arc) { // A plain HTTP request (the NIP-11 fetch) fails the upgrade; that is fine. let upgrade = tokio_tungstenite::accept_hdr_async(tcp, |request: &Request, response: Response| { - let host = request.headers().get("host").and_then(|h| h.to_str().ok()); - let host = host.unwrap_or_default().to_owned(); - shared.hosts.lock().unwrap().push(host); + let headers = request.headers().clone(); + shared.upgrades.lock().unwrap().push(headers); Ok(response) }); let Ok(ws) = upgrade.await else { diff --git a/crates/buzz-test-client/src/acceptance/mod.rs b/crates/buzz-test-client/src/acceptance/mod.rs index 2e549dec7de..c5316f3b6b8 100644 --- a/crates/buzz-test-client/src/acceptance/mod.rs +++ b/crates/buzz-test-client/src/acceptance/mod.rs @@ -285,8 +285,10 @@ async fn relay_info(cfg: &Config) -> (CheckReport, Option) { 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"); @@ -678,16 +680,22 @@ async fn open(cfg: &Config) -> anyhow::Result { /// 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. +/// 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 { let url = http_url(&cfg.relay_url)?; - let client = reqwest::Client::new(); let Some(addr) = &cfg.connect_addr else { - return Ok(client.get(url)); + 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}{}", url.path())) + .get(format!("http://{addr}{target}")) .header(reqwest::header::HOST, host)) } @@ -845,15 +853,27 @@ mod tests { /// 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 hosts = relay.hosts(); - assert!(!hosts.is_empty()); - assert!(hosts.iter().all(|h| h == "relay.invalid"), "{hosts:?}"); + 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!( @@ -862,10 +882,12 @@ mod tests { ); } - /// With a connect address the NIP-11 fetch goes to it over plain HTTP, - /// with the relay URL's host and port as the `Host` header. - #[tokio::test] - async fn nip11_goes_to_the_connect_addr_with_the_relay_host() { + /// 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) { use tokio::io::{AsyncReadExt, AsyncWriteExt}; let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); @@ -878,29 +900,66 @@ mod tests { tcp.read_exact(&mut byte).await.unwrap(); request.push(byte[0]); } - let body = r#"{"supported_nips":[1,11],"version":"1.2.3"}"#; let response = format!( - "HTTP/1.1 200 OK\r\ncontent-type: application/nostr+json\r\n\ - content-length: {}\r\nconnection: close\r\n\r\n{body}", + "{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() }); - let mut cfg = config("wss://relay.invalid:8443".into()); + (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 / http/1.1\r\n"), "{request}"); + 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!( From ff6dc6817422c9e552957888019ddf48eba7f612 Mon Sep 17 00:00:00 2001 From: Luke Tornquist Date: Fri, 20 Nov 2026 16:11:30 -0500 Subject: [PATCH 3/3] acceptance: pass the chart's connect address as a flag The chart now passes acceptance.connectAddr as --connect-addr instead of an env var. A relay image whose probe predates the option rejects the unknown flag and the run fails, instead of checking the public URL and reporting success. The README states the image requirement. The binary tests clear BUZZ_ACCEPTANCE_CONNECT_ADDR so a developer shell cannot redirect them. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Luke Tornquist --- crates/buzz-test-client/tests/e2e_acceptance.rs | 1 + deploy/charts/buzz/README.md | 4 +++- deploy/charts/buzz/templates/acceptance-cronjob.yaml | 9 ++++++--- deploy/charts/buzz/tests/acceptance_test.yaml | 6 ++++-- 4 files changed, 14 insertions(+), 6 deletions(-) diff --git a/crates/buzz-test-client/tests/e2e_acceptance.rs b/crates/buzz-test-client/tests/e2e_acceptance.rs index c2767f41207..119ce8f03de 100644 --- a/crates/buzz-test-client/tests/e2e_acceptance.rs +++ b/crates/buzz-test-client/tests/e2e_acceptance.rs @@ -62,6 +62,7 @@ fn probe_with_env(args: &[&str], envs: &[(&str, &str)]) -> (Output, Vec) .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()) diff --git a/deploy/charts/buzz/README.md b/deploy/charts/buzz/README.md index ee957d5acd6..4c7876acd7e 100644 --- a/deploy/charts/buzz/README.md +++ b/deploy/charts/buzz/README.md @@ -531,7 +531,9 @@ image predates the probe. of the URL's host, for a probe that runs where the public host is not reachable, such as inside the relay's cluster. The URL still sets the `Host` header, the NIP-42 relay tag and the NIP-11 request's `Host`, so the relay - serves the same community. + serves the same community. The chart passes it as `--connect-addr`, so the + relay image's probe must have that flag. An older probe exits with an error + instead of checking the public URL. - `acceptance.privateKeySecret.name` names a Secret with the probe's key (hex or nsec), or `acceptance.privateKeyFile` names a file an init container writes. Set exactly one: the chart fails to render with neither. diff --git a/deploy/charts/buzz/templates/acceptance-cronjob.yaml b/deploy/charts/buzz/templates/acceptance-cronjob.yaml index 5b4e2e72ea6..eca42587e2a 100644 --- a/deploy/charts/buzz/templates/acceptance-cronjob.yaml +++ b/deploy/charts/buzz/templates/acceptance-cronjob.yaml @@ -66,6 +66,12 @@ spec: - {{ $a.metricPrefix | quote }} - --tag - {{ printf "probe_revision:%s" (include "buzz.imageRevision" .) | quote }} + {{- with $a.connectAddr }} + # A flag, not an env var: a probe older than this option + # rejects the unknown flag instead of dialing the public URL. + - --connect-addr + - {{ . | quote }} + {{- end }} {{- range $a.tags }} - --tag - {{ . | quote }} @@ -77,9 +83,6 @@ spec: fieldRef: fieldPath: status.hostIP - { name: BUZZ_RELAY_URL, value: {{ default .Values.relayUrl $a.relayUrl | quote }} } - {{- with $a.connectAddr }} - - { name: BUZZ_ACCEPTANCE_CONNECT_ADDR, value: {{ . | quote }} } - {{- end }} {{- with $a.statsdAddr }} - { name: BUZZ_ACCEPTANCE_STATSD_ADDR, value: {{ . | quote }} } {{- end }} diff --git a/deploy/charts/buzz/tests/acceptance_test.yaml b/deploy/charts/buzz/tests/acceptance_test.yaml index f105d15811f..60d591adb07 100644 --- a/deploy/charts/buzz/tests/acceptance_test.yaml +++ b/deploy/charts/buzz/tests/acceptance_test.yaml @@ -172,6 +172,8 @@ tests: - example.acceptance - --tag - probe_revision:sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef + - --connect-addr + - relay.internal:80 - --tag - env:staging - --tag @@ -189,11 +191,11 @@ tests: content: name: BUZZ_RELAY_URL value: wss://probe.example.com - - contains: + - notContains: path: spec.jobTemplate.spec.template.spec.containers[0].env content: name: BUZZ_ACCEPTANCE_CONNECT_ADDR - value: relay.internal:80 + any: true - contains: path: spec.jobTemplate.spec.template.spec.containers[0].env content: