//! Transports on 127.0.0.1, in-process, with channel sinks for what they //! deliver; fake peers (blocking rustls streams written by hand) for what //! a real node never sends. Certificates: `crates/louise/tests/fixtures/ //! tls`, nodes `node-{a,b,c}.cluster.test` (`make-certs.sh nodes`). use std::collections::HashSet; use std::io::{Read, Write}; use std::net::{SocketAddr, TcpListener, TcpStream}; use std::sync::mpsc::{Receiver, RecvTimeoutError, Sender, channel}; use std::sync::{Arc, Mutex}; use std::thread::JoinHandle; use std::time::{Duration, Instant}; use louise_rt_prims::wire::MessageHeader; use rustls::pki_types::ServerName; use rustls::{ClientConnection, ServerConnection, StreamOwned}; use super::frame::{self, Hello, Peers}; use super::thread::FORGET_AFTER; use super::{ Config, Inbound, MAX_UNAUTHENTICATED, MAX_UNAUTHENTICATED_PER_SOURCE, Node, Outbound, PeerStats, Reason, Report, SendError, Stats, Throttle, Transport, Waiter, }; use crate::tls::{Authorities, ClientOptions, Identity, ServerOptions}; /// How long anything expected may take: generous, the tests never wait it /// out when they pass. const PATIENCE: Duration = Duration::from_secs(10); const SCHEMA: u64 = 0x5eed_1a7e; fn fixture(name: &str) -> String { format!( "{}/../../crates/louise/tests/fixtures/tls/{name}", env!("CARGO_MANIFEST_DIR") ) } fn name(n: &str) -> String { format!("node-{n}.cluster.test") } /// Node `n` with certificate `cert`: fast heartbeats, quick reconnection. fn config(n: &str, cert: &str) -> Config { let mut c = Config::new(&name(n), "test", "127.0.0.1:0".parse().expect("an address")); c.cert_file = fixture(&format!("{cert}.pem")); c.key_file = fixture(&format!("{cert}.key")); c.ca_files = vec![fixture("ca.pem")]; c.schema_hash = SCHEMA; c.heartbeat_ms = 100; c.node_down_after_ms = 3_000; c.reconnect_ms = 50; c } // ---- the sink --------------------------------------------------------------------------- #[derive(Clone, Debug, PartialEq)] enum Ev { Up(Node), Down(Node), Message(Node, MessageHeader, Vec), Signal(Node, Vec), Drained(Node, Vec), Closed(String, Reason), /// Sent before the `Closed` of a dial to an address only lists gave. Hearsay(String), } struct Sink(Mutex>); impl Sink { fn send(&self, e: Ev) { // The test may be over: nobody listens. let _ = self.0.lock().expect("the sink").send(e); } } impl Inbound for Sink { fn node_up(&self, peer: &Node) { self.send(Ev::Up(peer.clone())); } fn node_down(&self, peer: &Node) { self.send(Ev::Down(peer.clone())); } fn message(&self, from: &Node, header: &MessageHeader, payload: &[u8]) { self.send(Ev::Message(from.clone(), *header, payload.to_vec())); } fn signal(&self, from: &Node, body: &[u8]) { self.send(Ev::Signal(from.clone(), body.to_vec())); } fn drained(&self, peer: &Node, waiters: &[Waiter]) { self.send(Ev::Drained(peer.clone(), waiters.to_vec())); } fn closed(&self, peer: &str, reason: &Reason, hearsay: bool) { if hearsay { self.send(Ev::Hearsay(peer.to_owned())); } self.send(Ev::Closed(peer.to_owned(), reason.clone())); } } struct Events(Receiver); impl Events { fn next(&self, what: &str) -> Ev { match self.0.recv_timeout(PATIENCE) { Ok(e) => e, Err(RecvTimeoutError::Timeout) => panic!("still waiting: {what}"), Err(RecvTimeoutError::Disconnected) => panic!("the transport is gone: {what}"), } } /// The first event `want` picks; the others before it must not be a /// node coming up or going down, unless `want` takes it. fn wait(&self, what: &str, want: impl Fn(&Ev) -> Option) -> T { loop { let e = self.next(what); if let Some(t) = want(&e) { return t; } assert!( matches!(e, Ev::Closed(..) | Ev::Hearsay(_)), "{e:?} while waiting for {what}" ); } } fn up(&self, what: &str) -> Node { self.wait(what, |e| match e { Ev::Up(n) => Some(n.clone()), _ => None, }) } fn closed(&self, what: &str, want: impl Fn(&Reason) -> bool) -> (String, Reason) { self.wait(what, |e| match e { Ev::Closed(peer, r) if want(r) => Some((peer.clone(), r.clone())), _ => None, }) } /// The events of the next `period`. fn during(&self, period: Duration) -> Vec { let until = Instant::now() + period; let mut seen = Vec::new(); while let Some(left) = until.checked_duration_since(Instant::now()) { match self.0.recv_timeout(left) { Ok(e) => seen.push(e), Err(_) => break, } } seen } } fn start(config: Config) -> (Transport, Events) { let (tx, rx) = channel(); let transport = Transport::start(config, Arc::new(Sink(Mutex::new(tx)))).expect("the transport starts"); (transport, Events(rx)) } /// A message frame for `to`: `serial` names the message. fn message(to: &Node, serial: u64, payload: &[u8]) -> Vec { let header = MessageHeader { incarnation: to.incarnation, serial, tag: 1, type_hash: 9, payload_len: payload.len() as u32, }; [&header.encode()[..], payload].concat() } /// Wait until `f` holds. fn until(what: &str, f: impl Fn() -> bool) { let limit = Instant::now() + PATIENCE; while !f() { assert!(Instant::now() < limit, "still waiting: {what}"); std::thread::sleep(Duration::from_millis(5)); } } /// What `t` reports of node `n`. fn report(t: &Transport, n: &str) -> Report { t.report() .into_iter() .find(|r| r.node == name(n)) .unwrap_or_else(|| panic!("no report of {n}: {:?}", t.report())) } /// A and B, B dialing A: both up. fn pair(a: Config, mut b: Config) -> ((Transport, Events), (Transport, Events)) { let (ta, ea) = start(a); b.seeds = vec![(name("a"), ta.local_addr())]; let (tb, eb) = start(b); assert_eq!(ea.up("A sees B").name, name("b")); assert_eq!(eb.up("B sees A").name, name("a")); ((ta, ea), (tb, eb)) } // ---- fake peers ---------------------------------------------------------------------------- fn authorities(ca: &str) -> Authorities { Authorities { default_roots: false, pems: Vec::new(), files: vec![fixture(ca)], } } fn identity(cert: &str) -> Identity { Identity { cert_file: fixture(&format!("{cert}.pem")), key_file: fixture(&format!("{cert}.key")), } } type Dialer = StreamOwned; type Dialed = StreamOwned; /// A fake node with certificate `cert` dialing `addr` (node A), TLS done /// as far as the client sees it. fn fake_dial(addr: SocketAddr, cert: &str) -> Dialer { fake_dial_to(addr, &name("a"), cert) } /// [`fake_dial`] to node `node` at `addr`. fn fake_dial_to(addr: SocketAddr, node: &str, cert: &str) -> Dialer { let config = crate::tls::client_config(ClientOptions { authorities: authorities("ca.pem"), identity: Some(identity(cert)), alpn: vec![frame::ALPN.to_vec()], tls13_only: true, insecure: false, }) .expect("a client configuration"); let sock = TcpStream::connect(addr).expect("A listens"); sock.set_read_timeout(Some(PATIENCE)).expect("a timeout"); let server = ServerName::try_from(node.to_owned()).expect("a name"); let conn = ClientConnection::new(config, server).expect("a client"); let mut s = StreamOwned::new(conn, sock); // A refusing the client certificate shows on a later read. let _ = s.conn.complete_io(&mut s.sock); s } /// A fake node with certificate `cert` that A can dial: `then` runs with /// the first connection, TLS done (or failed) on its side. fn fake_listen( cert: &str, then: impl FnOnce(&mut Dialed) + Send + 'static, ) -> (SocketAddr, JoinHandle<()>) { let config = crate::tls::server_config(ServerOptions { identity: identity(cert), client_authorities: Some(authorities("ca.pem")), alpn: vec![frame::ALPN.to_vec()], tls13_only: true, peers: true, }) .expect("a server configuration"); let listener = TcpListener::bind("127.0.0.1:0").expect("a port"); let addr = listener.local_addr().expect("its address"); let thread = std::thread::spawn(move || { let (sock, _) = listener.accept().expect("A dials"); sock.set_read_timeout(Some(PATIENCE)).expect("a timeout"); let conn = ServerConnection::new(config).expect("a server"); let mut s = StreamOwned::new(conn, sock); let _ = s.conn.complete_io(&mut s.sock); then(&mut s); }); (addr, thread) } fn hello(node: &str, incarnation: u64) -> Hello { Hello { version: frame::VERSION, flags: 0, incarnation, schema_hash: SCHEMA, max_frame: 1 << 20, cluster: "test".into(), node: node.into(), } } fn put(s: &mut impl Write, kind: u8, body: &[u8]) { let len = (1 + body.len()) as u32; let frame = [&len.to_le_bytes()[..], &[kind], body].concat(); // A peer that closed shows on the next read. let _ = s.write_all(&frame).and_then(|()| s.flush()); } /// The next frame, or `None` once the connection is closed. fn get(s: &mut impl Read) -> Option<(u8, Vec)> { let mut len = [0; 4]; s.read_exact(&mut len).ok()?; let mut frame = vec![0; u32::from_le_bytes(len) as usize]; s.read_exact(&mut frame).ok()?; let (kind, body) = frame.split_first()?; Some((*kind, body.to_vec())) } /// Read until the connection closes: what it said last. fn until_closed(s: &mut impl Read) -> Vec<(u8, Vec)> { std::iter::from_fn(|| get(s)).collect() } /// A fake node B through the handshake with A, as the dialer. fn fake_up(a: &Transport, events: &Events, incarnation: u64) -> Dialer { fake_up_as(a, events, "b", incarnation) } /// A fake node `n` (`node-n` certificate) through the handshake with A. fn fake_up_as(a: &Transport, events: &Events, n: &str, incarnation: u64) -> Dialer { fake_up_with(a, events, n, incarnation, 0) } /// [`fake_up_as`], its hello setting `flags`. fn fake_up_with(a: &Transport, events: &Events, n: &str, incarnation: u64, flags: u64) -> Dialer { let mut s = fake_dial_to(a.local_addr(), &a.me().name, &format!("node-{n}")); let mut ours = hello(&name(n), incarnation); ours.flags = flags; put(&mut s, frame::HELLO, &ours.encode()); let (kind, body) = get(&mut s).expect("A's hello"); assert_eq!(kind, frame::HELLO); let theirs = Hello::decode(&body).expect("a hello"); assert_eq!( (theirs.node.as_str(), theirs.incarnation), (a.me().name.as_str(), a.me().incarnation) ); // Every op flag: a node takes every op family it knows. assert_eq!(theirs.flags & frame::FLAGS_OPS, frame::FLAGS_OPS); put(&mut s, frame::ACK, &[]); let up = events.up("the fake node is up"); assert_eq!( up, Node { name: name(n), incarnation } ); s } // ---- tests ------------------------------------------------------------------------------------ #[test] fn configurations_are_checked_at_start() { let refused = |f: &dyn Fn(&mut Config)| { let mut c = config("a", "node-a"); f(&mut c); let (tx, _rx) = channel(); Transport::start(c, Arc::new(Sink(Mutex::new(tx)))) .err() .unwrap_or_default() }; assert!(refused(&|c| c.node = "Node-A".into()).contains("not a lowercase DNS name")); assert!(refused(&|c| c.cluster = String::new()).contains("cluster name")); assert!(refused(&|c| c.ca_files.clear()).contains("no cluster authority")); assert!(refused(&|c| c.max_frame = 10).contains("max_frame")); assert!(refused(&|c| c.max_peers = 0).contains("max_peers")); assert!(refused(&|c| c.max_peers = 4097).contains("max_peers")); assert!(refused(&|c| c.node_down_after_ms = c.heartbeat_ms).contains("node_down_after_ms")); assert!(refused(&|c| c.node_down_after_ms = u64::MAX).contains("a day")); assert!(refused(&|c| c.reconnect_ms = u64::MAX).contains("a day")); assert!( refused(&|c| c.seeds = vec![(name("a"), "127.0.0.1:1".parse().expect("an address"))]) .contains("is this node") ); // A certificate that is not the node's. let e = refused(&|c| c.node = name("b")); assert!(e.contains("not valid for the node name"), "{e}"); let e = refused(&|c| c.cert_file = fixture("nonexistent.pem")); assert!(e.contains("nonexistent.pem"), "{e}"); assert_eq!(refused(&|_| {}), "", "the fixture configuration starts"); } #[test] fn frames_flow_in_order_both_ways() { let ((a, ea), (b, eb)) = pair(config("a", "node-a"), config("b", "node-b")); let (to_a, to_b) = (a.me().clone(), b.me().clone()); assert_eq!(a.peers(), std::slice::from_ref(&to_b)); assert_eq!(b.peers(), std::slice::from_ref(&to_a)); // Messages and signals interleaved, small and large (a frame of 1 MiB // is written in many pieces). let frames = |_: &Node| -> Vec<(bool, u64, Vec)> { (0..300u64) .map(|i| match i { 150 => (true, i, vec![0xab; 1 << 20]), // A signal starts with its op: one the handler takes, not // the transport's own (`frame::PEERS`). _ if i % 7 == 0 => (false, i, [&[0x10][..], &i.to_le_bytes()].concat()), _ => (true, i, vec![i as u8; (i % 100) as usize]), }) .collect() }; let send = |t: &Transport, to: &Node| { for (is_message, i, payload) in frames(to) { let frame = if is_message { Outbound::Message(message(to, i, &payload)) } else { Outbound::Signal(payload) }; t.send(to, frame).expect("queued"); } }; std::thread::scope(|s| { s.spawn(|| send(&a, &to_b)); s.spawn(|| send(&b, &to_a)); }); for (events, from, me) in [(&eb, &to_a, &to_b), (&ea, &to_b, &to_a)] { for (is_message, i, payload) in frames(me) { let want = if is_message { let header = MessageHeader { incarnation: me.incarnation, serial: i, tag: 1, type_hash: 9, payload_len: payload.len() as u32, }; Ev::Message(from.clone(), header, payload) } else { Ev::Signal(from.clone(), payload) }; let got = events.next("the next frame"); assert!(got == want, "frame {i} out of order: {got:?}"); } } // Counted on both sides; heartbeats and their echoes give a round-trip // time. let messages = frames(&to_a).iter().filter(|f| f.0).count() as u64; until("A's round trip to B", || report(&a, "b").rtt_us.is_some()); let seen = report(&a, "b"); assert_eq!( (seen.up, seen.incarnation, seen.queued), (true, Some(to_b.incarnation), 0) ); assert_eq!( (seen.sent, seen.received, seen.unsent, seen.dropped), (messages, messages, 0, 0) ); // What `send` refuses. let stranger = Node { name: name("c"), incarnation: 1, }; let old_b = Node { incarnation: to_b.incarnation ^ 1, ..to_b.clone() }; assert_eq!( a.send(&stranger, Outbound::Signal(vec![1])), Err(SendError::NotConnected) ); assert_eq!( a.send(&old_b, Outbound::Signal(vec![1])), Err(SendError::NotConnected), "another incarnation" ); assert_eq!( a.send(&to_b, Outbound::Signal(vec![0; 8 << 20])), Err(SendError::TooLarge), "over B's limit" ); let mut short = message(&to_b, 1, b"abc"); short.pop(); assert_eq!( a.send(&to_b, Outbound::Message(short)), Err(SendError::Malformed) ); assert_eq!( a.send(&to_b, Outbound::Message(message(&old_b, 1, b""))), Err(SendError::Malformed), "a header for another incarnation" ); assert_eq!(a.connections(), 1); b.stop(); let down = ea.wait("B down", |e| match e { Ev::Down(n) => Some(n.clone()), _ => None, }); assert_eq!(down, to_b); assert_eq!(a.peers(), []); assert_eq!(a.dropped(), 0); let seen = report(&a, "b"); assert_eq!( (seen.up, seen.incarnation, seen.rtt_us, seen.sent), (false, Some(to_b.incarnation), None, messages), "kept once down" ); } /// Message frames of 1 KiB of payload for `to`, from `first` on, until /// the queue is full: the one it gave back, and how many it took. fn fill(a: &Transport, to: &Node, first: u64, waiter: Option) -> (Outbound, u64) { let payload = vec![0; 1 << 10]; for i in first..first + 100_000 { match a.queue(to, Outbound::Message(message(to, i, &payload)), waiter) { Ok(()) => {} Err((SendError::Full, frame)) => return (frame, i - first), Err((e, _)) => panic!("{e:?}"), } } panic!("the queue never filled"); } /// Read `s` until `n` message frames came: the serials, in order. fn read_messages(s: &mut impl Read, n: u64) -> Vec { let mut serials = Vec::new(); while serials.len() < n as usize { let (kind, body) = get(s).expect("a frame"); if kind == frame::MESSAGE { serials.push(u64::from_le_bytes(body[8..16].try_into().expect("8 bytes"))); } } serials } #[test] fn a_full_queue_gives_messages_back_and_wakes_its_waiters() { let mut ca = config("a", "node-a"); ca.max_queue = 4 << 10; ca.node_down_after_ms = 60_000; // A peer that reads nothing yet: once the sockets' buffers are full, // nothing leaves A's queue. let (a, ea) = start(ca); let mut fake = fake_up(&a, &ea, 7); let b = Node { name: name("b"), incarnation: 7, }; // An empty queue takes a message over `max_queue`. a.send(&b, Outbound::Message(message(&b, 0, &[0; 4 << 10]))) .expect("an empty queue takes any message"); until("the thread takes it", || report(&a, "b").queued == 0); let first = Waiter { pid: 5, wait: 1 }; let (back, taken) = fill(&a, &b, 1, Some(first)); let serial = |frame: &Outbound| match frame { Outbound::Message(body) => u64::from_le_bytes(body[8..16].try_into().expect("8 bytes")), Outbound::Request(_) | Outbound::Signal(_) => panic!("a signal"), }; assert_eq!(serial(&back), 1 + taken, "given back"); let seen = report(&a, "b"); assert!(seen.queued <= 4 << 10, "bounded: {seen:?}"); assert_eq!(seen.parked, 1, "one waiter registered"); assert_eq!( a.send(&b, Outbound::Signal(vec![1])), Ok(()), "signals pass" ); // The peer reads: the thread takes the queue, and wakes the waiter, // once. It sends its message then, after the others. let reader = std::thread::spawn(move || { let serials = read_messages(&mut fake, 1 + taken); (fake, serials) }); let drained = ea.wait("the waiter woken", |e| match e { Ev::Drained(n, w) => Some((n.clone(), w.clone())), _ => None, }); assert_eq!(drained, (b.clone(), vec![first])); let (mut fake, serials) = reader.join().expect("the reader"); assert_eq!(serials, (0..1 + taken).collect::>(), "in order"); a.queue(&b, back, None) .map_err(|(e, _)| e) .expect("room now"); assert_eq!(read_messages(&mut fake, 1), [1 + taken]); // Full again, until the sockets' buffers are too: nothing leaves for // 100 ms. let mut next = 2 + taken; let mut idle = 0; while idle < 100 { let (_, more) = fill(&a, &b, next, None); next += more; if more == 0 { idle += 1; std::thread::sleep(Duration::from_millis(1)); } else { idle = 0; } } // A waiter forgotten (an exited sender), then another: the node going // down wakes the one left, the queued messages unsent. let gone = Waiter { pid: 6, wait: 1 }; assert_eq!(fill(&a, &b, next, Some(gone)).1, 0); assert_eq!( a.send(&b, Outbound::Request(vec![0x20; 1 << 10])), Err(SendError::Full), "a spawn request counts as a message does" ); a.unwait(&b, gone); let last = Waiter { pid: 6, wait: 2 }; let (back, _) = fill(&a, &b, next, Some(last)); drop(fake); let drained = ea.wait("the waiter woken by the loss", |e| match e { Ev::Drained(n, w) => Some((n.clone(), w.clone())), _ => None, }); assert_eq!(drained, (b.clone(), vec![last])); // The loss's `closed` and `node_down` come through the relay, after // the wake. let down = ea.wait("B down", |e| match e { Ev::Down(n) => Some(n.clone()), _ => None, }); assert_eq!(down, b); assert_eq!( a.queue(&b, back, Some(last)).map_err(|(e, _)| e), Err(SendError::NotConnected) ); let seen = report(&a, "b"); assert!(!seen.up && seen.unsent > 0, "{seen:?}"); assert!(seen.sent >= 2 + taken, "{seen:?}"); assert_eq!(seen.parked, 3, "{seen:?}"); } #[test] fn heartbeats_overtake_a_long_queue() { let mut ca = config("a", "node-a"); ca.node_down_after_ms = 60_000; let (a, ea) = start(ca); let mut fake = fake_up(&a, &ea, 7); let b = Node { name: name("b"), incarnation: 7, }; // 32 MiB queued while the peer reads nothing: more than the sockets' // buffers take, so most of it waits in A while heartbeats come due. const N: u64 = 8 << 10; for i in 0..N { a.send(&b, Outbound::Message(message(&b, i, &[0; 4 << 10]))) .expect("queued"); } std::thread::sleep(Duration::from_millis(500)); let (mut messages, mut overtaken) = (0, None); while messages < N { let (kind, body) = get(&mut fake).expect("a frame"); match kind { frame::MESSAGE => { assert_eq!(body[8..16], messages.to_le_bytes(), "in order"); messages += 1; } frame::HEARTBEAT => { if messages > 0 && overtaken.is_none() { overtaken = Some(messages); } put(&mut fake, frame::ECHO, &body); } other => panic!("frame kind {other}"), } } let overtaken = overtaken.expect("a heartbeat among the messages"); assert!(overtaken < N / 2, "a heartbeat after {overtaken} messages"); until("a round-trip time", || report(&a, "b").rtt_us.is_some()); // A answers the peer's heartbeats with their stamp. put(&mut fake, frame::HEARTBEAT, &[1, 2, 3, 4, 5, 6, 7, 8]); loop { match get(&mut fake).expect("a frame") { (frame::ECHO, body) => break assert_eq!(body, [1, 2, 3, 4, 5, 6, 7, 8]), (frame::HEARTBEAT, _) => {} (other, _) => panic!("frame kind {other}"), } } } /// #423: a peer's hello names the op families it takes. A signal frame /// of an op whose flag the peer cleared is refused (`Unsupported`), and /// `lacks` says so first; every other frame goes, in order. A node sets /// every op flag in its own hello ([`fake_up_with`] checks it). #[test] fn a_peer_gets_only_the_ops_its_hello_flags() { let (a, ea) = start(config("a", "node-a")); let ops: [(u8, u64); 5] = [ (0x16, frame::FLAG_DEMONITOR), (0x17, frame::FLAG_UNLINK), (0x18, frame::FLAG_UNLINK), (0x22, frame::FLAG_SPAWN_LINKED), (0x23, frame::FLAG_SPAWN_MONITORED), ]; let cleared = [ 0, frame::FLAG_DEMONITOR, frame::FLAG_SPAWN_LINKED, frame::FLAG_SPAWN_MONITORED, frame::FLAG_UNLINK, frame::FLAGS_OPS, ]; for (round, clear) in cleared.into_iter().enumerate() { let incarnation = 10 + round as u64; // Unknown bits are ignored. let flags = (u64::MAX << 5 | frame::FLAGS_OPS) & !clear; let mut fake = fake_up_with(&a, &ea, "b", incarnation, flags); let b = Node { name: name("b"), incarnation, }; let mut sent = Vec::new(); for (op, flag) in ops { let body = [&[op][..], &[round as u8; 24]].concat(); let lacked = flag & clear != 0; assert_eq!(a.lacks(&b, op), lacked, "op {op:02x}, cleared {clear:b}"); let frame = match op { 0x22 | 0x23 => Outbound::Request(body.clone()), _ => Outbound::Signal(body.clone()), }; let queued = a.send(&b, frame); if lacked { assert_eq!(queued, Err(SendError::Unsupported), "op {op:02x}"); } else { assert_eq!(queued, Ok(()), "op {op:02x}"); sent.push(body); } } // Ops every node takes, and a message, go whatever the flags. for op in [0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x20, 0x21] { assert!(!a.lacks(&b, op)); } a.send(&b, Outbound::Message(message(&b, 1, b"m"))) .expect("a message"); let end = vec![0x10, round as u8]; a.send(&b, Outbound::Signal(end.clone())).expect("a link"); sent.push(end); let mut got = Vec::new(); while got.last() != sent.last() { match get(&mut fake).expect("a frame") { (frame::SIGNAL, body) => got.push(body), (frame::MESSAGE | frame::HEARTBEAT | frame::ECHO, _) => {} (kind, _) => panic!("a frame of kind {kind}"), } } assert_eq!(got, sent, "cleared {clear:b}"); drop(fake); let down = ea.wait("B down", |e| match e { Ev::Down(n) => Some(n.clone()), _ => None, }); assert_eq!(down, b); // Not up: nothing lacks, and a send is not connected. assert!(!a.lacks(&b, 0x16)); assert_eq!( a.send(&b, Outbound::Signal(vec![0x16])), Err(SendError::NotConnected) ); } } #[test] fn the_cluster_and_schema_must_match() { for (field, want_a, want_code) in [ ("cluster", Reason::Cluster("other".into()), 2), ("schema", Reason::Schema(SCHEMA + 1), 3), ] { let (a, ea) = start(config("a", "node-a")); let mut cb = config("b", "node-b"); match field { "cluster" => cb.cluster = "other".into(), _ => cb.schema_hash = SCHEMA + 1, } cb.seeds = vec![(name("a"), a.local_addr())]; let (b, eb) = start(cb); let (peer, _) = ea.closed(field, |r| *r == want_a); assert!( peer.starts_with(&format!("{} at 127.0.0.1:", name("b"))), "{peer}" ); let (peer, why) = eb.closed(field, |r| matches!(r, Reason::Refused(..))); assert_eq!(peer, name("a")); let Reason::Refused(code, text) = why else { unreachable!() }; assert_eq!(code, want_code, "{field}: {text}"); assert!(a.peers().is_empty() && b.peers().is_empty(), "{field}"); } } #[test] fn another_protocol_version_is_refused() { let (a, ea) = start(config("a", "node-a")); let mut s = fake_dial(a.local_addr(), "node-b"); let mut h = hello(&name("b"), 1).encode(); h[0] = 2; put(&mut s, frame::HELLO, &h); ea.closed("version", |r| *r == Reason::Version(2)); let said = until_closed(&mut s); assert!( matches!(said.as_slice(), [(frame::REFUSE, body)] if body[0] == 1), "{said:?}" ); assert!(a.peers().is_empty()); } #[test] fn certificates_must_name_the_node() { let (a, ea) = start(config("a", "node-a")); // Dialing A with a certificate of another authority, or for another // name than the one claimed. let mut rogue = fake_dial(a.local_addr(), "node-rogue"); put(&mut rogue, frame::HELLO, &hello(&name("b"), 1).encode()); ea.closed("a rogue dialer", |r| matches!(r, Reason::Tls(_))); let mut impostor = fake_dial(a.local_addr(), "node-impostor"); put(&mut impostor, frame::HELLO, &hello(&name("b"), 1).encode()); ea.closed("an impostor dialer", |r| *r == Reason::Name(name("b"))); assert!( matches!(until_closed(&mut impostor).as_slice(), [(frame::REFUSE, body)] if body[0] == 4) ); // A certificate valid for the claimed name, but not A's peer: its own. let mut itself = fake_dial(a.local_addr(), "node-a"); put(&mut itself, frame::HELLO, &hello(&name("a"), 1).encode()); ea.closed("A itself", |r| *r == Reason::Name(name("a"))); // A dialing a node whose certificate is of another authority, not // valid for the name dialed, or whose hello claims another name. for (cert, claim, rustls_refuses) in [ ("node-rogue", "b", true), ("node-impostor", "b", true), ("node-b", "c", false), ] { let (addr, fake) = fake_listen(cert, move |s| { if get(s).is_some_and(|(kind, _)| kind == frame::HELLO) { put(s, frame::HELLO, &hello(&name(claim), 1).encode()); let _ = until_closed(s); } }); a.connect(&name("b"), addr); let (peer, why) = ea.closed(cert, |r| matches!(r, Reason::Tls(_) | Reason::Name(_))); assert_eq!(peer, name("b")); if rustls_refuses { assert!(matches!(why, Reason::Tls(_)), "{cert}: {why:?}"); } else { assert_eq!(why, Reason::Name(name(claim))); } fake.join().expect("the fake node"); } assert!(a.peers().is_empty()); } #[test] fn simultaneous_dials_keep_one_connection() { for round in 0..5 { let (a, ea) = start(config("a", "node-a")); let (b, eb) = start(config("b", "node-b")); std::thread::scope(|s| { s.spawn(|| a.connect(&name("b"), b.local_addr())); s.spawn(|| b.connect(&name("a"), a.local_addr())); }); assert_eq!(ea.up("A sees B"), *b.me(), "round {round}"); assert_eq!(eb.up("B sees A"), *a.me(), "round {round}"); until("one connection each", || { a.connections() == 1 && b.connections() == 1 }); for e in ea.during(Duration::from_millis(300)) { assert!( matches!(&e, Ev::Closed(_, r) if r.routine()), "round {round}: {e:?}" ); } assert_eq!((a.connections(), b.connections()), (1, 1)); // The connection kept works both ways. a.send(b.me(), Outbound::Signal(vec![1])).expect("A sends"); b.send(a.me(), Outbound::Signal(vec![2])).expect("B sends"); let got = eb.wait("A's signal", |e| match e { Ev::Signal(_, body) => Some(body.clone()), _ => None, }); assert_eq!(got, [1]); let got = ea.wait("B's signal", |e| match e { Ev::Signal(_, body) => Some(body.clone()), _ => None, }); assert_eq!(got, [2]); } } #[test] fn a_silent_peer_is_down_after_node_down_after_ms() { let mut ca = config("a", "node-a"); ca.node_down_after_ms = 500; let mut cb = config("b", "node-b"); cb.node_down_after_ms = 500; // Heartbeats keep an idle connection up. let ((a, ea), (b, eb)) = pair(ca.clone(), cb); let seen = ea.during(Duration::from_millis(1_500)); assert!(seen.is_empty(), "an idle connection: {seen:?}"); assert!(eb.during(Duration::ZERO).is_empty()); drop((a, b)); // A fake peer that completes the handshake, then goes silent. let (a, ea) = start(ca); let fake = fake_up(&a, &ea, 7); let up = Instant::now(); let (_, why) = ea.closed("a timeout", |r| *r == Reason::Timeout); let after = up.elapsed(); assert_eq!(why, Reason::Timeout); let down = ea.next("B down"); assert!( matches!(&down, Ev::Down(n) if n.incarnation == 7), "{down:?}" ); assert!( after >= Duration::from_millis(400) && after < Duration::from_millis(3_000), "down after {after:?}" ); drop(fake); // A dialer that never says hello is closed as late. let _mute = fake_dial(a.local_addr(), "node-b"); let since = Instant::now(); let (_, why) = ea.closed("a mute dialer", |_| true); assert_eq!(why, Reason::Timeout); assert!(since.elapsed() < Duration::from_millis(3_000)); } /// A sink that takes its time over each message, as decoding may. struct Slow(Sink, Duration); impl Inbound for Slow { fn node_up(&self, peer: &Node) { self.0.node_up(peer); } fn node_down(&self, peer: &Node) { self.0.node_down(peer); } fn message(&self, from: &Node, header: &MessageHeader, payload: &[u8]) { std::thread::sleep(self.1); self.0.message(from, header, payload); } fn signal(&self, from: &Node, body: &[u8]) { self.0.signal(from, body); } fn drained(&self, peer: &Node, waiters: &[Waiter]) { self.0.drained(peer, waiters); } fn closed(&self, peer: &str, reason: &Reason, hearsay: bool) { self.0.closed(peer, reason, hearsay); } } #[test] fn a_flooding_peer_starves_no_other() { // C writes faster than A's handler reads: A's socket from C never runs // dry, yet A keeps heartbeating B and reading B's. let mut ca = config("a", "node-a"); ca.node_down_after_ms = 600; let (tx, rx) = channel(); let slow = Slow(Sink(Mutex::new(tx)), Duration::from_micros(20)); let a = Transport::start(ca, Arc::new(slow)).expect("A starts"); let ea = Events(rx); let mut cb = config("b", "node-b"); cb.node_down_after_ms = 600; cb.seeds = vec![(name("a"), a.local_addr())]; let (b, eb) = start(cb); assert_eq!(ea.up("A sees B"), *b.me()); assert_eq!(eb.up("B sees A"), *a.me()); let mut c = fake_up_as(&a, &ea, "c", 9); let to_a = a.me().clone(); let flood = std::thread::spawn(move || { let until = Instant::now() + Duration::from_millis(2_000); let mut serial = 0; while Instant::now() < until { put(&mut c, frame::MESSAGE, &message(&to_a, serial, &[0; 64])); serial += 1; } c }); let seen = eb.during(Duration::from_millis(2_000)); assert!(seen.is_empty(), "B while C floods A: {seen:?}"); assert_eq!(b.peers(), [a.me().clone()]); drop(flood.join().expect("the flood")); } /// A fake peer, up with A, sends a heartbeat: how long A took to echo it. fn echo_time(c: &mut Dialer, stamp: u64) -> Duration { let sent = Instant::now(); put(c, frame::HEARTBEAT, &stamp.to_le_bytes()); loop { match get(c) { Some((frame::ECHO, body)) if body == stamp.to_le_bytes() => return sent.elapsed(), Some(_) => {} None => panic!("A closed the connection"), } } } /// A's handler takes 400 ms a message, as decoding a few MiB of boxed /// leaves does: it runs beside the transport, so A echoes C's heartbeats /// at once meanwhile (#404's security review, SEC-6: they waited for each /// decode). B's messages, twice A's backlog for a peer, pause B's /// connection, which is not taken for silent, and all arrive, in order. #[test] fn a_slow_handler_holds_up_no_heartbeat() { let mut ca = config("a", "node-a"); ca.node_down_after_ms = 1_000; let (tx, rx) = channel(); let slow = Slow(Sink(Mutex::new(tx)), Duration::from_millis(400)); let a = Transport::start(ca, Arc::new(slow)).expect("A starts"); let ea = Events(rx); let mut cb = config("b", "node-b"); cb.node_down_after_ms = 1_000; cb.seeds = vec![(name("a"), a.local_addr())]; let (b, eb) = start(cb); assert_eq!(ea.up("A sees B"), *b.me()); assert_eq!(eb.up("B sees A"), *a.me()); let mut c = fake_up_as(&a, &ea, "c", 9); let n = 2 * super::relay::BACKLOG as u64 / (1 << 20); for serial in 0..n { let frame = message(a.me(), serial, &vec![0; 1 << 20]); b.send(a.me(), Outbound::Message(frame)).expect("queued"); } // Until B's messages are handled, and a little more. let until = Instant::now() + Duration::from_millis(400) * n as u32; let mut worst = Duration::ZERO; let mut stamp = 0; let mut paused = false; while Instant::now() < until { stamp += 1; worst = worst.max(echo_time(&mut c, stamp)); paused |= !a.relay.resumed(&b.me().name); std::thread::sleep(Duration::from_millis(50)); } assert!(worst < Duration::from_millis(200), "an echo took {worst:?}"); assert!(paused, "B's backlog paused its connection"); let messages: Vec = (0..n) .map(|_| { ea.wait("B's messages", |e| match e { Ev::Message(from, header, _) if from == b.me() => Some(header.serial), _ => None, }) }) .collect(); assert_eq!(messages, (0..n).collect::>()); assert_eq!(eb.during(Duration::ZERO), [], "B kept A"); drop(c); } #[test] fn a_restarted_node_is_a_new_incarnation() { let ((a, ea), (b, _eb)) = pair(config("a", "node-a"), config("b", "node-b")); let first = b.me().clone(); b.stop(); let down = ea.wait("B down", |e| match e { Ev::Down(n) => Some(n.clone()), _ => None, }); assert_eq!(down, first); let mut cb = config("b", "node-b"); cb.seeds = vec![(name("a"), a.local_addr())]; let (b, _eb) = start(cb); let second = ea.up("B again"); assert_eq!(second, *b.me()); assert_ne!(second.incarnation, first.incarnation); drop((a, b)); // A new incarnation replaces one A still takes for up: the old one is // down at once, not after node_down_after_ms. let mut ca = config("a", "node-a"); ca.node_down_after_ms = 60_000; let (a, ea) = start(ca); let _silent = fake_up(&a, &ea, 7); let since = Instant::now(); let mut cb = config("b", "node-b"); cb.seeds = vec![(name("a"), a.local_addr())]; let (b, _eb) = start(cb); let down = ea.wait("the old B down", |e| match e { Ev::Down(n) => Some(n.clone()), _ => None, }); assert_eq!(down.incarnation, 7); assert_eq!(ea.up("the new B"), *b.me()); assert!(since.elapsed() < PATIENCE); assert_eq!(a.peers(), [b.me().clone()]); } #[test] fn a_full_node_refuses_strangers_not_its_seeds() { // Node X (the certificate for node-x) keeps two peers. let mut cx = config("x", "node-impostor"); cx.max_peers = 2; let (x, ex) = start(cx); let _a = fake_up_as(&x, &ex, "a", 1); let _b = fake_up_as(&x, &ex, "b", 1); // A third is refused at its hello, before X's goes out. let mut c = fake_dial_to(x.local_addr(), &name("x"), "node-c"); put(&mut c, frame::HELLO, &hello(&name("c"), 1).encode()); let (peer, _) = ex.closed("C refused", |r| *r == Reason::Full); assert!( peer.starts_with(&format!("{} at 127.0.0.1:", name("c"))), "{peer}" ); let said = until_closed(&mut c); assert!( matches!(said.as_slice(), [(frame::REFUSE, body)] if body[0] == 8), "{said:?}" ); // A new incarnation of a peer is no stranger: it replaces the old. let mut b = fake_dial_to(x.local_addr(), &name("x"), "node-b"); put(&mut b, frame::HELLO, &hello(&name("b"), 2).encode()); assert_eq!(get(&mut b).map(|(kind, _)| kind), Some(frame::HELLO)); put(&mut b, frame::ACK, &[]); loop { match ex.next("the new B") { Ev::Up(n) => break assert_eq!((n.name, n.incarnation), (name("b"), 2)), Ev::Down(n) => assert_eq!((n.name, n.incarnation), (name("b"), 1)), Ev::Closed(..) => {} e => panic!("{e:?} while waiting for the new B"), } } // A node X was told to connect to is never refused: C, once X dials // it (to a socket that never answers), dials in past the cap; X drops // its own dial, as for simultaneous dials (C's name is smaller). let held = TcpListener::bind("127.0.0.1:0").expect("a port"); x.connect(&name("c"), held.local_addr().expect("its address")); let (_dialed, _) = held.accept().expect("X dials C"); let _c = fake_up_as(&x, &ex, "c", 1); let names: Vec = x.peers().into_iter().map(|p| p.name).collect(); assert_eq!(names, [name("a"), name("b"), name("c")], "past max_peers"); } #[test] fn down_nodes_are_forgotten_least_recently_seen_first() { let known = |p: &PeerStats| { let mut names: Vec = p.iter().map(|(n, _)| n.clone()).collect(); names.sort(); names }; let mut p = PeerStats::new(2); p.keep("seed"); p.up("up"); p.stats("d1"); p.stats("d2"); // A message for d1: d2 is now the least recently seen. Stats::count(&p.stats("d1").unsent, 1); p.stats("d3"); assert_eq!(known(&p), ["d1", "d3", "seed", "up"]); let unsent = p .stats("d1") .unsent .load(std::sync::atomic::Ordering::Relaxed); assert_eq!(unsent, 1, "kept whole"); // However many names pass, a node up and a seed stay. for i in 0..100 { p.stats(&format!("n{i:02}")); } assert_eq!(known(&p), ["n98", "n99", "seed", "up"]); // A node that goes down is the most recently seen of the down ones. p.down("up"); assert_eq!(known(&p), ["n99", "seed", "up"]); // Up again, it is not counted among them. p.up("up"); p.stats("e"); assert_eq!(known(&p), ["e", "n99", "seed", "up"]); // Through the transport: its seeds, and what it reports. let mut ca = config("a", "node-a"); ca.max_peers = 1; ca.seeds = vec![(name("c"), "127.0.0.1:1".parse().expect("an address"))]; let (a, _ea) = start(ca); a.count_unsent(&name("b")); a.count_unsent(&name("x")); let reported: Vec = a.report().into_iter().map(|r| r.node).collect(); assert_eq!(reported, [name("c"), name("x")]); } #[test] fn bad_frames_close_the_connection() { let mut ca = config("a", "node-a"); ca.max_frame = 4096; let (a, ea) = start(ca); let b = |incarnation| Node { name: name("b"), incarnation, }; // A message for another incarnation of A is dropped and counted, the // connection kept. let mut s = fake_up(&a, &ea, 100); let stale = Node { incarnation: a.me().incarnation ^ 1, ..a.me().clone() }; put(&mut s, frame::MESSAGE, &message(&stale, 1, b"hi")); until("the frame dropped", || a.dropped() == 1); put(&mut s, frame::MESSAGE, &message(a.me(), 2, b"hi")); let got = ea.next("the next message"); assert!( matches!(&got, Ev::Message(_, h, p) if h.serial == 2 && p == b"hi"), "{got:?}" ); // Closed with A's heartbeat unread: an end of stream, or a reset. drop(s); let (peer, _) = ea.closed("B gone", |r| matches!(r, Reason::Closed(_))); assert_eq!(peer, name("b")); assert_eq!(ea.next("B down"), Ev::Down(b(100))); let cases: [(&[u8], Reason); 6] = [ // Over the limit: refused on its prefix alone. (&4097u32.to_le_bytes(), Reason::TooLarge(4097)), (&[0xff; 64], Reason::TooLarge(u32::MAX)), ( &[2, 0, 0, 0, 0x7f, 0], Reason::Protocol("an unexpected frame"), ), ( &[3, 0, 0, 0, frame::MESSAGE, 1, 2], Reason::Protocol("a message frame shorter than its header"), ), ( &[1, 0, 0, 0, frame::HELLO], Reason::Protocol("an unexpected frame"), ), // A heartbeat carries a stamp. ( &[1, 0, 0, 0, frame::HEARTBEAT], Reason::Protocol("an unexpected frame"), ), ]; for (i, (bytes, reason)) in cases.into_iter().enumerate() { let mut s = fake_up(&a, &ea, i as u64); s.write_all(bytes).expect("written"); s.flush().expect("flushed"); let (_, why) = ea.closed("a bad frame", |_| true); assert_eq!(why, reason, "case {i}"); assert_eq!(ea.next("B down"), Ev::Down(b(i as u64)), "case {i}"); // Its heartbeats, then why. let said = until_closed(&mut s); let kinds: Vec = said.iter().map(|(k, _)| *k).collect(); assert!( kinds .split_last() .is_some_and(|(last, before)| *last == frame::REFUSE && before.iter().all(|k| *k == frame::HEARTBEAT)), "{said:?}" ); } // Before the hello, frames are 1 KiB at most. let mut s = fake_dial(a.local_addr(), "node-b"); s.write_all(&2_000u32.to_le_bytes()).expect("written"); s.flush().expect("flushed"); let (_, why) = ea.closed("a large frame before the hello", |_| true); assert_eq!(why, Reason::TooLarge(2_000)); // Bytes that are not TLS at all. let mut raw = TcpStream::connect(a.local_addr()).expect("A listens"); raw.write_all(b"GET / HTTP/1.1\r\n\r\n").expect("written"); ea.closed("not TLS", |r| matches!(r, Reason::Tls(_))); let mut rest = Vec::new(); raw.set_read_timeout(Some(PATIENCE)).expect("a timeout"); let _ = raw.read_to_end(&mut rest); // A still works. let mut cb = config("b", "node-b"); cb.seeds = vec![(name("a"), a.local_addr())]; let (b, _eb) = start(cb); assert_eq!(ea.up("a real B"), *b.me()); } /// A TCP connection to `to` from the loopback address `127.0.0.{host}`: /// another source, as far as A's eviction goes. fn connect_from(host: u8, to: SocketAddr) -> std::io::Result { use std::os::fd::FromRawFd; let SocketAddr::V4(to) = to else { unreachable!("A listens on 127.0.0.1") }; let addr = |ip: std::net::Ipv4Addr, port: u16| libc::sockaddr_in { sin_family: libc::AF_INET as libc::sa_family_t, sin_port: port.to_be(), sin_addr: libc::in_addr { s_addr: u32::from(ip).to_be(), }, sin_zero: [0; 8], }; let len = std::mem::size_of::() as libc::socklen_t; // SAFETY: a fresh socket, owned by the stream once connected (closed // here otherwise); the addresses are `sockaddr_in`s of `len` bytes. unsafe { let fd = libc::socket(libc::AF_INET, libc::SOCK_STREAM | libc::SOCK_CLOEXEC, 0); if fd < 0 { return Err(std::io::Error::last_os_error()); } let from = addr(std::net::Ipv4Addr::new(127, 0, 0, host), 0); let to = addr(*to.ip(), to.port()); if libc::bind(fd, (&raw const from).cast(), len) != 0 || libc::connect(fd, (&raw const to).cast(), len) != 0 { let e = std::io::Error::last_os_error(); libc::close(fd); return Err(e); } Ok(TcpStream::from_raw_fd(fd)) } } #[test] fn idle_sockets_cannot_lock_nodes_out() { let mut ca = config("a", "node-a"); ca.node_down_after_ms = 60_000; let (a, ea) = start(ca); // As many as A holds, from as few sources as can hold them. let sources = (MAX_UNAUTHENTICATED / MAX_UNAUTHENTICATED_PER_SOURCE) as u8; let idle: Vec = (0..MAX_UNAUTHENTICATED) .map(|i| { let host = 2 + i as u8 % sources; connect_from(host, a.local_addr()).expect("A listens") }) .collect(); until("A holds them", || a.connections() == MAX_UNAUTHENTICATED); // B's connection closes the oldest of a source that holds the most. let mut cb = config("b", "node-b"); cb.seeds = vec![(name("a"), a.local_addr())]; let (b, _eb) = start(cb); assert_eq!(ea.up("B, past the idle sockets"), *b.me()); assert_eq!(a.connections(), MAX_UNAUTHENTICATED); // One source's connections past its share close its own oldest: B // took one of 127.0.0.2's (the oldest), the first of these takes it // back. let more: Vec = (0..=MAX_UNAUTHENTICATED_PER_SOURCE) .map(|_| connect_from(2, a.local_addr()).expect("A listens")) .collect(); let crowded = (0..MAX_UNAUTHENTICATED_PER_SOURCE) .map(|_| ea.closed("an idle socket", |r| *r == Reason::Crowded).0) .collect::>(); assert!( crowded.iter().all(|peer| peer.starts_with("127.0.0.2:")), "{crowded:?}" ); drop((idle, more)); } /// A dialer whose handshake (TCP accept to hello) takes `delay`, as over a /// link of that round-trip time: the TCP connection, then `meanwhile`, /// then the rest of `delay`, then TLS and the hello. Whether A took it up. fn slow_dial(a: &Transport, delay: Duration, incarnation: u64, meanwhile: impl FnOnce()) -> bool { let config = crate::tls::client_config(ClientOptions { authorities: authorities("ca.pem"), identity: Some(identity("node-b")), alpn: vec![frame::ALPN.to_vec()], tls13_only: true, insecure: false, }) .expect("a client configuration"); let since = Instant::now(); let sock = TcpStream::connect(a.local_addr()).expect("A listens"); sock.set_read_timeout(Some(PATIENCE)).expect("a timeout"); meanwhile(); std::thread::sleep(delay.saturating_sub(since.elapsed())); let server = ServerName::try_from(name("a")).expect("a name"); let conn = ClientConnection::new(config, server).expect("a client"); let mut s = StreamOwned::new(conn, sock); let _ = s.conn.complete_io(&mut s.sock); put( &mut s, frame::HELLO, &hello(&name("b"), incarnation).encode(), ); let answered = get(&mut s).is_some_and(|(kind, _)| kind == frame::HELLO); if answered { put(&mut s, frame::ACK, &[]); until("B up", || { a.peers().iter().any(|p| p.incarnation == incarnation) }); } drop(s); until("B forgotten", || a.peers().is_empty()); answered } /// Another host opening connections faster than a distant node handshakes /// (50 ms) evicts only its own (#404's security review, SEC-2: A closed /// the oldest of all, the distant node's): a burst of connections while it /// handshakes, then a steady 2,000 a second. #[test] fn a_flood_from_one_host_evicts_only_its_own() { use std::sync::atomic::{AtomicBool, Ordering}; let mut ca = config("a", "node-a"); ca.node_down_after_ms = 60_000; let (a, _ea) = start(ca); let addr = a.local_addr(); let delay = Duration::from_millis(50); let mut held = Vec::new(); assert!( slow_dial(&a, delay, 1, || { held.extend( (0..2 * MAX_UNAUTHENTICATED).map(|_| connect_from(2, addr).expect("A listens")), ); }), "a burst of connections from another host" ); drop(held); let stop = Arc::new(AtomicBool::new(false)); let flood = { let stop = stop.clone(); std::thread::spawn(move || { let mut held = std::collections::VecDeque::new(); let start = Instant::now(); let mut opened = 0u32; while !stop.load(Ordering::Relaxed) { let due = start + Duration::from_micros(500) * opened; std::thread::sleep(due.saturating_duration_since(Instant::now())); if let Ok(s) = connect_from(2, addr) { held.push_back(s); } opened += 1; if held.len() > 512 { held.pop_front(); } } }) }; std::thread::sleep(Duration::from_millis(200)); let connected = (0..3) .filter(|i| slow_dial(&a, delay, 10 + i, || ())) .count(); stop.store(true, Ordering::Relaxed); flood.join().expect("the flood"); assert_eq!(connected, 3, "under a steady flood from another host"); } /// A node with a certificate of the cluster's authority, but not for the /// name it claims, learns nothing from the refusal: code 4 whatever its /// cluster and schema (#404's security review, SEC-9: it learned whether it /// had guessed them). #[test] fn an_uncertified_name_is_refused_before_anything_else() { let (a, ea) = start(config("a", "node-a")); for (cluster, schema) in [("prod", SCHEMA), ("test", SCHEMA ^ 1), ("test", SCHEMA)] { let mut s = fake_dial(a.local_addr(), "node-impostor"); let mut h = hello(&name("b"), 1); h.cluster = cluster.into(); h.schema_hash = schema; put(&mut s, frame::HELLO, &h.encode()); ea.closed("the impostor", |r| *r == Reason::Name(name("b"))); let said = until_closed(&mut s); assert!( matches!(said.as_slice(), [(frame::REFUSE, body)] if body[0] == 4), "{cluster} {schema:x}: {said:?}" ); } } /// A node that connects again verifies its chain again: A issues no /// session ticket, so no handshake resumes (#404's security review, SEC-8: /// a resumed one skipped the certificate's dates for 24 h). #[test] fn every_connection_verifies_the_peer_again() { let (a, _ea) = start(config("a", "node-a")); let config = crate::tls::client_config(ClientOptions { authorities: authorities("ca.pem"), identity: Some(identity("node-b")), alpn: vec![frame::ALPN.to_vec()], tls13_only: true, insecure: false, }) .expect("a client configuration that would resume"); let mut kinds = Vec::new(); for incarnation in [1, 2] { let sock = TcpStream::connect(a.local_addr()).expect("A listens"); sock.set_read_timeout(Some(PATIENCE)).expect("a timeout"); let server = ServerName::try_from(name("a")).expect("a name"); let conn = ClientConnection::new(config.clone(), server).expect("a client"); let mut s = StreamOwned::new(conn, sock); put( &mut s, frame::HELLO, &hello(&name("b"), incarnation).encode(), ); assert!(get(&mut s).is_some_and(|(kind, _)| kind == frame::HELLO)); put(&mut s, frame::ACK, &[]); until("B up", || { a.peers().iter().any(|p| p.incarnation == incarnation) }); kinds.push(s.conn.handshake_kind()); // Tickets would arrive after the handshake: read them first. let _ = s.conn.complete_io(&mut s.sock); drop(s); until("B forgotten", || a.peers().is_empty()); } assert_eq!(kinds, [Some(rustls::HandshakeKind::Full); 2]); } #[test] fn throttled_lines_come_once_a_period_with_a_count() { let mut t = Throttle::default(); let now = Instant::now(); assert_eq!(t.admit(now), Some(0), "the first at once"); for i in 1..2_000 { assert_eq!(t.admit(now + Duration::from_micros(i)), None); } let later = now + Throttle::PERIOD; assert_eq!(t.admit(later), Some(1_999), "then how many were held back"); assert_eq!(t.admit(later), None); assert_eq!(Throttle::held_back(0), ""); } // ---- discovery ----------------------------------------------------------------------------- /// Node `n`, discovering a full mesh. fn mesh(n: &str) -> Config { let mut c = config(n, &format!("node-{n}")); c.mesh = true; c } /// [`mesh`], seeding node B at `b`. fn mesh_seeding(n: &str, b: &Transport) -> Config { let mut c = mesh(n); c.seeds = vec![(name("b"), b.local_addr())]; c } /// Wait until each of `names` came up, whatever else happens meanwhile. fn ups(events: &Events, what: &str, names: &[&str]) { let mut left: HashSet = names.iter().map(|n| name(n)).collect(); while !left.is_empty() { if let Ev::Up(n) = events.next(what) { left.remove(&n.name); } } } /// Wait until `n` goes down, whatever else happens meanwhile. fn down(events: &Events, what: &str, n: &str) { while !matches!(events.next(what), Ev::Down(d) if d.name == name(n)) {} } /// Whether `events` hold a connection to `n` closed (a dial that failed). fn dialed(events: &[Ev], n: &str) -> bool { events .iter() .any(|e| matches!(e, Ev::Closed(peer, _) if *peer == name(n))) } /// A list of peers, one frame's body. fn list(nodes: &[(&str, SocketAddr)]) -> Vec { let nodes: Vec<(String, SocketAddr)> = nodes.iter().map(|(n, a)| (name(n), *a)).collect(); let mut frames = Peers::frames(&nodes, 1 << 20); assert_eq!(frames.len(), 1); frames.remove(0) } /// The next list of peers a fake node gets. fn next_list(s: &mut impl Read) -> Peers { loop { let (kind, body) = get(s).expect("a list of peers"); if kind == frame::SIGNAL && body.first() == Some(&frame::PEERS) { return Peers::decode(&body[1..]).expect("a well-formed list"); } } } #[test] fn nodes_meet_the_nodes_their_peers_list() { // A and C each seed only B: B's lists make them meet, over one // connection. let (b, eb) = start(mesh("b")); let (a, ea) = start(mesh_seeding("a", &b)); let (c, ec) = start(mesh_seeding("c", &b)); ups(&ea, "A sees B and C", &["b", "c"]); ups(&ec, "C sees B and A", &["b", "a"]); ups(&eb, "B sees A and C", &["a", "c"]); until("one connection per pair", || { [&a, &b, &c].iter().all(|t| t.connections() == 2) }); let names = |t: &Transport| -> Vec { t.peers().into_iter().map(|p| p.name).collect() }; assert_eq!(names(&a), [name("b"), name("c")]); assert_eq!(names(&c), [name("a"), name("b")]); } #[test] fn without_discovery_only_seeds_are_dialed() { // B does not discover: it sends no list, so A and C, which do, never // learn of each other. Nor do they when none discovers. for b_meshes in [false, true] { let mut cb = mesh("b"); cb.mesh = b_meshes; let (b, _eb) = start(cb); let mut ca = mesh_seeding("a", &b); let mut cc = mesh_seeding("c", &b); ca.mesh = !b_meshes; cc.mesh = !b_meshes; let (_a, ea) = start(ca); let (_c, ec) = start(cc); ups(&ea, "A sees B", &["b"]); ups(&ec, "C sees B", &["b"]); let seen = ea.during(Duration::from_millis(1_000)); assert!( !seen.iter().any(|e| matches!(e, Ev::Up(_))), "B meshes: {b_meshes}: {seen:?}" ); } } #[test] fn a_lost_node_is_dialed_while_listed_then_forgotten() { let fast = |c: &mut Config| { c.heartbeat_ms = 50; c.node_down_after_ms = 400; }; let forget = Duration::from_millis(400) * FORGET_AFTER; let mut cb = mesh("b"); fast(&mut cb); let (b, eb) = start(cb); let mut ca = mesh_seeding("a", &b); fast(&mut ca); let (a, ea) = start(ca); let mut cc = mesh_seeding("c", &b); fast(&mut cc); let (c, ec) = start(cc); ups(&ea, "A sees B and C", &["b", "c"]); ups(&ec, "C sees B and A", &["b", "a"]); // C stops; back at its address, seeding nobody, it is dialed by both. let at = c.local_addr(); c.stop(); down(&ea, "A loses C", "c"); down(&eb, "B loses C", "c"); let mut cc = mesh("c"); fast(&mut cc); cc.listen = at; let (c, ec) = start(cc); ups(&ea, "A dials C again", &["c"]); ups(&eb, "B dials C again", &["c"]); ups(&ec, "C is dialed by A and B", &["a", "b"]); // C stops for good: A dials it until nobody listed it for a while, // then forgets it. c.stop(); down(&ea, "A loses C again", "c"); let meanwhile = ea.during(forget / 2); assert!(dialed(&meanwhile, "c"), "{meanwhile:?}"); let _ = ea.during(forget / 2 + Duration::from_millis(500)); let later = ea.during(Duration::from_secs(2)); assert!(!dialed(&later, "c"), "{later:?}"); // A seed is never forgotten. b.stop(); down(&ea, "A loses B", "b"); let _ = ea.during(forget + Duration::from_millis(500)); let later = ea.during(Duration::from_secs(2)); assert!(dialed(&later, "b"), "{later:?}"); drop(a); } #[test] fn a_listed_address_is_only_a_hint() { let (a, ea) = start(mesh("a")); let (c, ec) = start(mesh("c")); // B, a fake node that discovers, gets A's list: A's own address. let mut b = fake_up_with(&a, &ea, "b", 1, frame::FLAG_PEERS); let mine = next_list(&mut b); assert_eq!( mine, Peers { first: true, nodes: vec![(name("a"), a.local_addr())] } ); // It lists C where node B's certificate answers: A's dial is refused // at TLS, which checks the name A dials. let (wrong, impostor) = fake_listen("node-b", |_| {}); put(&mut b, frame::SIGNAL, &list(&[("c", wrong)])); let (peer, why) = ea.closed("A's dial refused", |r| matches!(r, Reason::Tls(_))); assert_eq!(peer, name("c")); assert!(why.to_string().contains("not valid for name"), "{why}"); impostor.join().expect("the impostor"); // No lockout: a list with C's real address replaces the hint. put(&mut b, frame::SIGNAL, &list(&[("c", c.local_addr())])); ups(&ea, "A dials C", &["c"]); ups(&ec, "C sees A", &["a"]); // B now gets C in A's list, at the address the dial confirmed. loop { let list = next_list(&mut b); if list.nodes.len() == 2 { assert_eq!(list.nodes[1], (name("c"), c.local_addr())); break; } } // Which no other peer's list replaces: C, back at its address after // a stop, is dialed there, not at the one B lists. put( &mut b, frame::SIGNAL, &list(&[("c", "127.0.0.1:1".parse().unwrap())]), ); let at = c.local_addr(); c.stop(); down(&ea, "A loses C", "c"); let mut cc = mesh("c"); cc.listen = at; let (_c, ec) = start(cc); ups(&ea, "A dials C again", &["c"]); ups(&ec, "C sees A again", &["a"]); assert_eq!(report(&a, "b").dropped, 0); } #[test] fn lists_go_only_between_nodes_that_discover() { let listed = |z: SocketAddr| list(&[("z", z)]); let nowhere: SocketAddr = "127.0.0.1:1".parse().unwrap(); // A discovers; B does not say it does: B's list is dropped and // counted, Z is not dialed, and A sends B no list. let (a, ea) = start(mesh("a")); let mut b = fake_up_as(&a, &ea, "b", 1); put(&mut b, frame::SIGNAL, &listed(nowhere)); until("B's list dropped", || report(&a, "b").dropped == 1); let seen = ea.during(Duration::from_millis(300)); assert!(!dialed(&seen, "z"), "{seen:?}"); // Nor does A take one malformed (its count, say, past what its bytes // hold): the connection stays up. let mut d = fake_up_with(&a, &ea, "c", 1, frame::FLAG_PEERS); put(&mut d, frame::SIGNAL, &[frame::PEERS, 1, 1, 0, 0]); put(&mut d, frame::SIGNAL, &[frame::PEERS, 1, 0xff, 0xff]); until("C's lists dropped", || report(&a, "c").dropped == 2); put(&mut d, frame::HEARTBEAT, &7u64.to_le_bytes()); loop { let (kind, body) = get(&mut d).expect("A still up with C"); if kind == frame::ECHO { assert_eq!(body, 7u64.to_le_bytes()); break; } } b.sock .set_read_timeout(Some(Duration::from_millis(500))) .expect("a timeout"); let to_b = until_closed(&mut b); assert!( to_b.iter().all(|(kind, _)| *kind != frame::SIGNAL), "{to_b:?}" ); // A does not discover: a list from a node that does is dropped. let (x, ex) = start(config("x", "node-impostor")); let mut b = fake_up_with(&x, &ex, "b", 1, frame::FLAG_PEERS); put(&mut b, frame::SIGNAL, &listed(nowhere)); until("B's list dropped by X", || report(&x, "b").dropped == 1); } // Second security review of #404 (dist/secreview2): confirming tests. mod secreview2;