From 9f49216f8beb1af33a8f57d2c175de95033925ca Mon Sep 17 00:00:00 2001 From: Luke Tornquist Date: Fri, 20 Nov 2026 14:16:02 -0500 Subject: [PATCH] feat(test-client): add buzz-acceptance relay probe (#9767) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Summary Adds `buzz-acceptance`, a third binary in `buzz-test-client` (next to `buzz-loadgen`). One run checks the relay's core jobs once against one relay and exits. It is meant to run on a schedule (for example a Kubernetes CronJob) or as a deployment step (for example an Argo Rollouts `job` analysis against the canary Service). Checks, in order: | Check | Stages | |---|---| | `relay_info` | `nip11` (the response must be a NIP-11 document) | | `connect_auth` | `ws_connect`, `nip42_auth` | | `channel_create` | `create` (a private, per-run channel with a 1 h TTL) | | `publish` | `ok` | | `fanout` | `connect_second`, `subscribe`, `publish`, `receive` | | `history` | `req_eose` (the published event is in a fresh REQ, intact) | | `access_control` | `unauthenticated_rejected`, `pubkey_mismatch_rejected` | | `cleanup` | `connect`, `delete_channel` (on a fresh connection) | `access_control` passes only on the relay's own denial reasons: `auth-required:` for a write on a socket that sent the NIP-FI assertion but skipped NIP-42 AUTH, and `invalid: event pubkey does not match authenticated identity` for a write signed by another key. A closed socket or any other reason fails the stage. `fanout` reads the listener while the publish waits for its OK, so `receive` measures delivery (publish → arrival on the second socket), not the publisher's acknowledgement. `fanout` and `history` verify the event they get back (`Event::verify`: id and signature against its content). An event the relay corrupted under its original id fails the stage. A channel is never stranded on purpose. If the create times out or the socket drops, the probe keeps the channel id and `cleanup` deletes it over a fresh connection. A failed cleanup names the channel. The TTL archives any channel a killed run leaves behind. Output: - A JSON report on stdout: each check's result, the stage that failed, and each completed stage's duration. - Optional DogStatsD metrics (`--statsd-addr`): `.runs`, `.run.seconds`, `.check.runs{check,result,stage}`, `.check.seconds{check,result}`, `.stage.seconds{check,stage}`. Every series also carries `relay_version` (from NIP-11) and any `--tag k:v`. - Exit code 0 when every check passed, 1 when a check failed, 2 when the probe could not run or send its metrics. A check whose prerequisite failed is reported as `skipped`, so each failure is counted once, at its cause, and every run reports the same set of checks. ### NIP-FI On a relay that enforces NIP-FI, pass `--assertion-file` (a regular file, at most 16 KiB; a FIFO or larger file fails the connection at once). The probe reads the file before every connection and sends it as `Nostr-Federated-Identity: Bearer …`. Another process (for example a sidecar) keeps it fresh. How the assertion is minted is deployment configuration and stays out of this repo. ## What got simpler Nothing got simpler. This adds one binary. It reuses `buzz-ws-client` and the crate's existing dependencies, and adds no new crate and no new dependency (`clap` gains its `env` feature). ## Testing - Unit tests drive the probe against a scripted relay: a publisher OK that arrives 600 ms after delivery (`receive` stays under 300 ms), a refusal with the wrong reason and a closed socket (both fail `access_control`), an unanswered create and a socket lost after create (both still delete that exact channel), and a failed cleanup (the error names the channel). Also: metric lines and tags, one datagram per line, stage timeout, assertion file limits, and an unreachable relay. - `tests/e2e_acceptance.rs` runs in CI's Relay E2E lane against a live relay. It runs the shared runner and the binary itself: exit 0 with JSON and datagrams on a pass, exit 1 when a check fails, exit 2 when the probe cannot run. ## Follow-ups (not in this PR) - Image and CronJob / Rollouts wiring. - Before the probe can gate a canary: a dial override that keeps the canonical Host and signed relay URL (like `buzz-loadgen`'s `connect_addr`). - Before it can gate a promotion: a build identifier from the relay. `relay_version` is the Cargo package version, which several image builds can share. - Confirm the delete took effect: read the channel back after `delete_channel` returns `OK true`. This needs a stable relay read contract for deleted channels. Until then the 1 h TTL bounds any channel a silent delete failure leaves behind. The scheduled deployment can also sweep stale probe channels at start. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Signed-off-by: Elrond <28d6302a099e5225b02c4155ac4236e4912603df2ab08dbfc2f4fef08ce598c8@buzz.block.builderlab.xyz> Signed-off-by: Luke Tornquist Co-authored-by: Elrond <28d6302a099e5225b02c4155ac4236e4912603df2ab08dbfc2f4fef08ce598c8@buzz.block.builderlab.xyz> Co-authored-by: Claude Opus 5.5 --- .github/workflows/_ci-relay.yml | 2 +- Justfile | 7 +- crates/buzz-test-client/Cargo.toml | 6 +- .../src/acceptance/fake_relay.rs | 193 +++ .../src/acceptance/metrics.rs | 213 ++++ crates/buzz-test-client/src/acceptance/mod.rs | 1037 +++++++++++++++++ crates/buzz-test-client/src/bin/acceptance.rs | 126 ++ crates/buzz-test-client/src/lib.rs | 3 + .../buzz-test-client/tests/e2e_acceptance.rs | 159 +++ scripts/run-tests.sh | 7 +- 10 files changed, 1745 insertions(+), 8 deletions(-) create mode 100644 crates/buzz-test-client/src/acceptance/fake_relay.rs create mode 100644 crates/buzz-test-client/src/acceptance/metrics.rs create mode 100644 crates/buzz-test-client/src/acceptance/mod.rs create mode 100644 crates/buzz-test-client/src/bin/acceptance.rs create mode 100644 crates/buzz-test-client/tests/e2e_acceptance.rs diff --git a/.github/workflows/_ci-relay.yml b/.github/workflows/_ci-relay.yml index cbe5cd4882..7d62a2044b 100644 --- a/.github/workflows/_ci-relay.yml +++ b/.github/workflows/_ci-relay.yml @@ -692,7 +692,7 @@ jobs: ./scripts/start-relay-for-tests.sh --no-build - name: Relay E2E tests run: | - cargo test -p buzz-test-client --test e2e_persona --test e2e_team_catalog --test e2e_nostr_interop --test e2e_thread_roots --test e2e_project -- --ignored --nocapture + cargo test -p buzz-test-client --test e2e_persona --test e2e_team_catalog --test e2e_nostr_interop --test e2e_thread_roots --test e2e_project --test e2e_acceptance -- --ignored --nocapture cargo test -p buzz-test-client --test e2e_relay invite -- --ignored --nocapture cargo test -p buzz-test-client --test e2e_relay nip43_membership_snapshots_are_rejected -- --ignored --nocapture cargo test -p buzz-test-client --test e2e_relay nip_ia_archive_snapshots_are_rejected -- --ignored --nocapture diff --git a/Justfile b/Justfile index 410d47d862..e5e441bd8d 100644 --- a/Justfile +++ b/Justfile @@ -679,9 +679,10 @@ test-unit: # relay events and agent prompts. They are infra-free; ignored lifecycle # tests remain excluded and run in their dedicated integration lanes. cargo nextest run -p buzz-acp --lib - # Load generator scenario, identity, shard and stats unit tests; all - # infra-free. Keep scripts/run-tests.sh in step. - cargo nextest run -p buzz-test-client --lib -E 'test(/^loadgen::/)' + # Load generator and acceptance probe unit tests; all infra-free (the + # probe's run against a scripted in-process relay). Keep + # scripts/run-tests.sh in step. + cargo nextest run -p buzz-test-client --lib -E 'test(/^(loadgen|acceptance)::/)' else ./scripts/run-tests.sh unit fi diff --git a/crates/buzz-test-client/Cargo.toml b/crates/buzz-test-client/Cargo.toml index 53cad25efa..70a2765007 100644 --- a/crates/buzz-test-client/Cargo.toml +++ b/crates/buzz-test-client/Cargo.toml @@ -24,7 +24,7 @@ uuid = { workspace = true } url = { workspace = true } rustls = "0.23" base64 = { workspace = true } -clap = { version = "4", features = ["derive"] } +clap = { version = "4", features = ["derive", "env"] } hex = { workspace = true } reqwest = { workspace = true } sha2 = { workspace = true } @@ -53,3 +53,7 @@ path = "src/main.rs" [[bin]] name = "buzz-loadgen" path = "src/bin/loadgen.rs" + +[[bin]] +name = "buzz-acceptance" +path = "src/bin/acceptance.rs" diff --git a/crates/buzz-test-client/src/acceptance/fake_relay.rs b/crates/buzz-test-client/src/acceptance/fake_relay.rs new file mode 100644 index 0000000000..d42e00353e --- /dev/null +++ b/crates/buzz-test-client/src/acceptance/fake_relay.rs @@ -0,0 +1,193 @@ +//! A scripted relay for the probe's tests: just enough NIP-01 and NIP-42 to +//! run every check, with knobs to delay, drop or close on chosen writes, +//! or to corrupt the events it serves. + +use std::collections::{HashMap, HashSet}; +use std::sync::{Arc, Mutex}; +use std::time::Duration; + +use futures_util::{SinkExt, StreamExt}; +use nostr::{Event, PublicKey}; +use serde_json::{json, Value}; +use tokio::net::TcpListener; +use tokio::sync::mpsc; +use tokio_tungstenite::tungstenite::Message; + +use super::{AUTH_REQUIRED, PUBKEY_MISMATCH}; + +/// How the relay answers a write on a connection that skipped AUTH. +pub enum Unauthenticated { + /// `OK false` with this reason. + Reason(String), + /// Close the socket without answering. + Close, +} + +/// What the relay does differently from accepting every write at once. +pub struct Script { + /// Wait this long before the OK for these kinds. + pub ack_delay: HashMap, + /// Never answer writes of these kinds (they are still stored). + pub no_ack: HashSet, + /// Accept writes of these kinds, then close the socket. + pub close_after: HashSet, + /// The answer to a write without AUTH. + pub unauthenticated: Unauthenticated, + /// Serve events of these kinds, stored and live, with altered content + /// under their original id and signature. + pub corrupt: HashSet, +} + +impl Default for Script { + fn default() -> Self { + Self { + ack_delay: HashMap::new(), + no_ack: HashSet::new(), + close_after: HashSet::new(), + unauthenticated: Unauthenticated::Reason(format!("{AUTH_REQUIRED} not authenticated")), + corrupt: HashSet::new(), + } + } +} + +type Outbox = mpsc::UnboundedSender; + +impl Script { + /// `event` as the relay serves it. + fn served(&self, event: &Event) -> Value { + let mut value = json!(event); + if self.corrupt.contains(&event.kind.as_u16()) { + value["content"] = json!(format!("{} (corrupted)", event.content)); + } + value + } +} + +struct Shared { + script: Script, + /// Every event written to the relay, accepted or not, in order. + events: Mutex>, + /// Live subscriptions: subscription id and the connection to send to. + live: Mutex>, +} + +/// A running scripted relay. +pub struct FakeRelay { + /// Its `ws://` URL. + pub url: String, + shared: Arc, +} + +impl FakeRelay { + /// Every event written so far, in order. + pub fn events(&self) -> Vec { + self.shared.events.lock().unwrap().clone() + } +} + +/// Starts a relay that follows `script` on a free local port. +pub async fn start(script: Script) -> FakeRelay { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = format!("ws://{}", listener.local_addr().unwrap()); + let shared = Arc::new(Shared { + script, + events: Mutex::new(Vec::new()), + live: Mutex::new(Vec::new()), + }); + let accept = shared.clone(); + tokio::spawn(async move { + while let Ok((tcp, _)) = listener.accept().await { + tokio::spawn(serve(tcp, accept.clone())); + } + }); + FakeRelay { url, shared } +} + +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 { + return; + }; + let (mut sink, mut stream) = ws.split(); + let (out, mut outbox) = mpsc::unbounded_channel::(); + let writer = tokio::spawn(async move { + while let Some(text) = outbox.recv().await { + if sink.send(Message::Text(text.into())).await.is_err() { + break; + } + } + }); + let send = |out: &Outbox, value: Value| { + let _ = out.send(value.to_string()); + }; + send(&out, json!(["AUTH", "challenge"])); + + let mut authed: Option = None; + while let Some(Ok(frame)) = stream.next().await { + let Message::Text(text) = frame else { continue }; + let Ok(Value::Array(msg)) = serde_json::from_str::(&text) else { + continue; + }; + match msg.first().and_then(Value::as_str) { + Some("AUTH") => { + let event: Event = serde_json::from_value(msg[1].clone()).unwrap(); + authed = Some(event.pubkey); + send(&out, json!(["OK", event.id.to_hex(), true, ""])); + } + Some("REQ") => { + let sub = msg[1].as_str().unwrap().to_string(); + let filter = &msg[2]; + if let Some(ids) = filter["ids"].as_array() { + let stored = shared.events.lock().unwrap().clone(); + for event in stored { + if ids.contains(&json!(event.id.to_hex())) { + send(&out, json!(["EVENT", sub, shared.script.served(&event)])); + } + } + } + if filter["limit"] == json!(0) { + shared.live.lock().unwrap().push((sub.clone(), out.clone())); + } + send(&out, json!(["EOSE", sub])); + } + Some("EVENT") => { + let event: Event = serde_json::from_value(msg[1].clone()).unwrap(); + shared.events.lock().unwrap().push(event.clone()); + let id = event.id.to_hex(); + let Some(pubkey) = authed else { + match &shared.script.unauthenticated { + Unauthenticated::Reason(reason) => { + send(&out, json!(["OK", id, false, reason])) + } + Unauthenticated::Close => break, + } + continue; + }; + if event.pubkey != pubkey { + send(&out, json!(["OK", id, false, PUBKEY_MISMATCH])); + continue; + } + let kind = event.kind.as_u16(); + if kind == super::KIND_MESSAGE { + let served = shared.script.served(&event); + for (sub, to) in shared.live.lock().unwrap().iter() { + send(to, json!(["EVENT", sub, served])); + } + } + if shared.script.no_ack.contains(&kind) { + continue; + } + if let Some(delay) = shared.script.ack_delay.get(&kind) { + tokio::time::sleep(*delay).await; + } + send(&out, json!(["OK", id, true, ""])); + if shared.script.close_after.contains(&kind) { + break; + } + } + _ => {} + } + } + drop(out); + let _ = writer.await; +} diff --git a/crates/buzz-test-client/src/acceptance/metrics.rs b/crates/buzz-test-client/src/acceptance/metrics.rs new file mode 100644 index 0000000000..7eebc6967c --- /dev/null +++ b/crates/buzz-test-client/src/acceptance/metrics.rs @@ -0,0 +1,213 @@ +//! DogStatsD lines for an acceptance [`Report`], sent over UDP. +//! +//! The format is the plain StatsD text protocol with the DogStatsD tag +//! extension (`name:value|type|#k:v,k:v`). Each line goes in its own datagram, +//! so no packet can exceed a path MTU however many tags an operator adds. + +use std::net::SocketAddr; + +use super::{Outcome, Report}; + +/// Every line for `report`: one run count and duration, then per check a run +/// count (tagged with its result and the stage that failed, or `none`), its +/// duration, and the duration of each stage it completed. +/// +/// `tags` are added to every line, after `relay_version` when the relay +/// reported one. Skipped checks are counted but carry no duration. +pub fn lines(prefix: &str, report: &Report, tags: &[String]) -> Vec { + let mut common: Vec = Vec::new(); + if let Some(version) = &report.relay_version { + common.push(format!("relay_version:{}", tag_value(version))); + } + common.extend(tags.iter().map(|t| tag_value(t))); + + let line = |name: &str, value: String, kind: &str, own: &[String]| { + let all: Vec<&str> = own + .iter() + .chain(common.iter()) + .map(String::as_str) + .collect(); + format!("{prefix}.{name}:{value}|{kind}|#{}", all.join(",")) + }; + + let run_result = if report.passed { + Outcome::Success + } else { + Outcome::Failure + }; + let mut out = vec![ + line( + "runs", + "1".into(), + "c", + &[format!("result:{}", run_result.as_str())], + ), + line( + "run.seconds", + seconds(report.seconds), + "d", + &[format!("result:{}", run_result.as_str())], + ), + ]; + for check in &report.checks { + let result = format!("result:{}", check.result.as_str()); + let name = format!("check:{}", check.check); + let stage = format!("stage:{}", check.failed_stage.unwrap_or("none")); + out.push(line( + "check.runs", + "1".into(), + "c", + &[name.clone(), result.clone(), stage], + )); + if check.result == Outcome::Skipped { + continue; + } + out.push(line( + "check.seconds", + seconds(check.seconds), + "d", + &[name.clone(), result], + )); + for timing in &check.stages { + out.push(line( + "stage.seconds", + seconds(timing.seconds), + "d", + &[name.clone(), format!("stage:{}", timing.stage)], + )); + } + } + out +} + +/// Sends each of `lines` to `addr` as its own UDP datagram. +/// +/// Fails on the first datagram the socket refuses, so a misconfigured agent +/// address is an error for the caller rather than a run with no metrics. +pub async fn send(addr: SocketAddr, lines: &[String]) -> std::io::Result<()> { + let bind: SocketAddr = if addr.is_ipv4() { + ([0, 0, 0, 0], 0).into() + } else { + ([0u16; 8], 0).into() + }; + let socket = tokio::net::UdpSocket::bind(bind).await?; + for line in lines { + socket.send_to(line.as_bytes(), addr).await?; + } + Ok(()) +} + +/// Seconds with millisecond precision; StatsD values are plain decimals. +fn seconds(s: f64) -> String { + format!("{s:.3}") +} + +/// `value` with the characters that end a DogStatsD tag or line replaced. +fn tag_value(value: &str) -> String { + value + .chars() + .map(|c| match c { + ',' | '|' | '#' | '\n' | '\r' | ' ' => '_', + c => c, + }) + .collect() +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::acceptance::{CheckReport, StageTiming}; + + fn report() -> Report { + Report { + relay_url: "wss://relay.example".into(), + relay_version: Some("1.2.3".into()), + passed: false, + seconds: 1.5, + checks: vec![ + CheckReport { + check: "publish", + result: Outcome::Success, + failed_stage: None, + error: None, + seconds: 0.25, + stages: vec![StageTiming { + stage: "ok", + seconds: 0.25, + }], + }, + CheckReport { + check: "fanout", + result: Outcome::Failure, + failed_stage: Some("receive"), + error: Some("timed out after 10s".into()), + seconds: 10.0, + stages: vec![StageTiming { + stage: "subscribe", + seconds: 0.004, + }], + }, + CheckReport { + check: "history", + result: Outcome::Skipped, + failed_stage: None, + error: Some("publish failed".into()), + seconds: 0.0, + stages: vec![], + }, + ], + } + } + + #[test] + fn lines_tag_every_series_and_skip_durations_for_skipped_checks() { + let tags = vec!["env:staging".to_string(), "target:a,b|c".to_string()]; + let got = lines("buzz.acceptance", &report(), &tags); + let common = "relay_version:1.2.3,env:staging,target:a_b_c"; + let want = vec![ + format!("buzz.acceptance.runs:1|c|#result:failure,{common}"), + format!("buzz.acceptance.run.seconds:1.500|d|#result:failure,{common}"), + format!( + "buzz.acceptance.check.runs:1|c|#check:publish,result:success,stage:none,{common}" + ), + format!("buzz.acceptance.check.seconds:0.250|d|#check:publish,result:success,{common}"), + format!("buzz.acceptance.stage.seconds:0.250|d|#check:publish,stage:ok,{common}"), + format!( + "buzz.acceptance.check.runs:1|c|#check:fanout,result:failure,stage:receive,{common}" + ), + format!("buzz.acceptance.check.seconds:10.000|d|#check:fanout,result:failure,{common}"), + format!("buzz.acceptance.stage.seconds:0.004|d|#check:fanout,stage:subscribe,{common}"), + format!( + "buzz.acceptance.check.runs:1|c|#check:history,result:skipped,stage:none,{common}" + ), + ]; + assert_eq!(got, want); + } + + #[test] + fn lines_without_relay_version_or_tags_still_tag_check_and_result() { + let mut r = report(); + r.relay_version = None; + r.passed = true; + r.checks.truncate(1); + let got = lines("p", &r, &[]); + assert_eq!(got[0], "p.runs:1|c|#result:success"); + assert_eq!( + got[2], + "p.check.runs:1|c|#check:publish,result:success,stage:none" + ); + } + + #[tokio::test] + async fn send_puts_each_line_in_its_own_datagram() { + let agent = tokio::net::UdpSocket::bind("127.0.0.1:0").await.unwrap(); + let addr = agent.local_addr().unwrap(); + let sent = vec!["a.b:1|c|#x:y".to_string(), "a.c:2|d|#x:y".to_string()]; + send(addr, &sent).await.unwrap(); + let mut buf = [0u8; 512]; + for want in &sent { + let n = agent.recv(&mut buf).await.unwrap(); + assert_eq!(std::str::from_utf8(&buf[..n]).unwrap(), want); + } + } +} diff --git a/crates/buzz-test-client/src/acceptance/mod.rs b/crates/buzz-test-client/src/acceptance/mod.rs new file mode 100644 index 0000000000..a9913434ea --- /dev/null +++ b/crates/buzz-test-client/src/acceptance/mod.rs @@ -0,0 +1,1037 @@ +//! Relay acceptance probe behind the `buzz-acceptance` binary. +//! +//! One run checks the relay's core jobs once, against one relay, and reports +//! each job (a "check") with its result, the stage where it failed, and how +//! long each stage took. It is meant to run on a schedule or as a deployment +//! step, and to exit non-zero when any check fails. +//! +//! Every run creates its own private channel, writes only there, and deletes +//! it at the end. A check that needs an earlier check's result is reported as +//! skipped when that check failed, so each failure is counted once, at its +//! cause, and every run reports the same set of checks. + +#[cfg(test)] +mod fake_relay; +pub mod metrics; + +use std::future::Future; +use std::io::Read; +use std::path::PathBuf; +use std::time::{Duration, Instant}; + +use anyhow::{anyhow, bail, Context}; +use buzz_ws_client::{HeaderMap, HeaderValue, NostrWsConnection, RelayMessage, WsClientError}; +use nostr::{ + Alphabet, Event, EventBuilder, EventId, Filter, Keys, Kind, SingleLetterTag, Tag, Timestamp, +}; +use serde::Serialize; +use serde_json::json; + +/// Request header carrying a NIP-FI assertion (`docs/nips/NIP-FI.md`). +const FEDERATED_IDENTITY_HEADER: &str = "Nostr-Federated-Identity"; + +/// Kind of the probe's channel messages (NIP-29 chat message). +const KIND_MESSAGE: u16 = 9; +/// NIP-29 group create and delete kinds. +const KIND_CREATE_GROUP: u16 = 9007; +const KIND_DELETE_GROUP: u16 = 9008; +/// Seconds of inactivity after which the relay archives a probe channel. A +/// backstop for runs that end before `cleanup` can delete their channel. +const CHANNEL_TTL_SECS: &str = "3600"; +/// Largest assertion file the probe reads. +const MAX_ASSERTION_BYTES: u64 = 16 * 1024; + +/// Every check, in the order a run reports them. +pub const CHECKS: [&str; 8] = [ + "relay_info", + "connect_auth", + "channel_create", + "publish", + "fanout", + "history", + "access_control", + "cleanup", +]; + +/// What one run needs. +pub struct Config { + /// The relay's WebSocket URL (`wss://…` or `ws://…`). + pub relay_url: 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 + /// every connection, so another process can keep it fresh. + pub assertion_file: Option, + /// The longest any one stage may take. + pub stage_timeout: Duration, +} + +/// The outcome of one run. +#[derive(Debug, Serialize)] +pub struct Report { + /// The relay the run checked. + pub relay_url: String, + /// The relay's NIP-11 `version`, when it reported one. + pub relay_version: Option, + /// True when no check failed. + pub passed: bool, + /// How long the whole run took. + pub seconds: f64, + /// One entry per name in [`CHECKS`], in that order. + pub checks: Vec, +} + +/// The outcome of one check. +#[derive(Debug, Serialize)] +pub struct CheckReport { + /// The check's name, one of [`CHECKS`]. + pub check: &'static str, + /// Whether it passed, failed or was skipped. + pub result: Outcome, + /// The stage that failed, for a failure. + pub failed_stage: Option<&'static str>, + /// Why it failed or was skipped. + pub error: Option, + /// How long the check took, failed stage included. + pub seconds: f64, + /// Each stage the check completed, with its duration. + pub stages: Vec, +} + +/// One completed stage and how long it took. +#[derive(Debug, Serialize)] +pub struct StageTiming { + /// The stage's name. + pub stage: &'static str, + /// How long it took. + pub seconds: f64, +} + +/// The result of one check. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +#[serde(rename_all = "lowercase")] +pub enum Outcome { + /// Every stage passed. + Success, + /// A stage failed or timed out. + Failure, + /// Not run, because a check it depends on failed. + Skipped, +} + +impl Outcome { + /// The lowercase name used in reports and metric tags. + pub fn as_str(self) -> &'static str { + match self { + Outcome::Success => "success", + Outcome::Failure => "failure", + Outcome::Skipped => "skipped", + } + } +} + +/// A stage that failed: its name and why. +struct StageError { + stage: &'static str, + error: String, +} + +/// One check in progress: times its stages and bounds each by the timeout. +struct Check { + name: &'static str, + started: Instant, + timeout: Duration, + stages: Vec, +} + +impl Check { + fn new(name: &'static str, timeout: Duration) -> Self { + Self { + name, + started: Instant::now(), + timeout, + stages: Vec::new(), + } + } + + /// Runs `work` as `stage`, recording its duration when it succeeds. + async fn stage( + &mut self, + stage: &'static str, + work: impl Future>, + ) -> Result { + let started = Instant::now(); + let result = match tokio::time::timeout(self.timeout, work).await { + Ok(Ok(value)) => Ok(value), + Ok(Err(e)) => Err(format!("{e:#}")), + Err(_) => Err(format!("timed out after {:?}", self.timeout)), + }; + match result { + Ok(value) => { + self.stages.push(StageTiming { + stage, + seconds: started.elapsed().as_secs_f64(), + }); + Ok(value) + } + Err(error) => Err(StageError { stage, error }), + } + } + + fn finish(self, result: Result<(), StageError>) -> CheckReport { + let (outcome, failed_stage, error) = match result { + Ok(()) => (Outcome::Success, None, None), + Err(e) => (Outcome::Failure, Some(e.stage), Some(e.error)), + }; + CheckReport { + check: self.name, + result: outcome, + failed_stage, + error, + seconds: self.started.elapsed().as_secs_f64(), + stages: self.stages, + } + } +} + +fn skipped(check: &'static str, because: &str) -> CheckReport { + CheckReport { + check, + result: Outcome::Skipped, + failed_stage: None, + error: Some(format!("skipped: {because} failed")), + seconds: 0.0, + stages: Vec::new(), + } +} + +/// Runs every check in [`CHECKS`] once against `cfg.relay_url`. +pub async fn run(cfg: &Config) -> Report { + let started = Instant::now(); + let mut checks = Vec::with_capacity(CHECKS.len()); + + let (report, relay_version) = relay_info(cfg).await; + checks.push(report); + + let (report, conn) = connect_auth(cfg).await; + checks.push(report); + match conn { + Some(mut conn) => { + let created = run_channel_checks(cfg, &mut conn, &mut checks).await; + // Closing is best effort: every check has already been recorded. + let _ = conn.disconnect().await; + checks.push(match created { + Some(channel) => cleanup(cfg, &channel).await, + None => skipped("cleanup", "channel_create"), + }); + } + None => { + for &check in &CHECKS[2..] { + checks.push(skipped(check, "connect_auth")); + } + } + } + + Report { + relay_url: cfg.relay_url.clone(), + relay_version, + passed: checks.iter().all(|c| c.result != Outcome::Failure), + seconds: started.elapsed().as_secs_f64(), + checks, + } +} + +/// The checks that need the authenticated connection `conn`, `cleanup` +/// excepted. Returns the channel `cleanup` must delete: one the relay +/// accepted, or one whose create may have committed without an answer. +async fn run_channel_checks( + cfg: &Config, + conn: &mut NostrWsConnection, + checks: &mut Vec, +) -> Option { + let (report, created) = channel_create(cfg, conn).await; + let passed = report.result == Outcome::Success; + checks.push(report); + if !passed { + for &check in &CHECKS[3..CHECKS.len() - 1] { + checks.push(skipped(check, "channel_create")); + } + return created; + } + let channel = created?; + + let (report, published) = publish(cfg, conn, &channel).await; + checks.push(report); + checks.push(fanout(cfg, conn, &channel).await); + checks.push(match published { + Some(id) => history(cfg, conn, &channel, id).await, + None => skipped("history", "publish"), + }); + checks.push(access_control(cfg, conn, &channel).await); + Some(channel) +} + +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) + .header("Accept", "application/nostr+json") + .send() + .await? + .error_for_status()?; + let info: serde_json::Value = response.json().await?; + if !info["supported_nips"].is_array() { + bail!("not a NIP-11 document: no supported_nips"); + } + Ok(info["version"].as_str().map(str::to_owned)) + }) + .await; + match result { + Ok(version) => (check.finish(Ok(())), version), + Err(e) => (check.finish(Err(e)), None), + } +} + +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?; + check + .stage("nip42_auth", async { + Ok(conn.authenticate(&cfg.keys, None).await?) + }) + .await?; + Ok(conn) + } + .await; + match result { + Ok(conn) => (check.finish(Ok(())), Some(conn)), + Err(e) => (check.finish(Err(e)), None), + } +} + +/// Creates the run's private channel, with a TTL as a backstop. Returns the +/// channel unless the relay refused it: after a timeout or a lost connection +/// the create may still have committed, so `cleanup` must try to delete it. +async fn channel_create( + cfg: &Config, + conn: &mut NostrWsConnection, +) -> (CheckReport, Option) { + let mut check = Check::new("channel_create", cfg.stage_timeout); + let channel = uuid::Uuid::new_v4().to_string(); + let mut refused = false; + let result = check + .stage("create", async { + let event = EventBuilder::new(Kind::Custom(KIND_CREATE_GROUP), "") + .tags([ + tag(["h", &channel])?, + tag(["name", &format!("acceptance-{channel}")])?, + tag(["channel_type", "stream"])?, + tag(["visibility", "private"])?, + tag(["ttl", CHANNEL_TTL_SECS])?, + ]) + .sign_with_keys(&cfg.keys)?; + let ok = conn.send_event(event).await?; + if !ok.accepted { + refused = true; + bail!("relay rejected the event: {}", ok.message); + } + Ok(()) + }) + .await; + let report = check.finish(result); + (report, (!refused).then_some(channel)) +} + +async fn publish( + cfg: &Config, + conn: &mut NostrWsConnection, + channel: &str, +) -> (CheckReport, Option) { + let mut check = Check::new("publish", cfg.stage_timeout); + let result = check + .stage("ok", async { + let event = message(&cfg.keys, channel, "acceptance publish")?; + let id = event.id; + accepted(conn, event).await?; + Ok(id) + }) + .await; + match result { + Ok(id) => (check.finish(Ok(())), Some(id)), + Err(e) => (check.finish(Err(e)), None), + } +} + +/// A second connection subscribes to the channel; the first publishes; the +/// second must receive it intact. `receive` is timed from the publish to the moment +/// the event arrived on the second socket. +async fn fanout(cfg: &Config, conn: &mut NostrWsConnection, channel: &str) -> CheckReport { + let mut check = Check::new("fanout", cfg.stage_timeout); + 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?) + }) + .await?; + let result = fanout_on(&mut check, cfg, conn, &mut listener, channel).await; + let _ = listener.disconnect().await; + result + } + .await; + check.finish(result) +} + +async fn fanout_on( + check: &mut Check, + cfg: &Config, + conn: &mut NostrWsConnection, + listener: &mut NostrWsConnection, + channel: &str, +) -> Result<(), StageError> { + let timeout = cfg.stage_timeout; + check + .stage("subscribe", async { + let live = channel_filter(channel).since(Timestamp::now()).limit(0); + listener.send_raw(&json!(["REQ", "fanout", live])).await?; + wait_for_eose(listener, "fanout", timeout).await + }) + .await?; + let event = message(&cfg.keys, channel, "acceptance fanout").map_err(|e| StageError { + stage: "publish", + error: format!("{e:#}"), + })?; + let id = event.id; + // Read the listener while the publish waits for its OK, so `receive` + // measures delivery, not the publisher's acknowledgement. + let sent_at = Instant::now(); + let arrived = async { + loop { + match listener.next_event_received(timeout).await? { + ( + at, + RelayMessage::Event { + subscription_id, + event, + }, + ) if subscription_id == "fanout" && event.id == id => { + intact(&event)?; + return Ok(at); + } + ( + _, + RelayMessage::Closed { + subscription_id, + message, + }, + ) if subscription_id == "fanout" => { + bail!("subscription closed: {message}") + } + _ => {} + } + } + }; + let (published, arrived) = tokio::join!( + check.stage("publish", accepted(conn, event)), + tokio::time::timeout(timeout, arrived) + ); + published?; + match arrived { + Ok(Ok(at)) => { + check.stages.push(StageTiming { + stage: "receive", + seconds: at.saturating_duration_since(sent_at).as_secs_f64(), + }); + Ok(()) + } + Ok(Err(e)) => Err(StageError { + stage: "receive", + error: format!("{e:#}"), + }), + Err(_) => Err(StageError { + stage: "receive", + error: format!("timed out after {timeout:?}"), + }), + } +} + +/// A fresh REQ for the channel must return the event `publish` stored, +/// intact. +async fn history( + cfg: &Config, + conn: &mut NostrWsConnection, + channel: &str, + id: EventId, +) -> CheckReport { + let mut check = Check::new("history", cfg.stage_timeout); + let timeout = cfg.stage_timeout; + let result = check + .stage("req_eose", async { + let filter = channel_filter(channel).id(id); + conn.send_raw(&json!(["REQ", "history", filter])).await?; + let mut found = false; + loop { + match conn.next_event(timeout).await? { + RelayMessage::Event { + subscription_id, + event, + } if subscription_id == "history" && event.id == id => { + intact(&event)?; + found = true; + } + RelayMessage::Eose { subscription_id } if subscription_id == "history" => break, + RelayMessage::Closed { + subscription_id, + message, + } if subscription_id == "history" => { + bail!("subscription closed: {message}") + } + _ => {} + } + } + conn.send_raw(&json!(["CLOSE", "history"])).await?; + if !found { + bail!("stored event {id} missing from history"); + } + Ok(()) + }) + .await; + check.finish(result) +} + +/// Denial reason (NIP-01 prefix) for a write on a connection without NIP-42 AUTH. +const AUTH_REQUIRED: &str = "auth-required:"; +/// Denial reason for a write signed by a key other than the authenticated one. +const PUBKEY_MISMATCH: &str = "invalid: event pubkey does not match authenticated identity"; + +/// The relay must refuse, with the matching reason, a write on a connection +/// that skipped NIP-42 AUTH, and a write signed by a key other than the one +/// the connection authenticated as. The unauthenticated connection still +/// sends the NIP-FI assertion, so only AUTH is missing. Any other answer, +/// including a closed socket or a different denial, fails the stage. +async fn access_control(cfg: &Config, conn: &mut NostrWsConnection, channel: &str) -> CheckReport { + let mut check = Check::new("access_control", cfg.stage_timeout); + let result = async { + 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 outcome = anon.send_event(event).await; + let _ = anon.disconnect().await; + denied(outcome, AUTH_REQUIRED) + }) + .await?; + check + .stage("pubkey_mismatch_rejected", async { + let event = message(&Keys::generate(), channel, "acceptance mismatch")?; + denied(conn.send_event(event).await, PUBKEY_MISMATCH) + }) + .await + } + .await; + check.finish(result) +} + +/// Deletes `channel` over a fresh connection, so a socket an earlier check +/// lost cannot strand it. A failure names the channel. +async fn cleanup(cfg: &Config, channel: &str) -> CheckReport { + let mut check = Check::new("cleanup", cfg.stage_timeout); + 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?) + }) + .await?; + let result = check + .stage("delete_channel", async { + let event = EventBuilder::new(Kind::Custom(KIND_DELETE_GROUP), "") + .tags([tag(["h", channel])?]) + .sign_with_keys(&cfg.keys)?; + accepted(&mut conn, event).await + }) + .await; + let _ = conn.disconnect().await; + result + } + .await + .map_err(|e| StageError { + stage: e.stage, + error: format!("channel {channel}: {}", e.error), + }); + check.finish(result) +} + +/// Sends `event` and fails unless the relay accepts it. +async fn accepted(conn: &mut NostrWsConnection, event: Event) -> anyhow::Result<()> { + let ok = conn.send_event(event).await?; + if !ok.accepted { + bail!("relay rejected the event: {}", ok.message); + } + Ok(()) +} + +/// Passes only when the relay answered `OK false` with a reason starting +/// with `expected`. No answer, a closed socket or another reason fails. +fn denied( + outcome: Result, + expected: &str, +) -> anyhow::Result<()> { + let ok = outcome.context("no OK for the write that should be refused")?; + if ok.accepted { + bail!("relay accepted the event"); + } + if !ok.message.starts_with(expected) { + bail!("relay refused for another reason: {}", ok.message); + } + Ok(()) +} + +async fn wait_for_eose( + conn: &mut NostrWsConnection, + sub_id: &str, + timeout: Duration, +) -> anyhow::Result<()> { + loop { + match conn.next_event(timeout).await? { + RelayMessage::Eose { subscription_id } if subscription_id == sub_id => return Ok(()), + RelayMessage::Closed { + subscription_id, + message, + } if subscription_id == sub_id => { + bail!("subscription closed: {message}") + } + _ => {} + } + } +} + +/// The WebSocket upgrade headers: the NIP-FI assertion, when configured. +fn upgrade_headers(cfg: &Config) -> anyhow::Result { + let mut headers = HeaderMap::new(); + if let Some(path) = &cfg.assertion_file { + let invalid = || { + anyhow!( + "assertion file {} must be a regular file of at most {MAX_ASSERTION_BYTES} bytes", + path.display() + ) + }; + let read = || -> std::io::Result> { + // Check before opening: opening a FIFO blocks until a writer + // appears, and no async timeout can interrupt that. + if !std::fs::metadata(path)?.is_file() { + return Ok(None); + } + let file = std::fs::File::open(path)?; + if !file.metadata()?.is_file() { + return Ok(None); + } + // Cap the read on the open file: it may grow after the check. + let mut assertion = String::new(); + file.take(MAX_ASSERTION_BYTES + 1) + .read_to_string(&mut assertion)?; + Ok((assertion.len() as u64 <= MAX_ASSERTION_BYTES).then_some(assertion)) + }; + let assertion = read() + .with_context(|| format!("read assertion file {}", path.display()))? + .ok_or_else(invalid)?; + let assertion = assertion.trim(); + if assertion.is_empty() { + bail!("assertion file {} is empty", path.display()); + } + let mut value = HeaderValue::from_str(&format!("Bearer {assertion}")) + .map_err(|_| anyhow!("assertion file {} is not a header value", path.display()))?; + value.set_sensitive(true); + headers.insert(FEDERATED_IDENTITY_HEADER, value); + } + Ok(headers) +} + +/// 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}"))?; + let scheme = match url.scheme() { + "wss" => "https", + "ws" => "http", + other => bail!("relay URL scheme must be ws or wss, not {other}"), + }; + url.set_scheme(scheme) + .map_err(|()| anyhow!("cannot use {scheme} for {ws_url}"))?; + Ok(url) +} + +/// Fails unless `event`'s id and signature match its content. A match on +/// the id field alone would pass an event the relay corrupted. +fn intact(event: &Event) -> anyhow::Result<()> { + event + .verify() + .with_context(|| format!("event {} failed verification", event.id)) +} + +fn channel_filter(channel: &str) -> Filter { + Filter::new() + .kind(Kind::Custom(KIND_MESSAGE)) + .custom_tag(SingleLetterTag::lowercase(Alphabet::H), channel) +} + +fn message(keys: &Keys, channel: &str, content: &str) -> anyhow::Result { + Ok(EventBuilder::new(Kind::Custom(KIND_MESSAGE), content) + .tags([tag(["h", channel])?]) + .sign_with_keys(keys)?) +} + +fn tag(parts: [&str; N]) -> anyhow::Result { + Ok(Tag::parse(parts)?) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn config(relay_url: String) -> Config { + Config { + relay_url, + keys: Keys::generate(), + assertion_file: None, + stage_timeout: Duration::from_secs(2), + } + } + + /// With nothing listening, the run fails at the cause (`relay_info` + /// and `connect_auth`), skips the checks that need a connection, and + /// still reports every check in order. + #[tokio::test] + async fn unreachable_relay_fails_at_the_cause_and_skips_dependents() { + let port = { + let socket = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + socket.local_addr().unwrap().port() + }; + let report = run(&config(format!("ws://127.0.0.1:{port}"))).await; + + assert!(!report.passed); + let names: Vec<&str> = report.checks.iter().map(|c| c.check).collect(); + assert_eq!(names, CHECKS); + let results: Vec<(&str, Outcome, Option<&str>)> = report + .checks + .iter() + .map(|c| (c.check, c.result, c.failed_stage)) + .collect(); + assert_eq!(results[0], ("relay_info", Outcome::Failure, Some("nip11"))); + assert_eq!( + results[1], + ("connect_auth", Outcome::Failure, Some("ws_connect")) + ); + for (name, outcome, stage) in &results[2..] { + assert_eq!((*outcome, *stage), (Outcome::Skipped, None), "{name}"); + } + } + + #[tokio::test] + async fn a_stage_that_overruns_the_timeout_fails_with_its_name() { + let mut check = Check::new("t", Duration::from_millis(20)); + check.stage("fast", async { Ok(()) }).await.ok().unwrap(); + let err = check + .stage("slow", async { + tokio::time::sleep(Duration::from_secs(5)).await; + Ok(()) + }) + .await + .err() + .unwrap(); + let report = check.finish(Err(err)); + assert_eq!(report.result, Outcome::Failure); + assert_eq!(report.failed_stage, Some("slow")); + assert!(report.error.unwrap().contains("timed out")); + let stages: Vec<&str> = report.stages.iter().map(|s| s.stage).collect(); + assert_eq!(stages, ["fast"]); + } + + #[test] + fn upgrade_headers_read_the_assertion_file_each_time() { + let dir = std::env::temp_dir().join(format!("acceptance-{}", uuid::Uuid::new_v4())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("assertion"); + let mut cfg = config("wss://relay.example".into()); + assert!(upgrade_headers(&cfg).unwrap().is_empty()); + + cfg.assertion_file = Some(path.clone()); + assert!(upgrade_headers(&cfg).is_err(), "missing file must fail"); + std::fs::write(&path, " \n").unwrap(); + assert!(upgrade_headers(&cfg).is_err(), "empty file must fail"); + + std::fs::write(&path, "first\n").unwrap(); + assert_eq!( + upgrade_headers(&cfg).unwrap()[FEDERATED_IDENTITY_HEADER], + "Bearer first" + ); + std::fs::write(&path, "second").unwrap(); + assert_eq!( + upgrade_headers(&cfg).unwrap()[FEDERATED_IDENTITY_HEADER], + "Bearer second" + ); + + std::fs::write(&path, "x".repeat(MAX_ASSERTION_BYTES as usize + 1)).unwrap(); + assert!(upgrade_headers(&cfg).is_err(), "oversized file must fail"); + cfg.assertion_file = Some(dir.clone()); + assert!(upgrade_headers(&cfg).is_err(), "a directory must fail"); + + // A FIFO with no writer must fail at once, not block the open. + #[cfg(unix)] + { + let fifo = dir.join("fifo"); + let made = std::process::Command::new("mkfifo") + .arg(&fifo) + .status() + .unwrap(); + assert!(made.success()); + let mut cfg = config("wss://relay.example".into()); + cfg.assertion_file = Some(fifo); + let (done, result) = std::sync::mpsc::channel(); + std::thread::spawn(move || done.send(upgrade_headers(&cfg).is_err()).unwrap()); + assert!( + result.recv_timeout(Duration::from_secs(5)).unwrap(), + "a FIFO must fail" + ); + } + std::fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn http_url_maps_websocket_schemes() { + assert_eq!( + http_url("wss://r.example/").unwrap().as_str(), + "https://r.example/" + ); + assert_eq!( + http_url("ws://127.0.0.1:3000").unwrap().as_str(), + "http://127.0.0.1:3000/" + ); + assert!(http_url("https://r.example").is_err()); + } + + #[test] + fn denied_passes_only_on_the_expected_refusal() { + let ok = |accepted, message: &str| { + Ok(buzz_ws_client::OkResponse { + event_id: "e".into(), + accepted, + message: message.into(), + }) + }; + assert!(denied(ok(false, "auth-required: not authenticated"), AUTH_REQUIRED).is_ok()); + assert!(denied(ok(false, PUBKEY_MISMATCH), PUBKEY_MISMATCH).is_ok()); + assert!(denied(ok(false, "error: database unavailable"), AUTH_REQUIRED).is_err()); + assert!(denied(ok(false, "rate-limited: slow down"), PUBKEY_MISMATCH).is_err()); + assert!(denied(ok(true, ""), AUTH_REQUIRED).is_err()); + assert!(denied(Err(WsClientError::ConnectionClosed), AUTH_REQUIRED).is_err()); + assert!(denied(Err(WsClientError::Timeout), AUTH_REQUIRED).is_err()); + } + + fn check<'a>(report: &'a Report, name: &str) -> &'a CheckReport { + report.checks.iter().find(|c| c.check == name).unwrap() + } + + fn stage_seconds(check: &CheckReport, stage: &str) -> f64 { + check + .stages + .iter() + .find(|s| s.stage == stage) + .unwrap_or_else(|| panic!("no {stage} stage in {check:?}")) + .seconds + } + + /// The `h` tag of every event of `kind` the relay saw. + fn channels(relay: &fake_relay::FakeRelay, kind: u16) -> Vec { + relay + .events() + .iter() + .filter(|e| e.kind.as_u16() == kind) + .filter_map(|e| { + e.tags + .iter() + .find(|t| t.kind().to_string() == "h") + .and_then(|t| t.content().map(str::to_owned)) + }) + .collect() + } + + /// The scripted relay serves no NIP-11, so only `relay_info` fails. + fn assert_all_pass_but_relay_info(report: &Report) { + for c in &report.checks[1..] { + assert_eq!(c.result, Outcome::Success, "{c:?}"); + } + } + + /// The publisher's OK arrives 600 ms after the event reaches the + /// listener; `receive` must report delivery, not the OK wait. + #[tokio::test] + async fn fanout_receive_is_timed_from_delivery_not_the_publishers_ack() { + let relay = fake_relay::start(fake_relay::Script { + ack_delay: [(KIND_MESSAGE, Duration::from_millis(600))].into(), + ..Default::default() + }) + .await; + let report = run(&config(relay.url.clone())).await; + + assert_all_pass_but_relay_info(&report); + let fanout = check(&report, "fanout"); + assert!(stage_seconds(fanout, "publish") >= 0.6, "{fanout:?}"); + assert!(stage_seconds(fanout, "receive") < 0.3, "{fanout:?}"); + let channel = channels(&relay, KIND_CREATE_GROUP); + assert_eq!(channels(&relay, KIND_DELETE_GROUP), channel); + let create = relay + .events() + .into_iter() + .find(|e| e.kind.as_u16() == KIND_CREATE_GROUP); + let ttl = create + .unwrap() + .tags + .iter() + .find(|t| t.kind().to_string() == "ttl") + .cloned(); + assert_eq!( + ttl.and_then(|t| t.content().map(str::to_owned)).as_deref(), + Some(CHANNEL_TTL_SECS) + ); + } + + /// The relay serves the probe's messages with altered content under + /// their original id. `fanout` and `history` must fail, not pass on the + /// id alone. + #[tokio::test] + async fn a_corrupted_event_under_its_original_id_fails_fanout_and_history() { + let relay = fake_relay::start(fake_relay::Script { + corrupt: [KIND_MESSAGE].into(), + ..Default::default() + }) + .await; + let report = run(&config(relay.url.clone())).await; + + for (name, stage) in [("fanout", "receive"), ("history", "req_eose")] { + let c = check(&report, name); + assert_eq!((c.result, c.failed_stage), (Outcome::Failure, Some(stage))); + assert!( + c.error.as_deref().unwrap().contains("failed verification"), + "{c:?}" + ); + } + for name in ["channel_create", "publish", "access_control", "cleanup"] { + assert_eq!(check(&report, name).result, Outcome::Success, "{name}"); + } + } + + /// A refusal for another reason, or a closed socket, is not proof the + /// relay enforces NIP-42: `access_control` fails at that stage. + #[tokio::test] + async fn access_control_fails_unless_the_refusal_is_the_auth_denial() { + for unauthenticated in [ + fake_relay::Unauthenticated::Reason("error: database unavailable".into()), + fake_relay::Unauthenticated::Close, + ] { + let relay = fake_relay::start(fake_relay::Script { + unauthenticated, + ..Default::default() + }) + .await; + let report = run(&config(relay.url.clone())).await; + let access = check(&report, "access_control"); + assert_eq!(access.result, Outcome::Failure, "{access:?}"); + assert_eq!(access.failed_stage, Some("unauthenticated_rejected")); + assert_eq!(check(&report, "cleanup").result, Outcome::Success); + } + } + + /// The create's OK never comes, but the relay stored it: the run fails + /// at `channel_create`, skips what needed the channel, and still deletes + /// that exact channel. + #[tokio::test] + async fn an_unanswered_create_is_still_deleted() { + let relay = fake_relay::start(fake_relay::Script { + no_ack: [KIND_CREATE_GROUP].into(), + ..Default::default() + }) + .await; + let mut cfg = config(relay.url.clone()); + cfg.stage_timeout = Duration::from_millis(500); + let report = run(&cfg).await; + + let create = check(&report, "channel_create"); + assert_eq!( + (create.result, create.failed_stage), + (Outcome::Failure, Some("create")) + ); + for name in ["publish", "fanout", "history", "access_control"] { + assert_eq!(check(&report, name).result, Outcome::Skipped, "{name}"); + } + assert_eq!(check(&report, "cleanup").result, Outcome::Success); + let created = channels(&relay, KIND_CREATE_GROUP); + assert_eq!(created.len(), 1); + assert_eq!(channels(&relay, KIND_DELETE_GROUP), created); + } + + /// The relay closes the socket right after accepting the create. The + /// checks on that socket fail, and cleanup deletes the channel over a + /// fresh connection. + #[tokio::test] + async fn a_socket_lost_after_create_still_deletes_the_channel() { + let relay = fake_relay::start(fake_relay::Script { + close_after: [KIND_CREATE_GROUP].into(), + ..Default::default() + }) + .await; + let report = run(&config(relay.url.clone())).await; + + assert_eq!(check(&report, "channel_create").result, Outcome::Success); + assert_eq!(check(&report, "publish").result, Outcome::Failure); + assert_eq!(check(&report, "cleanup").result, Outcome::Success); + let created = channels(&relay, KIND_CREATE_GROUP); + assert_eq!(channels(&relay, KIND_DELETE_GROUP), created); + } + + /// A cleanup that fails names the channel it could not delete. + #[tokio::test] + async fn a_failed_cleanup_names_the_channel() { + let relay = fake_relay::start(fake_relay::Script { + no_ack: [KIND_DELETE_GROUP].into(), + ..Default::default() + }) + .await; + let mut cfg = config(relay.url.clone()); + cfg.stage_timeout = Duration::from_millis(500); + let report = run(&cfg).await; + + let cleanup = check(&report, "cleanup"); + assert_eq!( + (cleanup.result, cleanup.failed_stage), + (Outcome::Failure, Some("delete_channel")) + ); + let channel = &channels(&relay, KIND_CREATE_GROUP)[0]; + assert!( + cleanup.error.as_deref().unwrap().contains(channel.as_str()), + "{cleanup:?}" + ); + } +} diff --git a/crates/buzz-test-client/src/bin/acceptance.rs b/crates/buzz-test-client/src/bin/acceptance.rs new file mode 100644 index 0000000000..ae374751dc --- /dev/null +++ b/crates/buzz-test-client/src/bin/acceptance.rs @@ -0,0 +1,126 @@ +//! Relay acceptance probe: checks the relay's core jobs once and exits. +//! +//! Prints a JSON report on stdout. Exits 0 when every check passed, 1 when a +//! check failed, and 2 when the probe itself could not run or report. +//! +//! Usage: +//! buzz-acceptance --relay-url wss://relay.example [--assertion-file ] +//! [--statsd-addr 127.0.0.1:8125] [--tag env:staging]... + +use std::net::SocketAddr; +use std::path::PathBuf; +use std::process::ExitCode; +use std::time::Duration; + +use buzz_test_client::acceptance::{self, metrics, Config}; +use clap::Parser; +use nostr::Keys; + +/// The longest resolving the metrics address or sending the metrics may take. +const METRICS_TIMEOUT: Duration = Duration::from_secs(5); + +#[derive(Parser)] +#[command( + name = "buzz-acceptance", + about = "Check a Buzz relay's core jobs once and report each one" +)] +struct Cli { + /// The relay's WebSocket URL. + #[arg(long, env = "BUZZ_RELAY_URL")] + relay_url: String, + /// Secret key (hex or nsec) to authenticate and sign as. Without one the + /// probe uses a new key, which works only on a relay that admits any key. + #[arg(long, env = "BUZZ_PRIVATE_KEY", hide_env_values = true)] + private_key: Option, + /// File holding a NIP-FI assertion for the key, read before every + /// connection. Keep it fresh from another process. + #[arg(long, env = "BUZZ_ACCEPTANCE_ASSERTION_FILE")] + assertion_file: Option, + /// The longest any one stage may take, in seconds. + #[arg(long, default_value_t = 10)] + stage_timeout_secs: u64, + /// DogStatsD address (`host:port`) to send metrics to. + #[arg(long, env = "BUZZ_ACCEPTANCE_STATSD_ADDR")] + statsd_addr: Option, + /// Metric name prefix. + #[arg(long, default_value = "buzz.acceptance")] + metric_prefix: String, + /// A `key:value` tag for every metric. Repeat for more. + #[arg(long = "tag")] + tags: Vec, +} + +fn main() -> ExitCode { + let _ = rustls::crypto::CryptoProvider::install_default( + rustls::crypto::aws_lc_rs::default_provider(), + ); + tracing_subscriber::fmt() + .with_env_filter(tracing_subscriber::EnvFilter::from_default_env()) + .with_writer(std::io::stderr) + .init(); + + let cli = Cli::parse(); + let runtime = match tokio::runtime::Runtime::new() { + Ok(runtime) => runtime, + Err(e) => { + eprintln!("buzz-acceptance: start runtime: {e}"); + return ExitCode::from(2); + } + }; + let result = runtime.block_on(probe(cli)); + // A timed-out hostname lookup keeps running on a blocking thread; do not + // let it hold the exit. + runtime.shutdown_timeout(Duration::from_secs(1)); + match result { + Ok(true) => ExitCode::SUCCESS, + Ok(false) => ExitCode::from(1), + Err(e) => { + eprintln!("buzz-acceptance: {e:#}"); + ExitCode::from(2) + } + } +} + +/// Runs the probe, prints its report and sends its metrics. Returns whether +/// every check passed. +async fn probe(cli: Cli) -> anyhow::Result { + let keys = match &cli.private_key { + Some(key) => Keys::parse(key).map_err(|e| anyhow::anyhow!("private key: {e}"))?, + None => Keys::generate(), + }; + let statsd = match &cli.statsd_addr { + Some(addr) => Some(resolve(addr).await?), + None => None, + }; + let cfg = Config { + relay_url: cli.relay_url, + keys, + assertion_file: cli.assertion_file, + stage_timeout: Duration::from_secs(cli.stage_timeout_secs), + }; + + let report = acceptance::run(&cfg).await; + println!("{}", serde_json::to_string(&report)?); + if let Some(addr) = statsd { + let lines = metrics::lines(&cli.metric_prefix, &report, &cli.tags); + tokio::time::timeout(METRICS_TIMEOUT, metrics::send(addr, &lines)) + .await + .map_err(|_| anyhow::anyhow!("send metrics to {addr}: timed out"))? + .map_err(|e| anyhow::anyhow!("send metrics to {addr}: {e}"))?; + } + Ok(report.passed) +} + +/// Resolves `host:port` once, before the run, so a bad address fails fast. +/// An IP literal never reaches the resolver. +async fn resolve(addr: &str) -> anyhow::Result { + if let Ok(literal) = addr.parse() { + return Ok(literal); + } + tokio::time::timeout(METRICS_TIMEOUT, tokio::net::lookup_host(addr)) + .await + .map_err(|_| anyhow::anyhow!("resolve statsd address {addr}: timed out"))? + .map_err(|e| anyhow::anyhow!("resolve statsd address {addr}: {e}"))? + .next() + .ok_or_else(|| anyhow::anyhow!("statsd address {addr} resolved to nothing")) +} diff --git a/crates/buzz-test-client/src/lib.rs b/crates/buzz-test-client/src/lib.rs index 25e47dbe4c..30c734c854 100644 --- a/crates/buzz-test-client/src/lib.rs +++ b/crates/buzz-test-client/src/lib.rs @@ -14,6 +14,9 @@ use tracing::debug; use buzz_ws_client::NostrWsConnection; pub use buzz_ws_client::{parse_relay_message, OkResponse, RelayMessage, WsClientError}; +/// Relay acceptance probe behind the `buzz-acceptance` binary. +pub mod acceptance; + /// Scenario-driven load generator behind the `buzz-loadgen` binary. /// The scenario schema is documented in `perf/LOADGEN.md`. #[allow(missing_docs)] diff --git a/crates/buzz-test-client/tests/e2e_acceptance.rs b/crates/buzz-test-client/tests/e2e_acceptance.rs new file mode 100644 index 0000000000..41b04d2a48 --- /dev/null +++ b/crates/buzz-test-client/tests/e2e_acceptance.rs @@ -0,0 +1,159 @@ +//! The `buzz-acceptance` probe against a running relay: every check passes, +//! through the shared runner and through the binary. +//! +//! Requires a running relay, so it is `#[ignore]`d. Start the relay, then run: +//! +//! ```text +//! RELAY_URL=ws://localhost:3000 cargo test -p buzz-test-client --test e2e_acceptance -- --ignored +//! ``` + +use std::io::Read; +use std::net::UdpSocket; +use std::process::{Command, Output, Stdio}; +use std::time::{Duration, Instant}; + +use buzz_test_client::acceptance::{self, Config, Outcome, CHECKS}; +use nostr::Keys; + +fn relay_url() -> String { + std::env::var("RELAY_URL").unwrap_or_else(|_| "ws://localhost:3000".into()) +} + +#[tokio::test] +#[ignore] +async fn every_acceptance_check_passes_against_a_live_relay() { + let report = acceptance::run(&Config { + relay_url: relay_url(), + keys: Keys::generate(), + assertion_file: None, + stage_timeout: Duration::from_secs(10), + }) + .await; + + let summary = serde_json::to_string_pretty(&report).unwrap(); + assert!(report.passed, "{summary}"); + let names: Vec<&str> = report.checks.iter().map(|c| c.check).collect(); + assert_eq!(names, CHECKS, "{summary}"); + for check in &report.checks { + assert_eq!(check.result, Outcome::Success, "{summary}"); + } + assert!(report.relay_version.is_some(), "{summary}"); +} + +/// Runs the binary with `args`, metrics sent to a local listener. Returns +/// its output and every datagram that arrived. +fn probe(args: &[&str]) -> (Output, Vec) { + let agent = UdpSocket::bind("127.0.0.1:0").unwrap(); + agent + .set_read_timeout(Some(Duration::from_millis(500))) + .unwrap(); + let addr = agent.local_addr().unwrap().to_string(); + let mut child = Command::new(env!("CARGO_BIN_EXE_buzz-acceptance")) + .args(args) + .args(["--statsd-addr", &addr, "--tag", "env:test"]) + .env_remove("BUZZ_PRIVATE_KEY") + .env_remove("BUZZ_RELAY_URL") + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .unwrap(); + // Drain both pipes while the child runs, so a chatty child cannot fill a + // pipe and stall before the deadline. + let stdout = drain(child.stdout.take().unwrap()); + let stderr = drain(child.stderr.take().unwrap()); + let deadline = Instant::now() + Duration::from_secs(120); + let status = loop { + if let Some(status) = child.try_wait().unwrap() { + break status; + } + if Instant::now() > deadline { + let _ = child.kill(); + let _ = child.wait(); + panic!("buzz-acceptance did not exit within 120 s"); + } + std::thread::sleep(Duration::from_millis(50)); + }; + let output = Output { + status, + stdout: stdout.join().unwrap(), + stderr: stderr.join().unwrap(), + }; + let mut lines = Vec::new(); + let mut buf = [0u8; 2048]; + while let Ok(n) = agent.recv(&mut buf) { + lines.push(String::from_utf8_lossy(&buf[..n]).into_owned()); + } + (output, lines) +} + +/// Reads `pipe` to its end on a thread, keeping at most 4 MiB. +fn drain(pipe: impl Read + Send + 'static) -> std::thread::JoinHandle> { + std::thread::spawn(move || { + let mut pipe = pipe; + let mut kept = Vec::new(); + let _ = (&mut pipe).take(4 << 20).read_to_end(&mut kept); + let _ = std::io::copy(&mut pipe, &mut std::io::sink()); + kept + }) +} + +fn report(output: &Output) -> serde_json::Value { + serde_json::from_slice(&output.stdout).unwrap_or_else(|e| { + panic!( + "stdout is not a JSON report ({e}): {}", + String::from_utf8_lossy(&output.stdout) + ) + }) +} + +#[test] +#[ignore] +fn the_binary_passes_against_a_live_relay_and_sends_metrics() { + let (output, lines) = probe(&["--relay-url", &relay_url()]); + let report = report(&output); + assert_eq!(output.status.code(), Some(0), "{report}"); + assert_eq!(report["passed"], true); + assert!( + lines.iter().any( + |l| l.starts_with("buzz.acceptance.runs:1|c|#result:success,") + && l.ends_with(",env:test") + ), + "{lines:?}" + ); + assert!( + lines.iter().any(|l| l.starts_with( + "buzz.acceptance.check.runs:1|c|#check:fanout,result:success,stage:none," + )), + "{lines:?}" + ); +} + +#[test] +#[ignore] +fn the_binary_exits_1_and_reports_when_a_check_fails() { + let (output, lines) = probe(&[ + "--relay-url", + "ws://127.0.0.1:1", + "--stage-timeout-secs", + "2", + ]); + let report = report(&output); + assert_eq!(output.status.code(), Some(1), "{report}"); + assert_eq!(report["passed"], false); + assert_eq!(report["checks"][1]["failed_stage"], "ws_connect"); + assert!( + lines + .iter() + .any(|l| l == "buzz.acceptance.runs:1|c|#result:failure,env:test"), + "{lines:?}" + ); +} + +#[test] +#[ignore] +fn the_binary_exits_2_when_it_cannot_run() { + let (output, lines) = probe(&["--relay-url", &relay_url(), "--private-key", "not-a-key"]); + assert_eq!(output.status.code(), Some(2)); + assert!(output.stdout.is_empty()); + assert!(lines.is_empty(), "{lines:?}"); +} diff --git a/scripts/run-tests.sh b/scripts/run-tests.sh index 8954836a27..a7864569ba 100755 --- a/scripts/run-tests.sh +++ b/scripts/run-tests.sh @@ -580,9 +580,10 @@ run_unit_tests() { run_test_step "buzz-relay boot lifecycle tests" \ cargo test -p buzz-relay --test boot_lifecycle -- --nocapture - # Load generator unit tests are infra-free. Keep in step with `just test-unit`. - run_test_step "buzz-test-client loadgen unit tests" \ - cargo test -p buzz-test-client --lib loadgen:: -- --nocapture + # Load generator and acceptance probe unit tests are infra-free. Keep in + # step with `just test-unit`. + run_test_step "buzz-test-client loadgen and acceptance unit tests" \ + cargo test -p buzz-test-client --lib -- --nocapture loadgen:: acceptance:: } # ---- DB / integration tests (infra required) --------------------------------