
louise
Clone avec HTTPS, un jeton personnel en mot de passe, ou avec SSH, une clé ajoutée dans vos paramètres.
Dernier runRéussi#1203 · main · 9 min 56 s
1Étoiles
0Forks
0Issues
| 1 | //! Transports on 127.0.0.1, in-process, with channel sinks for what they |
| 2 | //! deliver; fake peers (blocking rustls streams written by hand) for what |
| 3 | //! a real node never sends. Certificates: `crates/louise/tests/fixtures/ |
| 4 | //! tls`, nodes `node-{a,b,c}.cluster.test` (`make-certs.sh nodes`). |
| 5 | |
| 6 | use std::collections::HashSet; |
| 7 | use std::io::{Read, Write}; |
| 8 | use std::net::{SocketAddr, TcpListener, TcpStream}; |
| 9 | use std::sync::mpsc::{Receiver, RecvTimeoutError, Sender, channel}; |
| 10 | use std::sync::{Arc, Mutex}; |
| 11 | use std::thread::JoinHandle; |
| 12 | use std::time::{Duration, Instant}; |
| 13 | |
| 14 | use louise_rt_prims::wire::MessageHeader; |
| 15 | use rustls::pki_types::ServerName; |
| 16 | use rustls::{ClientConnection, ServerConnection, StreamOwned}; |
| 17 | |
| 18 | use super::frame::{self, Hello, Peers}; |
| 19 | use super::thread::FORGET_AFTER; |
| 20 | use super::{ |
| 21 | Config, Inbound, MAX_UNAUTHENTICATED, MAX_UNAUTHENTICATED_PER_SOURCE, Node, Outbound, |
| 22 | PeerStats, Reason, Report, SendError, Stats, Throttle, Transport, Waiter, |
| 23 | }; |
| 24 | use crate::tls::{Authorities, ClientOptions, Identity, ServerOptions}; |
| 25 | |
| 26 | /// How long anything expected may take: generous, the tests never wait it |
| 27 | /// out when they pass. |
| 28 | const PATIENCE: Duration = Duration::from_secs(10); |
| 29 | const SCHEMA: u64 = 0x5eed_1a7e; |
| 30 | |
| 31 | fn fixture(name: &str) -> String { |
| 32 | format!( |
| 33 | "{}/../../crates/louise/tests/fixtures/tls/{name}", |
| 34 | env!("CARGO_MANIFEST_DIR") |
| 35 | ) |
| 36 | } |
| 37 | |
| 38 | fn name(n: &str) -> String { |
| 39 | format!("node-{n}.cluster.test") |
| 40 | } |
| 41 | |
| 42 | /// Node `n` with certificate `cert`: fast heartbeats, quick reconnection. |
| 43 | fn config(n: &str, cert: &str) -> Config { |
| 44 | let mut c = Config::new(&name(n), "test", "127.0.0.1:0".parse().expect("an address")); |
| 45 | c.cert_file = fixture(&format!("{cert}.pem")); |
| 46 | c.key_file = fixture(&format!("{cert}.key")); |
| 47 | c.ca_files = vec![fixture("ca.pem")]; |
| 48 | c.schema_hash = SCHEMA; |
| 49 | c.heartbeat_ms = 100; |
| 50 | c.node_down_after_ms = 3_000; |
| 51 | c.reconnect_ms = 50; |
| 52 | c |
| 53 | } |
| 54 | |
| 55 | // ---- the sink --------------------------------------------------------------------------- |
| 56 | |
| 57 | #[derive(Clone, Debug, PartialEq)] |
| 58 | enum Ev { |
| 59 | Up(Node), |
| 60 | Down(Node), |
| 61 | Message(Node, MessageHeader, Vec<u8>), |
| 62 | Signal(Node, Vec<u8>), |
| 63 | Drained(Node, Vec<Waiter>), |
| 64 | Closed(String, Reason), |
| 65 | /// Sent before the `Closed` of a dial to an address only lists gave. |
| 66 | Hearsay(String), |
| 67 | } |
| 68 | |
| 69 | struct Sink(Mutex<Sender<Ev>>); |
| 70 | |
| 71 | impl Sink { |
| 72 | fn send(&self, e: Ev) { |
| 73 | // The test may be over: nobody listens. |
| 74 | let _ = self.0.lock().expect("the sink").send(e); |
| 75 | } |
| 76 | } |
| 77 | |
| 78 | impl Inbound for Sink { |
| 79 | fn node_up(&self, peer: &Node) { |
| 80 | self.send(Ev::Up(peer.clone())); |
| 81 | } |
| 82 | fn node_down(&self, peer: &Node) { |
| 83 | self.send(Ev::Down(peer.clone())); |
| 84 | } |
| 85 | fn message(&self, from: &Node, header: &MessageHeader, payload: &[u8]) { |
| 86 | self.send(Ev::Message(from.clone(), *header, payload.to_vec())); |
| 87 | } |
| 88 | fn signal(&self, from: &Node, body: &[u8]) { |
| 89 | self.send(Ev::Signal(from.clone(), body.to_vec())); |
| 90 | } |
| 91 | fn drained(&self, peer: &Node, waiters: &[Waiter]) { |
| 92 | self.send(Ev::Drained(peer.clone(), waiters.to_vec())); |
| 93 | } |
| 94 | fn closed(&self, peer: &str, reason: &Reason, hearsay: bool) { |
| 95 | if hearsay { |
| 96 | self.send(Ev::Hearsay(peer.to_owned())); |
| 97 | } |
| 98 | self.send(Ev::Closed(peer.to_owned(), reason.clone())); |
| 99 | } |
| 100 | } |
| 101 | |
| 102 | struct Events(Receiver<Ev>); |
| 103 | |
| 104 | impl Events { |
| 105 | fn next(&self, what: &str) -> Ev { |
| 106 | match self.0.recv_timeout(PATIENCE) { |
| 107 | Ok(e) => e, |
| 108 | Err(RecvTimeoutError::Timeout) => panic!("still waiting: {what}"), |
| 109 | Err(RecvTimeoutError::Disconnected) => panic!("the transport is gone: {what}"), |
| 110 | } |
| 111 | } |
| 112 | |
| 113 | /// The first event `want` picks; the others before it must not be a |
| 114 | /// node coming up or going down, unless `want` takes it. |
| 115 | fn wait<T>(&self, what: &str, want: impl Fn(&Ev) -> Option<T>) -> T { |
| 116 | loop { |
| 117 | let e = self.next(what); |
| 118 | if let Some(t) = want(&e) { |
| 119 | return t; |
| 120 | } |
| 121 | assert!( |
| 122 | matches!(e, Ev::Closed(..) | Ev::Hearsay(_)), |
| 123 | "{e:?} while waiting for {what}" |
| 124 | ); |
| 125 | } |
| 126 | } |
| 127 | |
| 128 | fn up(&self, what: &str) -> Node { |
| 129 | self.wait(what, |e| match e { |
| 130 | Ev::Up(n) => Some(n.clone()), |
| 131 | _ => None, |
| 132 | }) |
| 133 | } |
| 134 | |
| 135 | fn closed(&self, what: &str, want: impl Fn(&Reason) -> bool) -> (String, Reason) { |
| 136 | self.wait(what, |e| match e { |
| 137 | Ev::Closed(peer, r) if want(r) => Some((peer.clone(), r.clone())), |
| 138 | _ => None, |
| 139 | }) |
| 140 | } |
| 141 | |
| 142 | /// The events of the next `period`. |
| 143 | fn during(&self, period: Duration) -> Vec<Ev> { |
| 144 | let until = Instant::now() + period; |
| 145 | let mut seen = Vec::new(); |
| 146 | while let Some(left) = until.checked_duration_since(Instant::now()) { |
| 147 | match self.0.recv_timeout(left) { |
| 148 | Ok(e) => seen.push(e), |
| 149 | Err(_) => break, |
| 150 | } |
| 151 | } |
| 152 | seen |
| 153 | } |
| 154 | } |
| 155 | |
| 156 | fn start(config: Config) -> (Transport, Events) { |
| 157 | let (tx, rx) = channel(); |
| 158 | let transport = |
| 159 | Transport::start(config, Arc::new(Sink(Mutex::new(tx)))).expect("the transport starts"); |
| 160 | (transport, Events(rx)) |
| 161 | } |
| 162 | |
| 163 | /// A message frame for `to`: `serial` names the message. |
| 164 | fn message(to: &Node, serial: u64, payload: &[u8]) -> Vec<u8> { |
| 165 | let header = MessageHeader { |
| 166 | incarnation: to.incarnation, |
| 167 | serial, |
| 168 | tag: 1, |
| 169 | type_hash: 9, |
| 170 | payload_len: payload.len() as u32, |
| 171 | }; |
| 172 | [&header.encode()[..], payload].concat() |
| 173 | } |
| 174 | |
| 175 | /// Wait until `f` holds. |
| 176 | fn until(what: &str, f: impl Fn() -> bool) { |
| 177 | let limit = Instant::now() + PATIENCE; |
| 178 | while !f() { |
| 179 | assert!(Instant::now() < limit, "still waiting: {what}"); |
| 180 | std::thread::sleep(Duration::from_millis(5)); |
| 181 | } |
| 182 | } |
| 183 | |
| 184 | /// What `t` reports of node `n`. |
| 185 | fn report(t: &Transport, n: &str) -> Report { |
| 186 | t.report() |
| 187 | .into_iter() |
| 188 | .find(|r| r.node == name(n)) |
| 189 | .unwrap_or_else(|| panic!("no report of {n}: {:?}", t.report())) |
| 190 | } |
| 191 | |
| 192 | /// A and B, B dialing A: both up. |
| 193 | fn pair(a: Config, mut b: Config) -> ((Transport, Events), (Transport, Events)) { |
| 194 | let (ta, ea) = start(a); |
| 195 | b.seeds = vec![(name("a"), ta.local_addr())]; |
| 196 | let (tb, eb) = start(b); |
| 197 | assert_eq!(ea.up("A sees B").name, name("b")); |
| 198 | assert_eq!(eb.up("B sees A").name, name("a")); |
| 199 | ((ta, ea), (tb, eb)) |
| 200 | } |
| 201 | |
| 202 | // ---- fake peers ---------------------------------------------------------------------------- |
| 203 | |
| 204 | fn authorities(ca: &str) -> Authorities { |
| 205 | Authorities { |
| 206 | default_roots: false, |
| 207 | pems: Vec::new(), |
| 208 | files: vec![fixture(ca)], |
| 209 | } |
| 210 | } |
| 211 | |
| 212 | fn identity(cert: &str) -> Identity { |
| 213 | Identity { |
| 214 | cert_file: fixture(&format!("{cert}.pem")), |
| 215 | key_file: fixture(&format!("{cert}.key")), |
| 216 | } |
| 217 | } |
| 218 | |
| 219 | type Dialer = StreamOwned<ClientConnection, TcpStream>; |
| 220 | type Dialed = StreamOwned<ServerConnection, TcpStream>; |
| 221 | |
| 222 | /// A fake node with certificate `cert` dialing `addr` (node A), TLS done |
| 223 | /// as far as the client sees it. |
| 224 | fn fake_dial(addr: SocketAddr, cert: &str) -> Dialer { |
| 225 | fake_dial_to(addr, &name("a"), cert) |
| 226 | } |
| 227 | |
| 228 | /// [`fake_dial`] to node `node` at `addr`. |
| 229 | fn fake_dial_to(addr: SocketAddr, node: &str, cert: &str) -> Dialer { |
| 230 | let config = crate::tls::client_config(ClientOptions { |
| 231 | authorities: authorities("ca.pem"), |
| 232 | identity: Some(identity(cert)), |
| 233 | alpn: vec![frame::ALPN.to_vec()], |
| 234 | tls13_only: true, |
| 235 | insecure: false, |
| 236 | }) |
| 237 | .expect("a client configuration"); |
| 238 | let sock = TcpStream::connect(addr).expect("A listens"); |
| 239 | sock.set_read_timeout(Some(PATIENCE)).expect("a timeout"); |
| 240 | let server = ServerName::try_from(node.to_owned()).expect("a name"); |
| 241 | let conn = ClientConnection::new(config, server).expect("a client"); |
| 242 | let mut s = StreamOwned::new(conn, sock); |
| 243 | // A refusing the client certificate shows on a later read. |
| 244 | let _ = s.conn.complete_io(&mut s.sock); |
| 245 | s |
| 246 | } |
| 247 | |
| 248 | /// A fake node with certificate `cert` that A can dial: `then` runs with |
| 249 | /// the first connection, TLS done (or failed) on its side. |
| 250 | fn fake_listen( |
| 251 | cert: &str, |
| 252 | then: impl FnOnce(&mut Dialed) + Send + 'static, |
| 253 | ) -> (SocketAddr, JoinHandle<()>) { |
| 254 | let config = crate::tls::server_config(ServerOptions { |
| 255 | identity: identity(cert), |
| 256 | client_authorities: Some(authorities("ca.pem")), |
| 257 | alpn: vec![frame::ALPN.to_vec()], |
| 258 | tls13_only: true, |
| 259 | peers: true, |
| 260 | }) |
| 261 | .expect("a server configuration"); |
| 262 | let listener = TcpListener::bind("127.0.0.1:0").expect("a port"); |
| 263 | let addr = listener.local_addr().expect("its address"); |
| 264 | let thread = std::thread::spawn(move || { |
| 265 | let (sock, _) = listener.accept().expect("A dials"); |
| 266 | sock.set_read_timeout(Some(PATIENCE)).expect("a timeout"); |
| 267 | let conn = ServerConnection::new(config).expect("a server"); |
| 268 | let mut s = StreamOwned::new(conn, sock); |
| 269 | let _ = s.conn.complete_io(&mut s.sock); |
| 270 | then(&mut s); |
| 271 | }); |
| 272 | (addr, thread) |
| 273 | } |
| 274 | |
| 275 | fn hello(node: &str, incarnation: u64) -> Hello { |
| 276 | Hello { |
| 277 | version: frame::VERSION, |
| 278 | flags: 0, |
| 279 | incarnation, |
| 280 | schema_hash: SCHEMA, |
| 281 | max_frame: 1 << 20, |
| 282 | cluster: "test".into(), |
| 283 | node: node.into(), |
| 284 | } |
| 285 | } |
| 286 | |
| 287 | fn put(s: &mut impl Write, kind: u8, body: &[u8]) { |
| 288 | let len = (1 + body.len()) as u32; |
| 289 | let frame = [&len.to_le_bytes()[..], &[kind], body].concat(); |
| 290 | // A peer that closed shows on the next read. |
| 291 | let _ = s.write_all(&frame).and_then(|()| s.flush()); |
| 292 | } |
| 293 | |
| 294 | /// The next frame, or `None` once the connection is closed. |
| 295 | fn get(s: &mut impl Read) -> Option<(u8, Vec<u8>)> { |
| 296 | let mut len = [0; 4]; |
| 297 | s.read_exact(&mut len).ok()?; |
| 298 | let mut frame = vec![0; u32::from_le_bytes(len) as usize]; |
| 299 | s.read_exact(&mut frame).ok()?; |
| 300 | let (kind, body) = frame.split_first()?; |
| 301 | Some((*kind, body.to_vec())) |
| 302 | } |
| 303 | |
| 304 | /// Read until the connection closes: what it said last. |
| 305 | fn until_closed(s: &mut impl Read) -> Vec<(u8, Vec<u8>)> { |
| 306 | std::iter::from_fn(|| get(s)).collect() |
| 307 | } |
| 308 | |
| 309 | /// A fake node B through the handshake with A, as the dialer. |
| 310 | fn fake_up(a: &Transport, events: &Events, incarnation: u64) -> Dialer { |
| 311 | fake_up_as(a, events, "b", incarnation) |
| 312 | } |
| 313 | |
| 314 | /// A fake node `n` (`node-n` certificate) through the handshake with A. |
| 315 | fn fake_up_as(a: &Transport, events: &Events, n: &str, incarnation: u64) -> Dialer { |
| 316 | fake_up_with(a, events, n, incarnation, 0) |
| 317 | } |
| 318 | |
| 319 | /// [`fake_up_as`], its hello setting `flags`. |
| 320 | fn fake_up_with(a: &Transport, events: &Events, n: &str, incarnation: u64, flags: u64) -> Dialer { |
| 321 | let mut s = fake_dial_to(a.local_addr(), &a.me().name, &format!("node-{n}")); |
| 322 | let mut ours = hello(&name(n), incarnation); |
| 323 | ours.flags = flags; |
| 324 | put(&mut s, frame::HELLO, &ours.encode()); |
| 325 | let (kind, body) = get(&mut s).expect("A's hello"); |
| 326 | assert_eq!(kind, frame::HELLO); |
| 327 | let theirs = Hello::decode(&body).expect("a hello"); |
| 328 | assert_eq!( |
| 329 | (theirs.node.as_str(), theirs.incarnation), |
| 330 | (a.me().name.as_str(), a.me().incarnation) |
| 331 | ); |
| 332 | // Every op flag: a node takes every op family it knows. |
| 333 | assert_eq!(theirs.flags & frame::FLAGS_OPS, frame::FLAGS_OPS); |
| 334 | put(&mut s, frame::ACK, &[]); |
| 335 | let up = events.up("the fake node is up"); |
| 336 | assert_eq!( |
| 337 | up, |
| 338 | Node { |
| 339 | name: name(n), |
| 340 | incarnation |
| 341 | } |
| 342 | ); |
| 343 | s |
| 344 | } |
| 345 | |
| 346 | // ---- tests ------------------------------------------------------------------------------------ |
| 347 | |
| 348 | #[test] |
| 349 | fn configurations_are_checked_at_start() { |
| 350 | let refused = |f: &dyn Fn(&mut Config)| { |
| 351 | let mut c = config("a", "node-a"); |
| 352 | f(&mut c); |
| 353 | let (tx, _rx) = channel(); |
| 354 | Transport::start(c, Arc::new(Sink(Mutex::new(tx)))) |
| 355 | .err() |
| 356 | .unwrap_or_default() |
| 357 | }; |
| 358 | assert!(refused(&|c| c.node = "Node-A".into()).contains("not a lowercase DNS name")); |
| 359 | assert!(refused(&|c| c.cluster = String::new()).contains("cluster name")); |
| 360 | assert!(refused(&|c| c.ca_files.clear()).contains("no cluster authority")); |
| 361 | assert!(refused(&|c| c.max_frame = 10).contains("max_frame")); |
| 362 | assert!(refused(&|c| c.max_peers = 0).contains("max_peers")); |
| 363 | assert!(refused(&|c| c.max_peers = 4097).contains("max_peers")); |
| 364 | assert!(refused(&|c| c.node_down_after_ms = c.heartbeat_ms).contains("node_down_after_ms")); |
| 365 | assert!(refused(&|c| c.node_down_after_ms = u64::MAX).contains("a day")); |
| 366 | assert!(refused(&|c| c.reconnect_ms = u64::MAX).contains("a day")); |
| 367 | assert!( |
| 368 | refused(&|c| c.seeds = vec![(name("a"), "127.0.0.1:1".parse().expect("an address"))]) |
| 369 | .contains("is this node") |
| 370 | ); |
| 371 | // A certificate that is not the node's. |
| 372 | let e = refused(&|c| c.node = name("b")); |
| 373 | assert!(e.contains("not valid for the node name"), "{e}"); |
| 374 | let e = refused(&|c| c.cert_file = fixture("nonexistent.pem")); |
| 375 | assert!(e.contains("nonexistent.pem"), "{e}"); |
| 376 | assert_eq!(refused(&|_| {}), "", "the fixture configuration starts"); |
| 377 | } |
| 378 | |
| 379 | #[test] |
| 380 | fn frames_flow_in_order_both_ways() { |
| 381 | let ((a, ea), (b, eb)) = pair(config("a", "node-a"), config("b", "node-b")); |
| 382 | let (to_a, to_b) = (a.me().clone(), b.me().clone()); |
| 383 | assert_eq!(a.peers(), std::slice::from_ref(&to_b)); |
| 384 | assert_eq!(b.peers(), std::slice::from_ref(&to_a)); |
| 385 | // Messages and signals interleaved, small and large (a frame of 1 MiB |
| 386 | // is written in many pieces). |
| 387 | let frames = |_: &Node| -> Vec<(bool, u64, Vec<u8>)> { |
| 388 | (0..300u64) |
| 389 | .map(|i| match i { |
| 390 | 150 => (true, i, vec![0xab; 1 << 20]), |
| 391 | // A signal starts with its op: one the handler takes, not |
| 392 | // the transport's own (`frame::PEERS`). |
| 393 | _ if i % 7 == 0 => (false, i, [&[0x10][..], &i.to_le_bytes()].concat()), |
| 394 | _ => (true, i, vec![i as u8; (i % 100) as usize]), |
| 395 | }) |
| 396 | .collect() |
| 397 | }; |
| 398 | let send = |t: &Transport, to: &Node| { |
| 399 | for (is_message, i, payload) in frames(to) { |
| 400 | let frame = if is_message { |
| 401 | Outbound::Message(message(to, i, &payload)) |
| 402 | } else { |
| 403 | Outbound::Signal(payload) |
| 404 | }; |
| 405 | t.send(to, frame).expect("queued"); |
| 406 | } |
| 407 | }; |
| 408 | std::thread::scope(|s| { |
| 409 | s.spawn(|| send(&a, &to_b)); |
| 410 | s.spawn(|| send(&b, &to_a)); |
| 411 | }); |
| 412 | for (events, from, me) in [(&eb, &to_a, &to_b), (&ea, &to_b, &to_a)] { |
| 413 | for (is_message, i, payload) in frames(me) { |
| 414 | let want = if is_message { |
| 415 | let header = MessageHeader { |
| 416 | incarnation: me.incarnation, |
| 417 | serial: i, |
| 418 | tag: 1, |
| 419 | type_hash: 9, |
| 420 | payload_len: payload.len() as u32, |
| 421 | }; |
| 422 | Ev::Message(from.clone(), header, payload) |
| 423 | } else { |
| 424 | Ev::Signal(from.clone(), payload) |
| 425 | }; |
| 426 | let got = events.next("the next frame"); |
| 427 | assert!(got == want, "frame {i} out of order: {got:?}"); |
| 428 | } |
| 429 | } |
| 430 | // Counted on both sides; heartbeats and their echoes give a round-trip |
| 431 | // time. |
| 432 | let messages = frames(&to_a).iter().filter(|f| f.0).count() as u64; |
| 433 | until("A's round trip to B", || report(&a, "b").rtt_us.is_some()); |
| 434 | let seen = report(&a, "b"); |
| 435 | assert_eq!( |
| 436 | (seen.up, seen.incarnation, seen.queued), |
| 437 | (true, Some(to_b.incarnation), 0) |
| 438 | ); |
| 439 | assert_eq!( |
| 440 | (seen.sent, seen.received, seen.unsent, seen.dropped), |
| 441 | (messages, messages, 0, 0) |
| 442 | ); |
| 443 | // What `send` refuses. |
| 444 | let stranger = Node { |
| 445 | name: name("c"), |
| 446 | incarnation: 1, |
| 447 | }; |
| 448 | let old_b = Node { |
| 449 | incarnation: to_b.incarnation ^ 1, |
| 450 | ..to_b.clone() |
| 451 | }; |
| 452 | assert_eq!( |
| 453 | a.send(&stranger, Outbound::Signal(vec![1])), |
| 454 | Err(SendError::NotConnected) |
| 455 | ); |
| 456 | assert_eq!( |
| 457 | a.send(&old_b, Outbound::Signal(vec![1])), |
| 458 | Err(SendError::NotConnected), |
| 459 | "another incarnation" |
| 460 | ); |
| 461 | assert_eq!( |
| 462 | a.send(&to_b, Outbound::Signal(vec![0; 8 << 20])), |
| 463 | Err(SendError::TooLarge), |
| 464 | "over B's limit" |
| 465 | ); |
| 466 | let mut short = message(&to_b, 1, b"abc"); |
| 467 | short.pop(); |
| 468 | assert_eq!( |
| 469 | a.send(&to_b, Outbound::Message(short)), |
| 470 | Err(SendError::Malformed) |
| 471 | ); |
| 472 | assert_eq!( |
| 473 | a.send(&to_b, Outbound::Message(message(&old_b, 1, b""))), |
| 474 | Err(SendError::Malformed), |
| 475 | "a header for another incarnation" |
| 476 | ); |
| 477 | assert_eq!(a.connections(), 1); |
| 478 | b.stop(); |
| 479 | let down = ea.wait("B down", |e| match e { |
| 480 | Ev::Down(n) => Some(n.clone()), |
| 481 | _ => None, |
| 482 | }); |
| 483 | assert_eq!(down, to_b); |
| 484 | assert_eq!(a.peers(), []); |
| 485 | assert_eq!(a.dropped(), 0); |
| 486 | let seen = report(&a, "b"); |
| 487 | assert_eq!( |
| 488 | (seen.up, seen.incarnation, seen.rtt_us, seen.sent), |
| 489 | (false, Some(to_b.incarnation), None, messages), |
| 490 | "kept once down" |
| 491 | ); |
| 492 | } |
| 493 | |
| 494 | /// Message frames of 1 KiB of payload for `to`, from `first` on, until |
| 495 | /// the queue is full: the one it gave back, and how many it took. |
| 496 | fn fill(a: &Transport, to: &Node, first: u64, waiter: Option<Waiter>) -> (Outbound, u64) { |
| 497 | let payload = vec![0; 1 << 10]; |
| 498 | for i in first..first + 100_000 { |
| 499 | match a.queue(to, Outbound::Message(message(to, i, &payload)), waiter) { |
| 500 | Ok(()) => {} |
| 501 | Err((SendError::Full, frame)) => return (frame, i - first), |
| 502 | Err((e, _)) => panic!("{e:?}"), |
| 503 | } |
| 504 | } |
| 505 | panic!("the queue never filled"); |
| 506 | } |
| 507 | |
| 508 | /// Read `s` until `n` message frames came: the serials, in order. |
| 509 | fn read_messages(s: &mut impl Read, n: u64) -> Vec<u64> { |
| 510 | let mut serials = Vec::new(); |
| 511 | while serials.len() < n as usize { |
| 512 | let (kind, body) = get(s).expect("a frame"); |
| 513 | if kind == frame::MESSAGE { |
| 514 | serials.push(u64::from_le_bytes(body[8..16].try_into().expect("8 bytes"))); |
| 515 | } |
| 516 | } |
| 517 | serials |
| 518 | } |
| 519 | |
| 520 | #[test] |
| 521 | fn a_full_queue_gives_messages_back_and_wakes_its_waiters() { |
| 522 | let mut ca = config("a", "node-a"); |
| 523 | ca.max_queue = 4 << 10; |
| 524 | ca.node_down_after_ms = 60_000; |
| 525 | // A peer that reads nothing yet: once the sockets' buffers are full, |
| 526 | // nothing leaves A's queue. |
| 527 | let (a, ea) = start(ca); |
| 528 | let mut fake = fake_up(&a, &ea, 7); |
| 529 | let b = Node { |
| 530 | name: name("b"), |
| 531 | incarnation: 7, |
| 532 | }; |
| 533 | // An empty queue takes a message over `max_queue`. |
| 534 | a.send(&b, Outbound::Message(message(&b, 0, &[0; 4 << 10]))) |
| 535 | .expect("an empty queue takes any message"); |
| 536 | until("the thread takes it", || report(&a, "b").queued == 0); |
| 537 | let first = Waiter { pid: 5, wait: 1 }; |
| 538 | let (back, taken) = fill(&a, &b, 1, Some(first)); |
| 539 | let serial = |frame: &Outbound| match frame { |
| 540 | Outbound::Message(body) => u64::from_le_bytes(body[8..16].try_into().expect("8 bytes")), |
| 541 | Outbound::Request(_) | Outbound::Signal(_) => panic!("a signal"), |
| 542 | }; |
| 543 | assert_eq!(serial(&back), 1 + taken, "given back"); |
| 544 | let seen = report(&a, "b"); |
| 545 | assert!(seen.queued <= 4 << 10, "bounded: {seen:?}"); |
| 546 | assert_eq!(seen.parked, 1, "one waiter registered"); |
| 547 | assert_eq!( |
| 548 | a.send(&b, Outbound::Signal(vec![1])), |
| 549 | Ok(()), |
| 550 | "signals pass" |
| 551 | ); |
| 552 | // The peer reads: the thread takes the queue, and wakes the waiter, |
| 553 | // once. It sends its message then, after the others. |
| 554 | let reader = std::thread::spawn(move || { |
| 555 | let serials = read_messages(&mut fake, 1 + taken); |
| 556 | (fake, serials) |
| 557 | }); |
| 558 | let drained = ea.wait("the waiter woken", |e| match e { |
| 559 | Ev::Drained(n, w) => Some((n.clone(), w.clone())), |
| 560 | _ => None, |
| 561 | }); |
| 562 | assert_eq!(drained, (b.clone(), vec![first])); |
| 563 | let (mut fake, serials) = reader.join().expect("the reader"); |
| 564 | assert_eq!(serials, (0..1 + taken).collect::<Vec<_>>(), "in order"); |
| 565 | a.queue(&b, back, None) |
| 566 | .map_err(|(e, _)| e) |
| 567 | .expect("room now"); |
| 568 | assert_eq!(read_messages(&mut fake, 1), [1 + taken]); |
| 569 | // Full again, until the sockets' buffers are too: nothing leaves for |
| 570 | // 100 ms. |
| 571 | let mut next = 2 + taken; |
| 572 | let mut idle = 0; |
| 573 | while idle < 100 { |
| 574 | let (_, more) = fill(&a, &b, next, None); |
| 575 | next += more; |
| 576 | if more == 0 { |
| 577 | idle += 1; |
| 578 | std::thread::sleep(Duration::from_millis(1)); |
| 579 | } else { |
| 580 | idle = 0; |
| 581 | } |
| 582 | } |
| 583 | // A waiter forgotten (an exited sender), then another: the node going |
| 584 | // down wakes the one left, the queued messages unsent. |
| 585 | let gone = Waiter { pid: 6, wait: 1 }; |
| 586 | assert_eq!(fill(&a, &b, next, Some(gone)).1, 0); |
| 587 | assert_eq!( |
| 588 | a.send(&b, Outbound::Request(vec![0x20; 1 << 10])), |
| 589 | Err(SendError::Full), |
| 590 | "a spawn request counts as a message does" |
| 591 | ); |
| 592 | a.unwait(&b, gone); |
| 593 | let last = Waiter { pid: 6, wait: 2 }; |
| 594 | let (back, _) = fill(&a, &b, next, Some(last)); |
| 595 | drop(fake); |
| 596 | let drained = ea.wait("the waiter woken by the loss", |e| match e { |
| 597 | Ev::Drained(n, w) => Some((n.clone(), w.clone())), |
| 598 | _ => None, |
| 599 | }); |
| 600 | assert_eq!(drained, (b.clone(), vec![last])); |
| 601 | // The loss's `closed` and `node_down` come through the relay, after |
| 602 | // the wake. |
| 603 | let down = ea.wait("B down", |e| match e { |
| 604 | Ev::Down(n) => Some(n.clone()), |
| 605 | _ => None, |
| 606 | }); |
| 607 | assert_eq!(down, b); |
| 608 | assert_eq!( |
| 609 | a.queue(&b, back, Some(last)).map_err(|(e, _)| e), |
| 610 | Err(SendError::NotConnected) |
| 611 | ); |
| 612 | let seen = report(&a, "b"); |
| 613 | assert!(!seen.up && seen.unsent > 0, "{seen:?}"); |
| 614 | assert!(seen.sent >= 2 + taken, "{seen:?}"); |
| 615 | assert_eq!(seen.parked, 3, "{seen:?}"); |
| 616 | } |
| 617 | |
| 618 | #[test] |
| 619 | fn heartbeats_overtake_a_long_queue() { |
| 620 | let mut ca = config("a", "node-a"); |
| 621 | ca.node_down_after_ms = 60_000; |
| 622 | let (a, ea) = start(ca); |
| 623 | let mut fake = fake_up(&a, &ea, 7); |
| 624 | let b = Node { |
| 625 | name: name("b"), |
| 626 | incarnation: 7, |
| 627 | }; |
| 628 | // 32 MiB queued while the peer reads nothing: more than the sockets' |
| 629 | // buffers take, so most of it waits in A while heartbeats come due. |
| 630 | const N: u64 = 8 << 10; |
| 631 | for i in 0..N { |
| 632 | a.send(&b, Outbound::Message(message(&b, i, &[0; 4 << 10]))) |
| 633 | .expect("queued"); |
| 634 | } |
| 635 | std::thread::sleep(Duration::from_millis(500)); |
| 636 | let (mut messages, mut overtaken) = (0, None); |
| 637 | while messages < N { |
| 638 | let (kind, body) = get(&mut fake).expect("a frame"); |
| 639 | match kind { |
| 640 | frame::MESSAGE => { |
| 641 | assert_eq!(body[8..16], messages.to_le_bytes(), "in order"); |
| 642 | messages += 1; |
| 643 | } |
| 644 | frame::HEARTBEAT => { |
| 645 | if messages > 0 && overtaken.is_none() { |
| 646 | overtaken = Some(messages); |
| 647 | } |
| 648 | put(&mut fake, frame::ECHO, &body); |
| 649 | } |
| 650 | other => panic!("frame kind {other}"), |
| 651 | } |
| 652 | } |
| 653 | let overtaken = overtaken.expect("a heartbeat among the messages"); |
| 654 | assert!(overtaken < N / 2, "a heartbeat after {overtaken} messages"); |
| 655 | until("a round-trip time", || report(&a, "b").rtt_us.is_some()); |
| 656 | // A answers the peer's heartbeats with their stamp. |
| 657 | put(&mut fake, frame::HEARTBEAT, &[1, 2, 3, 4, 5, 6, 7, 8]); |
| 658 | loop { |
| 659 | match get(&mut fake).expect("a frame") { |
| 660 | (frame::ECHO, body) => break assert_eq!(body, [1, 2, 3, 4, 5, 6, 7, 8]), |
| 661 | (frame::HEARTBEAT, _) => {} |
| 662 | (other, _) => panic!("frame kind {other}"), |
| 663 | } |
| 664 | } |
| 665 | } |
| 666 | |
| 667 | /// #423: a peer's hello names the op families it takes. A signal frame |
| 668 | /// of an op whose flag the peer cleared is refused (`Unsupported`), and |
| 669 | /// `lacks` says so first; every other frame goes, in order. A node sets |
| 670 | /// every op flag in its own hello ([`fake_up_with`] checks it). |
| 671 | #[test] |
| 672 | fn a_peer_gets_only_the_ops_its_hello_flags() { |
| 673 | let (a, ea) = start(config("a", "node-a")); |
| 674 | let ops: [(u8, u64); 5] = [ |
| 675 | (0x16, frame::FLAG_DEMONITOR), |
| 676 | (0x17, frame::FLAG_UNLINK), |
| 677 | (0x18, frame::FLAG_UNLINK), |
| 678 | (0x22, frame::FLAG_SPAWN_LINKED), |
| 679 | (0x23, frame::FLAG_SPAWN_MONITORED), |
| 680 | ]; |
| 681 | let cleared = [ |
| 682 | 0, |
| 683 | frame::FLAG_DEMONITOR, |
| 684 | frame::FLAG_SPAWN_LINKED, |
| 685 | frame::FLAG_SPAWN_MONITORED, |
| 686 | frame::FLAG_UNLINK, |
| 687 | frame::FLAGS_OPS, |
| 688 | ]; |
| 689 | for (round, clear) in cleared.into_iter().enumerate() { |
| 690 | let incarnation = 10 + round as u64; |
| 691 | // Unknown bits are ignored. |
| 692 | let flags = (u64::MAX << 5 | frame::FLAGS_OPS) & !clear; |
| 693 | let mut fake = fake_up_with(&a, &ea, "b", incarnation, flags); |
| 694 | let b = Node { |
| 695 | name: name("b"), |
| 696 | incarnation, |
| 697 | }; |
| 698 | let mut sent = Vec::new(); |
| 699 | for (op, flag) in ops { |
| 700 | let body = [&[op][..], &[round as u8; 24]].concat(); |
| 701 | let lacked = flag & clear != 0; |
| 702 | assert_eq!(a.lacks(&b, op), lacked, "op {op:02x}, cleared {clear:b}"); |
| 703 | let frame = match op { |
| 704 | 0x22 | 0x23 => Outbound::Request(body.clone()), |
| 705 | _ => Outbound::Signal(body.clone()), |
| 706 | }; |
| 707 | let queued = a.send(&b, frame); |
| 708 | if lacked { |
| 709 | assert_eq!(queued, Err(SendError::Unsupported), "op {op:02x}"); |
| 710 | } else { |
| 711 | assert_eq!(queued, Ok(()), "op {op:02x}"); |
| 712 | sent.push(body); |
| 713 | } |
| 714 | } |
| 715 | // Ops every node takes, and a message, go whatever the flags. |
| 716 | for op in [0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x20, 0x21] { |
| 717 | assert!(!a.lacks(&b, op)); |
| 718 | } |
| 719 | a.send(&b, Outbound::Message(message(&b, 1, b"m"))) |
| 720 | .expect("a message"); |
| 721 | let end = vec![0x10, round as u8]; |
| 722 | a.send(&b, Outbound::Signal(end.clone())).expect("a link"); |
| 723 | sent.push(end); |
| 724 | let mut got = Vec::new(); |
| 725 | while got.last() != sent.last() { |
| 726 | match get(&mut fake).expect("a frame") { |
| 727 | (frame::SIGNAL, body) => got.push(body), |
| 728 | (frame::MESSAGE | frame::HEARTBEAT | frame::ECHO, _) => {} |
| 729 | (kind, _) => panic!("a frame of kind {kind}"), |
| 730 | } |
| 731 | } |
| 732 | assert_eq!(got, sent, "cleared {clear:b}"); |
| 733 | drop(fake); |
| 734 | let down = ea.wait("B down", |e| match e { |
| 735 | Ev::Down(n) => Some(n.clone()), |
| 736 | _ => None, |
| 737 | }); |
| 738 | assert_eq!(down, b); |
| 739 | // Not up: nothing lacks, and a send is not connected. |
| 740 | assert!(!a.lacks(&b, 0x16)); |
| 741 | assert_eq!( |
| 742 | a.send(&b, Outbound::Signal(vec![0x16])), |
| 743 | Err(SendError::NotConnected) |
| 744 | ); |
| 745 | } |
| 746 | } |
| 747 | |
| 748 | #[test] |
| 749 | fn the_cluster_and_schema_must_match() { |
| 750 | for (field, want_a, want_code) in [ |
| 751 | ("cluster", Reason::Cluster("other".into()), 2), |
| 752 | ("schema", Reason::Schema(SCHEMA + 1), 3), |
| 753 | ] { |
| 754 | let (a, ea) = start(config("a", "node-a")); |
| 755 | let mut cb = config("b", "node-b"); |
| 756 | match field { |
| 757 | "cluster" => cb.cluster = "other".into(), |
| 758 | _ => cb.schema_hash = SCHEMA + 1, |
| 759 | } |
| 760 | cb.seeds = vec![(name("a"), a.local_addr())]; |
| 761 | let (b, eb) = start(cb); |
| 762 | let (peer, _) = ea.closed(field, |r| *r == want_a); |
| 763 | assert!( |
| 764 | peer.starts_with(&format!("{} at 127.0.0.1:", name("b"))), |
| 765 | "{peer}" |
| 766 | ); |
| 767 | let (peer, why) = eb.closed(field, |r| matches!(r, Reason::Refused(..))); |
| 768 | assert_eq!(peer, name("a")); |
| 769 | let Reason::Refused(code, text) = why else { |
| 770 | unreachable!() |
| 771 | }; |
| 772 | assert_eq!(code, want_code, "{field}: {text}"); |
| 773 | assert!(a.peers().is_empty() && b.peers().is_empty(), "{field}"); |
| 774 | } |
| 775 | } |
| 776 | |
| 777 | #[test] |
| 778 | fn another_protocol_version_is_refused() { |
| 779 | let (a, ea) = start(config("a", "node-a")); |
| 780 | let mut s = fake_dial(a.local_addr(), "node-b"); |
| 781 | let mut h = hello(&name("b"), 1).encode(); |
| 782 | h[0] = 2; |
| 783 | put(&mut s, frame::HELLO, &h); |
| 784 | ea.closed("version", |r| *r == Reason::Version(2)); |
| 785 | let said = until_closed(&mut s); |
| 786 | assert!( |
| 787 | matches!(said.as_slice(), [(frame::REFUSE, body)] if body[0] == 1), |
| 788 | "{said:?}" |
| 789 | ); |
| 790 | assert!(a.peers().is_empty()); |
| 791 | } |
| 792 | |
| 793 | #[test] |
| 794 | fn certificates_must_name_the_node() { |
| 795 | let (a, ea) = start(config("a", "node-a")); |
| 796 | // Dialing A with a certificate of another authority, or for another |
| 797 | // name than the one claimed. |
| 798 | let mut rogue = fake_dial(a.local_addr(), "node-rogue"); |
| 799 | put(&mut rogue, frame::HELLO, &hello(&name("b"), 1).encode()); |
| 800 | ea.closed("a rogue dialer", |r| matches!(r, Reason::Tls(_))); |
| 801 | let mut impostor = fake_dial(a.local_addr(), "node-impostor"); |
| 802 | put(&mut impostor, frame::HELLO, &hello(&name("b"), 1).encode()); |
| 803 | ea.closed("an impostor dialer", |r| *r == Reason::Name(name("b"))); |
| 804 | assert!( |
| 805 | matches!(until_closed(&mut impostor).as_slice(), [(frame::REFUSE, body)] if body[0] == 4) |
| 806 | ); |
| 807 | // A certificate valid for the claimed name, but not A's peer: its own. |
| 808 | let mut itself = fake_dial(a.local_addr(), "node-a"); |
| 809 | put(&mut itself, frame::HELLO, &hello(&name("a"), 1).encode()); |
| 810 | ea.closed("A itself", |r| *r == Reason::Name(name("a"))); |
| 811 | |
| 812 | // A dialing a node whose certificate is of another authority, not |
| 813 | // valid for the name dialed, or whose hello claims another name. |
| 814 | for (cert, claim, rustls_refuses) in [ |
| 815 | ("node-rogue", "b", true), |
| 816 | ("node-impostor", "b", true), |
| 817 | ("node-b", "c", false), |
| 818 | ] { |
| 819 | let (addr, fake) = fake_listen(cert, move |s| { |
| 820 | if get(s).is_some_and(|(kind, _)| kind == frame::HELLO) { |
| 821 | put(s, frame::HELLO, &hello(&name(claim), 1).encode()); |
| 822 | let _ = until_closed(s); |
| 823 | } |
| 824 | }); |
| 825 | a.connect(&name("b"), addr); |
| 826 | let (peer, why) = ea.closed(cert, |r| matches!(r, Reason::Tls(_) | Reason::Name(_))); |
| 827 | assert_eq!(peer, name("b")); |
| 828 | if rustls_refuses { |
| 829 | assert!(matches!(why, Reason::Tls(_)), "{cert}: {why:?}"); |
| 830 | } else { |
| 831 | assert_eq!(why, Reason::Name(name(claim))); |
| 832 | } |
| 833 | fake.join().expect("the fake node"); |
| 834 | } |
| 835 | assert!(a.peers().is_empty()); |
| 836 | } |
| 837 | |
| 838 | #[test] |
| 839 | fn simultaneous_dials_keep_one_connection() { |
| 840 | for round in 0..5 { |
| 841 | let (a, ea) = start(config("a", "node-a")); |
| 842 | let (b, eb) = start(config("b", "node-b")); |
| 843 | std::thread::scope(|s| { |
| 844 | s.spawn(|| a.connect(&name("b"), b.local_addr())); |
| 845 | s.spawn(|| b.connect(&name("a"), a.local_addr())); |
| 846 | }); |
| 847 | assert_eq!(ea.up("A sees B"), *b.me(), "round {round}"); |
| 848 | assert_eq!(eb.up("B sees A"), *a.me(), "round {round}"); |
| 849 | until("one connection each", || { |
| 850 | a.connections() == 1 && b.connections() == 1 |
| 851 | }); |
| 852 | for e in ea.during(Duration::from_millis(300)) { |
| 853 | assert!( |
| 854 | matches!(&e, Ev::Closed(_, r) if r.routine()), |
| 855 | "round {round}: {e:?}" |
| 856 | ); |
| 857 | } |
| 858 | assert_eq!((a.connections(), b.connections()), (1, 1)); |
| 859 | // The connection kept works both ways. |
| 860 | a.send(b.me(), Outbound::Signal(vec![1])).expect("A sends"); |
| 861 | b.send(a.me(), Outbound::Signal(vec![2])).expect("B sends"); |
| 862 | let got = eb.wait("A's signal", |e| match e { |
| 863 | Ev::Signal(_, body) => Some(body.clone()), |
| 864 | _ => None, |
| 865 | }); |
| 866 | assert_eq!(got, [1]); |
| 867 | let got = ea.wait("B's signal", |e| match e { |
| 868 | Ev::Signal(_, body) => Some(body.clone()), |
| 869 | _ => None, |
| 870 | }); |
| 871 | assert_eq!(got, [2]); |
| 872 | } |
| 873 | } |
| 874 | |
| 875 | #[test] |
| 876 | fn a_silent_peer_is_down_after_node_down_after_ms() { |
| 877 | let mut ca = config("a", "node-a"); |
| 878 | ca.node_down_after_ms = 500; |
| 879 | let mut cb = config("b", "node-b"); |
| 880 | cb.node_down_after_ms = 500; |
| 881 | // Heartbeats keep an idle connection up. |
| 882 | let ((a, ea), (b, eb)) = pair(ca.clone(), cb); |
| 883 | let seen = ea.during(Duration::from_millis(1_500)); |
| 884 | assert!(seen.is_empty(), "an idle connection: {seen:?}"); |
| 885 | assert!(eb.during(Duration::ZERO).is_empty()); |
| 886 | drop((a, b)); |
| 887 | // A fake peer that completes the handshake, then goes silent. |
| 888 | let (a, ea) = start(ca); |
| 889 | let fake = fake_up(&a, &ea, 7); |
| 890 | let up = Instant::now(); |
| 891 | let (_, why) = ea.closed("a timeout", |r| *r == Reason::Timeout); |
| 892 | let after = up.elapsed(); |
| 893 | assert_eq!(why, Reason::Timeout); |
| 894 | let down = ea.next("B down"); |
| 895 | assert!( |
| 896 | matches!(&down, Ev::Down(n) if n.incarnation == 7), |
| 897 | "{down:?}" |
| 898 | ); |
| 899 | assert!( |
| 900 | after >= Duration::from_millis(400) && after < Duration::from_millis(3_000), |
| 901 | "down after {after:?}" |
| 902 | ); |
| 903 | drop(fake); |
| 904 | // A dialer that never says hello is closed as late. |
| 905 | let _mute = fake_dial(a.local_addr(), "node-b"); |
| 906 | let since = Instant::now(); |
| 907 | let (_, why) = ea.closed("a mute dialer", |_| true); |
| 908 | assert_eq!(why, Reason::Timeout); |
| 909 | assert!(since.elapsed() < Duration::from_millis(3_000)); |
| 910 | } |
| 911 | |
| 912 | /// A sink that takes its time over each message, as decoding may. |
| 913 | struct Slow(Sink, Duration); |
| 914 | |
| 915 | impl Inbound for Slow { |
| 916 | fn node_up(&self, peer: &Node) { |
| 917 | self.0.node_up(peer); |
| 918 | } |
| 919 | fn node_down(&self, peer: &Node) { |
| 920 | self.0.node_down(peer); |
| 921 | } |
| 922 | fn message(&self, from: &Node, header: &MessageHeader, payload: &[u8]) { |
| 923 | std::thread::sleep(self.1); |
| 924 | self.0.message(from, header, payload); |
| 925 | } |
| 926 | fn signal(&self, from: &Node, body: &[u8]) { |
| 927 | self.0.signal(from, body); |
| 928 | } |
| 929 | fn drained(&self, peer: &Node, waiters: &[Waiter]) { |
| 930 | self.0.drained(peer, waiters); |
| 931 | } |
| 932 | fn closed(&self, peer: &str, reason: &Reason, hearsay: bool) { |
| 933 | self.0.closed(peer, reason, hearsay); |
| 934 | } |
| 935 | } |
| 936 | |
| 937 | #[test] |
| 938 | fn a_flooding_peer_starves_no_other() { |
| 939 | // C writes faster than A's handler reads: A's socket from C never runs |
| 940 | // dry, yet A keeps heartbeating B and reading B's. |
| 941 | let mut ca = config("a", "node-a"); |
| 942 | ca.node_down_after_ms = 600; |
| 943 | let (tx, rx) = channel(); |
| 944 | let slow = Slow(Sink(Mutex::new(tx)), Duration::from_micros(20)); |
| 945 | let a = Transport::start(ca, Arc::new(slow)).expect("A starts"); |
| 946 | let ea = Events(rx); |
| 947 | let mut cb = config("b", "node-b"); |
| 948 | cb.node_down_after_ms = 600; |
| 949 | cb.seeds = vec![(name("a"), a.local_addr())]; |
| 950 | let (b, eb) = start(cb); |
| 951 | assert_eq!(ea.up("A sees B"), *b.me()); |
| 952 | assert_eq!(eb.up("B sees A"), *a.me()); |
| 953 | let mut c = fake_up_as(&a, &ea, "c", 9); |
| 954 | let to_a = a.me().clone(); |
| 955 | let flood = std::thread::spawn(move || { |
| 956 | let until = Instant::now() + Duration::from_millis(2_000); |
| 957 | let mut serial = 0; |
| 958 | while Instant::now() < until { |
| 959 | put(&mut c, frame::MESSAGE, &message(&to_a, serial, &[0; 64])); |
| 960 | serial += 1; |
| 961 | } |
| 962 | c |
| 963 | }); |
| 964 | let seen = eb.during(Duration::from_millis(2_000)); |
| 965 | assert!(seen.is_empty(), "B while C floods A: {seen:?}"); |
| 966 | assert_eq!(b.peers(), [a.me().clone()]); |
| 967 | drop(flood.join().expect("the flood")); |
| 968 | } |
| 969 | |
| 970 | /// A fake peer, up with A, sends a heartbeat: how long A took to echo it. |
| 971 | fn echo_time(c: &mut Dialer, stamp: u64) -> Duration { |
| 972 | let sent = Instant::now(); |
| 973 | put(c, frame::HEARTBEAT, &stamp.to_le_bytes()); |
| 974 | loop { |
| 975 | match get(c) { |
| 976 | Some((frame::ECHO, body)) if body == stamp.to_le_bytes() => return sent.elapsed(), |
| 977 | Some(_) => {} |
| 978 | None => panic!("A closed the connection"), |
| 979 | } |
| 980 | } |
| 981 | } |
| 982 | |
| 983 | /// A's handler takes 400 ms a message, as decoding a few MiB of boxed |
| 984 | /// leaves does: it runs beside the transport, so A echoes C's heartbeats |
| 985 | /// at once meanwhile (#404's security review, SEC-6: they waited for each |
| 986 | /// decode). B's messages, twice A's backlog for a peer, pause B's |
| 987 | /// connection, which is not taken for silent, and all arrive, in order. |
| 988 | #[test] |
| 989 | fn a_slow_handler_holds_up_no_heartbeat() { |
| 990 | let mut ca = config("a", "node-a"); |
| 991 | ca.node_down_after_ms = 1_000; |
| 992 | let (tx, rx) = channel(); |
| 993 | let slow = Slow(Sink(Mutex::new(tx)), Duration::from_millis(400)); |
| 994 | let a = Transport::start(ca, Arc::new(slow)).expect("A starts"); |
| 995 | let ea = Events(rx); |
| 996 | let mut cb = config("b", "node-b"); |
| 997 | cb.node_down_after_ms = 1_000; |
| 998 | cb.seeds = vec![(name("a"), a.local_addr())]; |
| 999 | let (b, eb) = start(cb); |
| 1000 | assert_eq!(ea.up("A sees B"), *b.me()); |
| 1001 | assert_eq!(eb.up("B sees A"), *a.me()); |
| 1002 | let mut c = fake_up_as(&a, &ea, "c", 9); |
| 1003 | let n = 2 * super::relay::BACKLOG as u64 / (1 << 20); |
| 1004 | for serial in 0..n { |
| 1005 | let frame = message(a.me(), serial, &vec![0; 1 << 20]); |
| 1006 | b.send(a.me(), Outbound::Message(frame)).expect("queued"); |
| 1007 | } |
| 1008 | // Until B's messages are handled, and a little more. |
| 1009 | let until = Instant::now() + Duration::from_millis(400) * n as u32; |
| 1010 | let mut worst = Duration::ZERO; |
| 1011 | let mut stamp = 0; |
| 1012 | let mut paused = false; |
| 1013 | while Instant::now() < until { |
| 1014 | stamp += 1; |
| 1015 | worst = worst.max(echo_time(&mut c, stamp)); |
| 1016 | paused |= !a.relay.resumed(&b.me().name); |
| 1017 | std::thread::sleep(Duration::from_millis(50)); |
| 1018 | } |
| 1019 | assert!(worst < Duration::from_millis(200), "an echo took {worst:?}"); |
| 1020 | assert!(paused, "B's backlog paused its connection"); |
| 1021 | let messages: Vec<u64> = (0..n) |
| 1022 | .map(|_| { |
| 1023 | ea.wait("B's messages", |e| match e { |
| 1024 | Ev::Message(from, header, _) if from == b.me() => Some(header.serial), |
| 1025 | _ => None, |
| 1026 | }) |
| 1027 | }) |
| 1028 | .collect(); |
| 1029 | assert_eq!(messages, (0..n).collect::<Vec<_>>()); |
| 1030 | assert_eq!(eb.during(Duration::ZERO), [], "B kept A"); |
| 1031 | drop(c); |
| 1032 | } |
| 1033 | |
| 1034 | #[test] |
| 1035 | fn a_restarted_node_is_a_new_incarnation() { |
| 1036 | let ((a, ea), (b, _eb)) = pair(config("a", "node-a"), config("b", "node-b")); |
| 1037 | let first = b.me().clone(); |
| 1038 | b.stop(); |
| 1039 | let down = ea.wait("B down", |e| match e { |
| 1040 | Ev::Down(n) => Some(n.clone()), |
| 1041 | _ => None, |
| 1042 | }); |
| 1043 | assert_eq!(down, first); |
| 1044 | let mut cb = config("b", "node-b"); |
| 1045 | cb.seeds = vec![(name("a"), a.local_addr())]; |
| 1046 | let (b, _eb) = start(cb); |
| 1047 | let second = ea.up("B again"); |
| 1048 | assert_eq!(second, *b.me()); |
| 1049 | assert_ne!(second.incarnation, first.incarnation); |
| 1050 | drop((a, b)); |
| 1051 | |
| 1052 | // A new incarnation replaces one A still takes for up: the old one is |
| 1053 | // down at once, not after node_down_after_ms. |
| 1054 | let mut ca = config("a", "node-a"); |
| 1055 | ca.node_down_after_ms = 60_000; |
| 1056 | let (a, ea) = start(ca); |
| 1057 | let _silent = fake_up(&a, &ea, 7); |
| 1058 | let since = Instant::now(); |
| 1059 | let mut cb = config("b", "node-b"); |
| 1060 | cb.seeds = vec![(name("a"), a.local_addr())]; |
| 1061 | let (b, _eb) = start(cb); |
| 1062 | let down = ea.wait("the old B down", |e| match e { |
| 1063 | Ev::Down(n) => Some(n.clone()), |
| 1064 | _ => None, |
| 1065 | }); |
| 1066 | assert_eq!(down.incarnation, 7); |
| 1067 | assert_eq!(ea.up("the new B"), *b.me()); |
| 1068 | assert!(since.elapsed() < PATIENCE); |
| 1069 | assert_eq!(a.peers(), [b.me().clone()]); |
| 1070 | } |
| 1071 | |
| 1072 | #[test] |
| 1073 | fn a_full_node_refuses_strangers_not_its_seeds() { |
| 1074 | // Node X (the certificate for node-x) keeps two peers. |
| 1075 | let mut cx = config("x", "node-impostor"); |
| 1076 | cx.max_peers = 2; |
| 1077 | let (x, ex) = start(cx); |
| 1078 | let _a = fake_up_as(&x, &ex, "a", 1); |
| 1079 | let _b = fake_up_as(&x, &ex, "b", 1); |
| 1080 | // A third is refused at its hello, before X's goes out. |
| 1081 | let mut c = fake_dial_to(x.local_addr(), &name("x"), "node-c"); |
| 1082 | put(&mut c, frame::HELLO, &hello(&name("c"), 1).encode()); |
| 1083 | let (peer, _) = ex.closed("C refused", |r| *r == Reason::Full); |
| 1084 | assert!( |
| 1085 | peer.starts_with(&format!("{} at 127.0.0.1:", name("c"))), |
| 1086 | "{peer}" |
| 1087 | ); |
| 1088 | let said = until_closed(&mut c); |
| 1089 | assert!( |
| 1090 | matches!(said.as_slice(), [(frame::REFUSE, body)] if body[0] == 8), |
| 1091 | "{said:?}" |
| 1092 | ); |
| 1093 | // A new incarnation of a peer is no stranger: it replaces the old. |
| 1094 | let mut b = fake_dial_to(x.local_addr(), &name("x"), "node-b"); |
| 1095 | put(&mut b, frame::HELLO, &hello(&name("b"), 2).encode()); |
| 1096 | assert_eq!(get(&mut b).map(|(kind, _)| kind), Some(frame::HELLO)); |
| 1097 | put(&mut b, frame::ACK, &[]); |
| 1098 | loop { |
| 1099 | match ex.next("the new B") { |
| 1100 | Ev::Up(n) => break assert_eq!((n.name, n.incarnation), (name("b"), 2)), |
| 1101 | Ev::Down(n) => assert_eq!((n.name, n.incarnation), (name("b"), 1)), |
| 1102 | Ev::Closed(..) => {} |
| 1103 | e => panic!("{e:?} while waiting for the new B"), |
| 1104 | } |
| 1105 | } |
| 1106 | // A node X was told to connect to is never refused: C, once X dials |
| 1107 | // it (to a socket that never answers), dials in past the cap; X drops |
| 1108 | // its own dial, as for simultaneous dials (C's name is smaller). |
| 1109 | let held = TcpListener::bind("127.0.0.1:0").expect("a port"); |
| 1110 | x.connect(&name("c"), held.local_addr().expect("its address")); |
| 1111 | let (_dialed, _) = held.accept().expect("X dials C"); |
| 1112 | let _c = fake_up_as(&x, &ex, "c", 1); |
| 1113 | let names: Vec<String> = x.peers().into_iter().map(|p| p.name).collect(); |
| 1114 | assert_eq!(names, [name("a"), name("b"), name("c")], "past max_peers"); |
| 1115 | } |
| 1116 | |
| 1117 | #[test] |
| 1118 | fn down_nodes_are_forgotten_least_recently_seen_first() { |
| 1119 | let known = |p: &PeerStats| { |
| 1120 | let mut names: Vec<String> = p.iter().map(|(n, _)| n.clone()).collect(); |
| 1121 | names.sort(); |
| 1122 | names |
| 1123 | }; |
| 1124 | let mut p = PeerStats::new(2); |
| 1125 | p.keep("seed"); |
| 1126 | p.up("up"); |
| 1127 | p.stats("d1"); |
| 1128 | p.stats("d2"); |
| 1129 | // A message for d1: d2 is now the least recently seen. |
| 1130 | Stats::count(&p.stats("d1").unsent, 1); |
| 1131 | p.stats("d3"); |
| 1132 | assert_eq!(known(&p), ["d1", "d3", "seed", "up"]); |
| 1133 | let unsent = p |
| 1134 | .stats("d1") |
| 1135 | .unsent |
| 1136 | .load(std::sync::atomic::Ordering::Relaxed); |
| 1137 | assert_eq!(unsent, 1, "kept whole"); |
| 1138 | // However many names pass, a node up and a seed stay. |
| 1139 | for i in 0..100 { |
| 1140 | p.stats(&format!("n{i:02}")); |
| 1141 | } |
| 1142 | assert_eq!(known(&p), ["n98", "n99", "seed", "up"]); |
| 1143 | // A node that goes down is the most recently seen of the down ones. |
| 1144 | p.down("up"); |
| 1145 | assert_eq!(known(&p), ["n99", "seed", "up"]); |
| 1146 | // Up again, it is not counted among them. |
| 1147 | p.up("up"); |
| 1148 | p.stats("e"); |
| 1149 | assert_eq!(known(&p), ["e", "n99", "seed", "up"]); |
| 1150 | // Through the transport: its seeds, and what it reports. |
| 1151 | let mut ca = config("a", "node-a"); |
| 1152 | ca.max_peers = 1; |
| 1153 | ca.seeds = vec![(name("c"), "127.0.0.1:1".parse().expect("an address"))]; |
| 1154 | let (a, _ea) = start(ca); |
| 1155 | a.count_unsent(&name("b")); |
| 1156 | a.count_unsent(&name("x")); |
| 1157 | let reported: Vec<String> = a.report().into_iter().map(|r| r.node).collect(); |
| 1158 | assert_eq!(reported, [name("c"), name("x")]); |
| 1159 | } |
| 1160 | |
| 1161 | #[test] |
| 1162 | fn bad_frames_close_the_connection() { |
| 1163 | let mut ca = config("a", "node-a"); |
| 1164 | ca.max_frame = 4096; |
| 1165 | let (a, ea) = start(ca); |
| 1166 | let b = |incarnation| Node { |
| 1167 | name: name("b"), |
| 1168 | incarnation, |
| 1169 | }; |
| 1170 | // A message for another incarnation of A is dropped and counted, the |
| 1171 | // connection kept. |
| 1172 | let mut s = fake_up(&a, &ea, 100); |
| 1173 | let stale = Node { |
| 1174 | incarnation: a.me().incarnation ^ 1, |
| 1175 | ..a.me().clone() |
| 1176 | }; |
| 1177 | put(&mut s, frame::MESSAGE, &message(&stale, 1, b"hi")); |
| 1178 | until("the frame dropped", || a.dropped() == 1); |
| 1179 | put(&mut s, frame::MESSAGE, &message(a.me(), 2, b"hi")); |
| 1180 | let got = ea.next("the next message"); |
| 1181 | assert!( |
| 1182 | matches!(&got, Ev::Message(_, h, p) if h.serial == 2 && p == b"hi"), |
| 1183 | "{got:?}" |
| 1184 | ); |
| 1185 | // Closed with A's heartbeat unread: an end of stream, or a reset. |
| 1186 | drop(s); |
| 1187 | let (peer, _) = ea.closed("B gone", |r| matches!(r, Reason::Closed(_))); |
| 1188 | assert_eq!(peer, name("b")); |
| 1189 | assert_eq!(ea.next("B down"), Ev::Down(b(100))); |
| 1190 | let cases: [(&[u8], Reason); 6] = [ |
| 1191 | // Over the limit: refused on its prefix alone. |
| 1192 | (&4097u32.to_le_bytes(), Reason::TooLarge(4097)), |
| 1193 | (&[0xff; 64], Reason::TooLarge(u32::MAX)), |
| 1194 | ( |
| 1195 | &[2, 0, 0, 0, 0x7f, 0], |
| 1196 | Reason::Protocol("an unexpected frame"), |
| 1197 | ), |
| 1198 | ( |
| 1199 | &[3, 0, 0, 0, frame::MESSAGE, 1, 2], |
| 1200 | Reason::Protocol("a message frame shorter than its header"), |
| 1201 | ), |
| 1202 | ( |
| 1203 | &[1, 0, 0, 0, frame::HELLO], |
| 1204 | Reason::Protocol("an unexpected frame"), |
| 1205 | ), |
| 1206 | // A heartbeat carries a stamp. |
| 1207 | ( |
| 1208 | &[1, 0, 0, 0, frame::HEARTBEAT], |
| 1209 | Reason::Protocol("an unexpected frame"), |
| 1210 | ), |
| 1211 | ]; |
| 1212 | for (i, (bytes, reason)) in cases.into_iter().enumerate() { |
| 1213 | let mut s = fake_up(&a, &ea, i as u64); |
| 1214 | s.write_all(bytes).expect("written"); |
| 1215 | s.flush().expect("flushed"); |
| 1216 | let (_, why) = ea.closed("a bad frame", |_| true); |
| 1217 | assert_eq!(why, reason, "case {i}"); |
| 1218 | assert_eq!(ea.next("B down"), Ev::Down(b(i as u64)), "case {i}"); |
| 1219 | // Its heartbeats, then why. |
| 1220 | let said = until_closed(&mut s); |
| 1221 | let kinds: Vec<u8> = said.iter().map(|(k, _)| *k).collect(); |
| 1222 | assert!( |
| 1223 | kinds |
| 1224 | .split_last() |
| 1225 | .is_some_and(|(last, before)| *last == frame::REFUSE |
| 1226 | && before.iter().all(|k| *k == frame::HEARTBEAT)), |
| 1227 | "{said:?}" |
| 1228 | ); |
| 1229 | } |
| 1230 | // Before the hello, frames are 1 KiB at most. |
| 1231 | let mut s = fake_dial(a.local_addr(), "node-b"); |
| 1232 | s.write_all(&2_000u32.to_le_bytes()).expect("written"); |
| 1233 | s.flush().expect("flushed"); |
| 1234 | let (_, why) = ea.closed("a large frame before the hello", |_| true); |
| 1235 | assert_eq!(why, Reason::TooLarge(2_000)); |
| 1236 | // Bytes that are not TLS at all. |
| 1237 | let mut raw = TcpStream::connect(a.local_addr()).expect("A listens"); |
| 1238 | raw.write_all(b"GET / HTTP/1.1\r\n\r\n").expect("written"); |
| 1239 | ea.closed("not TLS", |r| matches!(r, Reason::Tls(_))); |
| 1240 | let mut rest = Vec::new(); |
| 1241 | raw.set_read_timeout(Some(PATIENCE)).expect("a timeout"); |
| 1242 | let _ = raw.read_to_end(&mut rest); |
| 1243 | // A still works. |
| 1244 | let mut cb = config("b", "node-b"); |
| 1245 | cb.seeds = vec![(name("a"), a.local_addr())]; |
| 1246 | let (b, _eb) = start(cb); |
| 1247 | assert_eq!(ea.up("a real B"), *b.me()); |
| 1248 | } |
| 1249 | |
| 1250 | /// A TCP connection to `to` from the loopback address `127.0.0.{host}`: |
| 1251 | /// another source, as far as A's eviction goes. |
| 1252 | fn connect_from(host: u8, to: SocketAddr) -> std::io::Result<TcpStream> { |
| 1253 | use std::os::fd::FromRawFd; |
| 1254 | let SocketAddr::V4(to) = to else { |
| 1255 | unreachable!("A listens on 127.0.0.1") |
| 1256 | }; |
| 1257 | let addr = |ip: std::net::Ipv4Addr, port: u16| libc::sockaddr_in { |
| 1258 | sin_family: libc::AF_INET as libc::sa_family_t, |
| 1259 | sin_port: port.to_be(), |
| 1260 | sin_addr: libc::in_addr { |
| 1261 | s_addr: u32::from(ip).to_be(), |
| 1262 | }, |
| 1263 | sin_zero: [0; 8], |
| 1264 | }; |
| 1265 | let len = std::mem::size_of::<libc::sockaddr_in>() as libc::socklen_t; |
| 1266 | // SAFETY: a fresh socket, owned by the stream once connected (closed |
| 1267 | // here otherwise); the addresses are `sockaddr_in`s of `len` bytes. |
| 1268 | unsafe { |
| 1269 | let fd = libc::socket(libc::AF_INET, libc::SOCK_STREAM | libc::SOCK_CLOEXEC, 0); |
| 1270 | if fd < 0 { |
| 1271 | return Err(std::io::Error::last_os_error()); |
| 1272 | } |
| 1273 | let from = addr(std::net::Ipv4Addr::new(127, 0, 0, host), 0); |
| 1274 | let to = addr(*to.ip(), to.port()); |
| 1275 | if libc::bind(fd, (&raw const from).cast(), len) != 0 |
| 1276 | || libc::connect(fd, (&raw const to).cast(), len) != 0 |
| 1277 | { |
| 1278 | let e = std::io::Error::last_os_error(); |
| 1279 | libc::close(fd); |
| 1280 | return Err(e); |
| 1281 | } |
| 1282 | Ok(TcpStream::from_raw_fd(fd)) |
| 1283 | } |
| 1284 | } |
| 1285 | |
| 1286 | #[test] |
| 1287 | fn idle_sockets_cannot_lock_nodes_out() { |
| 1288 | let mut ca = config("a", "node-a"); |
| 1289 | ca.node_down_after_ms = 60_000; |
| 1290 | let (a, ea) = start(ca); |
| 1291 | // As many as A holds, from as few sources as can hold them. |
| 1292 | let sources = (MAX_UNAUTHENTICATED / MAX_UNAUTHENTICATED_PER_SOURCE) as u8; |
| 1293 | let idle: Vec<TcpStream> = (0..MAX_UNAUTHENTICATED) |
| 1294 | .map(|i| { |
| 1295 | let host = 2 + i as u8 % sources; |
| 1296 | connect_from(host, a.local_addr()).expect("A listens") |
| 1297 | }) |
| 1298 | .collect(); |
| 1299 | until("A holds them", || a.connections() == MAX_UNAUTHENTICATED); |
| 1300 | // B's connection closes the oldest of a source that holds the most. |
| 1301 | let mut cb = config("b", "node-b"); |
| 1302 | cb.seeds = vec![(name("a"), a.local_addr())]; |
| 1303 | let (b, _eb) = start(cb); |
| 1304 | assert_eq!(ea.up("B, past the idle sockets"), *b.me()); |
| 1305 | assert_eq!(a.connections(), MAX_UNAUTHENTICATED); |
| 1306 | // One source's connections past its share close its own oldest: B |
| 1307 | // took one of 127.0.0.2's (the oldest), the first of these takes it |
| 1308 | // back. |
| 1309 | let more: Vec<TcpStream> = (0..=MAX_UNAUTHENTICATED_PER_SOURCE) |
| 1310 | .map(|_| connect_from(2, a.local_addr()).expect("A listens")) |
| 1311 | .collect(); |
| 1312 | let crowded = (0..MAX_UNAUTHENTICATED_PER_SOURCE) |
| 1313 | .map(|_| ea.closed("an idle socket", |r| *r == Reason::Crowded).0) |
| 1314 | .collect::<Vec<_>>(); |
| 1315 | assert!( |
| 1316 | crowded.iter().all(|peer| peer.starts_with("127.0.0.2:")), |
| 1317 | "{crowded:?}" |
| 1318 | ); |
| 1319 | drop((idle, more)); |
| 1320 | } |
| 1321 | |
| 1322 | /// A dialer whose handshake (TCP accept to hello) takes `delay`, as over a |
| 1323 | /// link of that round-trip time: the TCP connection, then `meanwhile`, |
| 1324 | /// then the rest of `delay`, then TLS and the hello. Whether A took it up. |
| 1325 | fn slow_dial(a: &Transport, delay: Duration, incarnation: u64, meanwhile: impl FnOnce()) -> bool { |
| 1326 | let config = crate::tls::client_config(ClientOptions { |
| 1327 | authorities: authorities("ca.pem"), |
| 1328 | identity: Some(identity("node-b")), |
| 1329 | alpn: vec![frame::ALPN.to_vec()], |
| 1330 | tls13_only: true, |
| 1331 | insecure: false, |
| 1332 | }) |
| 1333 | .expect("a client configuration"); |
| 1334 | let since = Instant::now(); |
| 1335 | let sock = TcpStream::connect(a.local_addr()).expect("A listens"); |
| 1336 | sock.set_read_timeout(Some(PATIENCE)).expect("a timeout"); |
| 1337 | meanwhile(); |
| 1338 | std::thread::sleep(delay.saturating_sub(since.elapsed())); |
| 1339 | let server = ServerName::try_from(name("a")).expect("a name"); |
| 1340 | let conn = ClientConnection::new(config, server).expect("a client"); |
| 1341 | let mut s = StreamOwned::new(conn, sock); |
| 1342 | let _ = s.conn.complete_io(&mut s.sock); |
| 1343 | put( |
| 1344 | &mut s, |
| 1345 | frame::HELLO, |
| 1346 | &hello(&name("b"), incarnation).encode(), |
| 1347 | ); |
| 1348 | let answered = get(&mut s).is_some_and(|(kind, _)| kind == frame::HELLO); |
| 1349 | if answered { |
| 1350 | put(&mut s, frame::ACK, &[]); |
| 1351 | until("B up", || { |
| 1352 | a.peers().iter().any(|p| p.incarnation == incarnation) |
| 1353 | }); |
| 1354 | } |
| 1355 | drop(s); |
| 1356 | until("B forgotten", || a.peers().is_empty()); |
| 1357 | answered |
| 1358 | } |
| 1359 | |
| 1360 | /// Another host opening connections faster than a distant node handshakes |
| 1361 | /// (50 ms) evicts only its own (#404's security review, SEC-2: A closed |
| 1362 | /// the oldest of all, the distant node's): a burst of connections while it |
| 1363 | /// handshakes, then a steady 2,000 a second. |
| 1364 | #[test] |
| 1365 | fn a_flood_from_one_host_evicts_only_its_own() { |
| 1366 | use std::sync::atomic::{AtomicBool, Ordering}; |
| 1367 | let mut ca = config("a", "node-a"); |
| 1368 | ca.node_down_after_ms = 60_000; |
| 1369 | let (a, _ea) = start(ca); |
| 1370 | let addr = a.local_addr(); |
| 1371 | let delay = Duration::from_millis(50); |
| 1372 | let mut held = Vec::new(); |
| 1373 | assert!( |
| 1374 | slow_dial(&a, delay, 1, || { |
| 1375 | held.extend( |
| 1376 | (0..2 * MAX_UNAUTHENTICATED).map(|_| connect_from(2, addr).expect("A listens")), |
| 1377 | ); |
| 1378 | }), |
| 1379 | "a burst of connections from another host" |
| 1380 | ); |
| 1381 | drop(held); |
| 1382 | let stop = Arc::new(AtomicBool::new(false)); |
| 1383 | let flood = { |
| 1384 | let stop = stop.clone(); |
| 1385 | std::thread::spawn(move || { |
| 1386 | let mut held = std::collections::VecDeque::new(); |
| 1387 | let start = Instant::now(); |
| 1388 | let mut opened = 0u32; |
| 1389 | while !stop.load(Ordering::Relaxed) { |
| 1390 | let due = start + Duration::from_micros(500) * opened; |
| 1391 | std::thread::sleep(due.saturating_duration_since(Instant::now())); |
| 1392 | if let Ok(s) = connect_from(2, addr) { |
| 1393 | held.push_back(s); |
| 1394 | } |
| 1395 | opened += 1; |
| 1396 | if held.len() > 512 { |
| 1397 | held.pop_front(); |
| 1398 | } |
| 1399 | } |
| 1400 | }) |
| 1401 | }; |
| 1402 | std::thread::sleep(Duration::from_millis(200)); |
| 1403 | let connected = (0..3) |
| 1404 | .filter(|i| slow_dial(&a, delay, 10 + i, || ())) |
| 1405 | .count(); |
| 1406 | stop.store(true, Ordering::Relaxed); |
| 1407 | flood.join().expect("the flood"); |
| 1408 | assert_eq!(connected, 3, "under a steady flood from another host"); |
| 1409 | } |
| 1410 | |
| 1411 | /// A node with a certificate of the cluster's authority, but not for the |
| 1412 | /// name it claims, learns nothing from the refusal: code 4 whatever its |
| 1413 | /// cluster and schema (#404's security review, SEC-9: it learned whether it |
| 1414 | /// had guessed them). |
| 1415 | #[test] |
| 1416 | fn an_uncertified_name_is_refused_before_anything_else() { |
| 1417 | let (a, ea) = start(config("a", "node-a")); |
| 1418 | for (cluster, schema) in [("prod", SCHEMA), ("test", SCHEMA ^ 1), ("test", SCHEMA)] { |
| 1419 | let mut s = fake_dial(a.local_addr(), "node-impostor"); |
| 1420 | let mut h = hello(&name("b"), 1); |
| 1421 | h.cluster = cluster.into(); |
| 1422 | h.schema_hash = schema; |
| 1423 | put(&mut s, frame::HELLO, &h.encode()); |
| 1424 | ea.closed("the impostor", |r| *r == Reason::Name(name("b"))); |
| 1425 | let said = until_closed(&mut s); |
| 1426 | assert!( |
| 1427 | matches!(said.as_slice(), [(frame::REFUSE, body)] if body[0] == 4), |
| 1428 | "{cluster} {schema:x}: {said:?}" |
| 1429 | ); |
| 1430 | } |
| 1431 | } |
| 1432 | |
| 1433 | /// A node that connects again verifies its chain again: A issues no |
| 1434 | /// session ticket, so no handshake resumes (#404's security review, SEC-8: |
| 1435 | /// a resumed one skipped the certificate's dates for 24 h). |
| 1436 | #[test] |
| 1437 | fn every_connection_verifies_the_peer_again() { |
| 1438 | let (a, _ea) = start(config("a", "node-a")); |
| 1439 | let config = crate::tls::client_config(ClientOptions { |
| 1440 | authorities: authorities("ca.pem"), |
| 1441 | identity: Some(identity("node-b")), |
| 1442 | alpn: vec![frame::ALPN.to_vec()], |
| 1443 | tls13_only: true, |
| 1444 | insecure: false, |
| 1445 | }) |
| 1446 | .expect("a client configuration that would resume"); |
| 1447 | let mut kinds = Vec::new(); |
| 1448 | for incarnation in [1, 2] { |
| 1449 | let sock = TcpStream::connect(a.local_addr()).expect("A listens"); |
| 1450 | sock.set_read_timeout(Some(PATIENCE)).expect("a timeout"); |
| 1451 | let server = ServerName::try_from(name("a")).expect("a name"); |
| 1452 | let conn = ClientConnection::new(config.clone(), server).expect("a client"); |
| 1453 | let mut s = StreamOwned::new(conn, sock); |
| 1454 | put( |
| 1455 | &mut s, |
| 1456 | frame::HELLO, |
| 1457 | &hello(&name("b"), incarnation).encode(), |
| 1458 | ); |
| 1459 | assert!(get(&mut s).is_some_and(|(kind, _)| kind == frame::HELLO)); |
| 1460 | put(&mut s, frame::ACK, &[]); |
| 1461 | until("B up", || { |
| 1462 | a.peers().iter().any(|p| p.incarnation == incarnation) |
| 1463 | }); |
| 1464 | kinds.push(s.conn.handshake_kind()); |
| 1465 | // Tickets would arrive after the handshake: read them first. |
| 1466 | let _ = s.conn.complete_io(&mut s.sock); |
| 1467 | drop(s); |
| 1468 | until("B forgotten", || a.peers().is_empty()); |
| 1469 | } |
| 1470 | assert_eq!(kinds, [Some(rustls::HandshakeKind::Full); 2]); |
| 1471 | } |
| 1472 | |
| 1473 | #[test] |
| 1474 | fn throttled_lines_come_once_a_period_with_a_count() { |
| 1475 | let mut t = Throttle::default(); |
| 1476 | let now = Instant::now(); |
| 1477 | assert_eq!(t.admit(now), Some(0), "the first at once"); |
| 1478 | for i in 1..2_000 { |
| 1479 | assert_eq!(t.admit(now + Duration::from_micros(i)), None); |
| 1480 | } |
| 1481 | let later = now + Throttle::PERIOD; |
| 1482 | assert_eq!(t.admit(later), Some(1_999), "then how many were held back"); |
| 1483 | assert_eq!(t.admit(later), None); |
| 1484 | assert_eq!(Throttle::held_back(0), ""); |
| 1485 | } |
| 1486 | |
| 1487 | // ---- discovery ----------------------------------------------------------------------------- |
| 1488 | |
| 1489 | /// Node `n`, discovering a full mesh. |
| 1490 | fn mesh(n: &str) -> Config { |
| 1491 | let mut c = config(n, &format!("node-{n}")); |
| 1492 | c.mesh = true; |
| 1493 | c |
| 1494 | } |
| 1495 | |
| 1496 | /// [`mesh`], seeding node B at `b`. |
| 1497 | fn mesh_seeding(n: &str, b: &Transport) -> Config { |
| 1498 | let mut c = mesh(n); |
| 1499 | c.seeds = vec![(name("b"), b.local_addr())]; |
| 1500 | c |
| 1501 | } |
| 1502 | |
| 1503 | /// Wait until each of `names` came up, whatever else happens meanwhile. |
| 1504 | fn ups(events: &Events, what: &str, names: &[&str]) { |
| 1505 | let mut left: HashSet<String> = names.iter().map(|n| name(n)).collect(); |
| 1506 | while !left.is_empty() { |
| 1507 | if let Ev::Up(n) = events.next(what) { |
| 1508 | left.remove(&n.name); |
| 1509 | } |
| 1510 | } |
| 1511 | } |
| 1512 | |
| 1513 | /// Wait until `n` goes down, whatever else happens meanwhile. |
| 1514 | fn down(events: &Events, what: &str, n: &str) { |
| 1515 | while !matches!(events.next(what), Ev::Down(d) if d.name == name(n)) {} |
| 1516 | } |
| 1517 | |
| 1518 | /// Whether `events` hold a connection to `n` closed (a dial that failed). |
| 1519 | fn dialed(events: &[Ev], n: &str) -> bool { |
| 1520 | events |
| 1521 | .iter() |
| 1522 | .any(|e| matches!(e, Ev::Closed(peer, _) if *peer == name(n))) |
| 1523 | } |
| 1524 | |
| 1525 | /// A list of peers, one frame's body. |
| 1526 | fn list(nodes: &[(&str, SocketAddr)]) -> Vec<u8> { |
| 1527 | let nodes: Vec<(String, SocketAddr)> = nodes.iter().map(|(n, a)| (name(n), *a)).collect(); |
| 1528 | let mut frames = Peers::frames(&nodes, 1 << 20); |
| 1529 | assert_eq!(frames.len(), 1); |
| 1530 | frames.remove(0) |
| 1531 | } |
| 1532 | |
| 1533 | /// The next list of peers a fake node gets. |
| 1534 | fn next_list(s: &mut impl Read) -> Peers { |
| 1535 | loop { |
| 1536 | let (kind, body) = get(s).expect("a list of peers"); |
| 1537 | if kind == frame::SIGNAL && body.first() == Some(&frame::PEERS) { |
| 1538 | return Peers::decode(&body[1..]).expect("a well-formed list"); |
| 1539 | } |
| 1540 | } |
| 1541 | } |
| 1542 | |
| 1543 | #[test] |
| 1544 | fn nodes_meet_the_nodes_their_peers_list() { |
| 1545 | // A and C each seed only B: B's lists make them meet, over one |
| 1546 | // connection. |
| 1547 | let (b, eb) = start(mesh("b")); |
| 1548 | let (a, ea) = start(mesh_seeding("a", &b)); |
| 1549 | let (c, ec) = start(mesh_seeding("c", &b)); |
| 1550 | ups(&ea, "A sees B and C", &["b", "c"]); |
| 1551 | ups(&ec, "C sees B and A", &["b", "a"]); |
| 1552 | ups(&eb, "B sees A and C", &["a", "c"]); |
| 1553 | until("one connection per pair", || { |
| 1554 | [&a, &b, &c].iter().all(|t| t.connections() == 2) |
| 1555 | }); |
| 1556 | let names = |t: &Transport| -> Vec<String> { t.peers().into_iter().map(|p| p.name).collect() }; |
| 1557 | assert_eq!(names(&a), [name("b"), name("c")]); |
| 1558 | assert_eq!(names(&c), [name("a"), name("b")]); |
| 1559 | } |
| 1560 | |
| 1561 | #[test] |
| 1562 | fn without_discovery_only_seeds_are_dialed() { |
| 1563 | // B does not discover: it sends no list, so A and C, which do, never |
| 1564 | // learn of each other. Nor do they when none discovers. |
| 1565 | for b_meshes in [false, true] { |
| 1566 | let mut cb = mesh("b"); |
| 1567 | cb.mesh = b_meshes; |
| 1568 | let (b, _eb) = start(cb); |
| 1569 | let mut ca = mesh_seeding("a", &b); |
| 1570 | let mut cc = mesh_seeding("c", &b); |
| 1571 | ca.mesh = !b_meshes; |
| 1572 | cc.mesh = !b_meshes; |
| 1573 | let (_a, ea) = start(ca); |
| 1574 | let (_c, ec) = start(cc); |
| 1575 | ups(&ea, "A sees B", &["b"]); |
| 1576 | ups(&ec, "C sees B", &["b"]); |
| 1577 | let seen = ea.during(Duration::from_millis(1_000)); |
| 1578 | assert!( |
| 1579 | !seen.iter().any(|e| matches!(e, Ev::Up(_))), |
| 1580 | "B meshes: {b_meshes}: {seen:?}" |
| 1581 | ); |
| 1582 | } |
| 1583 | } |
| 1584 | |
| 1585 | #[test] |
| 1586 | fn a_lost_node_is_dialed_while_listed_then_forgotten() { |
| 1587 | let fast = |c: &mut Config| { |
| 1588 | c.heartbeat_ms = 50; |
| 1589 | c.node_down_after_ms = 400; |
| 1590 | }; |
| 1591 | let forget = Duration::from_millis(400) * FORGET_AFTER; |
| 1592 | let mut cb = mesh("b"); |
| 1593 | fast(&mut cb); |
| 1594 | let (b, eb) = start(cb); |
| 1595 | let mut ca = mesh_seeding("a", &b); |
| 1596 | fast(&mut ca); |
| 1597 | let (a, ea) = start(ca); |
| 1598 | let mut cc = mesh_seeding("c", &b); |
| 1599 | fast(&mut cc); |
| 1600 | let (c, ec) = start(cc); |
| 1601 | ups(&ea, "A sees B and C", &["b", "c"]); |
| 1602 | ups(&ec, "C sees B and A", &["b", "a"]); |
| 1603 | // C stops; back at its address, seeding nobody, it is dialed by both. |
| 1604 | let at = c.local_addr(); |
| 1605 | c.stop(); |
| 1606 | down(&ea, "A loses C", "c"); |
| 1607 | down(&eb, "B loses C", "c"); |
| 1608 | let mut cc = mesh("c"); |
| 1609 | fast(&mut cc); |
| 1610 | cc.listen = at; |
| 1611 | let (c, ec) = start(cc); |
| 1612 | ups(&ea, "A dials C again", &["c"]); |
| 1613 | ups(&eb, "B dials C again", &["c"]); |
| 1614 | ups(&ec, "C is dialed by A and B", &["a", "b"]); |
| 1615 | // C stops for good: A dials it until nobody listed it for a while, |
| 1616 | // then forgets it. |
| 1617 | c.stop(); |
| 1618 | down(&ea, "A loses C again", "c"); |
| 1619 | let meanwhile = ea.during(forget / 2); |
| 1620 | assert!(dialed(&meanwhile, "c"), "{meanwhile:?}"); |
| 1621 | let _ = ea.during(forget / 2 + Duration::from_millis(500)); |
| 1622 | let later = ea.during(Duration::from_secs(2)); |
| 1623 | assert!(!dialed(&later, "c"), "{later:?}"); |
| 1624 | // A seed is never forgotten. |
| 1625 | b.stop(); |
| 1626 | down(&ea, "A loses B", "b"); |
| 1627 | let _ = ea.during(forget + Duration::from_millis(500)); |
| 1628 | let later = ea.during(Duration::from_secs(2)); |
| 1629 | assert!(dialed(&later, "b"), "{later:?}"); |
| 1630 | drop(a); |
| 1631 | } |
| 1632 | |
| 1633 | #[test] |
| 1634 | fn a_listed_address_is_only_a_hint() { |
| 1635 | let (a, ea) = start(mesh("a")); |
| 1636 | let (c, ec) = start(mesh("c")); |
| 1637 | // B, a fake node that discovers, gets A's list: A's own address. |
| 1638 | let mut b = fake_up_with(&a, &ea, "b", 1, frame::FLAG_PEERS); |
| 1639 | let mine = next_list(&mut b); |
| 1640 | assert_eq!( |
| 1641 | mine, |
| 1642 | Peers { |
| 1643 | first: true, |
| 1644 | nodes: vec![(name("a"), a.local_addr())] |
| 1645 | } |
| 1646 | ); |
| 1647 | // It lists C where node B's certificate answers: A's dial is refused |
| 1648 | // at TLS, which checks the name A dials. |
| 1649 | let (wrong, impostor) = fake_listen("node-b", |_| {}); |
| 1650 | put(&mut b, frame::SIGNAL, &list(&[("c", wrong)])); |
| 1651 | let (peer, why) = ea.closed("A's dial refused", |r| matches!(r, Reason::Tls(_))); |
| 1652 | assert_eq!(peer, name("c")); |
| 1653 | assert!(why.to_string().contains("not valid for name"), "{why}"); |
| 1654 | impostor.join().expect("the impostor"); |
| 1655 | // No lockout: a list with C's real address replaces the hint. |
| 1656 | put(&mut b, frame::SIGNAL, &list(&[("c", c.local_addr())])); |
| 1657 | ups(&ea, "A dials C", &["c"]); |
| 1658 | ups(&ec, "C sees A", &["a"]); |
| 1659 | // B now gets C in A's list, at the address the dial confirmed. |
| 1660 | loop { |
| 1661 | let list = next_list(&mut b); |
| 1662 | if list.nodes.len() == 2 { |
| 1663 | assert_eq!(list.nodes[1], (name("c"), c.local_addr())); |
| 1664 | break; |
| 1665 | } |
| 1666 | } |
| 1667 | // Which no other peer's list replaces: C, back at its address after |
| 1668 | // a stop, is dialed there, not at the one B lists. |
| 1669 | put( |
| 1670 | &mut b, |
| 1671 | frame::SIGNAL, |
| 1672 | &list(&[("c", "127.0.0.1:1".parse().unwrap())]), |
| 1673 | ); |
| 1674 | let at = c.local_addr(); |
| 1675 | c.stop(); |
| 1676 | down(&ea, "A loses C", "c"); |
| 1677 | let mut cc = mesh("c"); |
| 1678 | cc.listen = at; |
| 1679 | let (_c, ec) = start(cc); |
| 1680 | ups(&ea, "A dials C again", &["c"]); |
| 1681 | ups(&ec, "C sees A again", &["a"]); |
| 1682 | assert_eq!(report(&a, "b").dropped, 0); |
| 1683 | } |
| 1684 | |
| 1685 | #[test] |
| 1686 | fn lists_go_only_between_nodes_that_discover() { |
| 1687 | let listed = |z: SocketAddr| list(&[("z", z)]); |
| 1688 | let nowhere: SocketAddr = "127.0.0.1:1".parse().unwrap(); |
| 1689 | // A discovers; B does not say it does: B's list is dropped and |
| 1690 | // counted, Z is not dialed, and A sends B no list. |
| 1691 | let (a, ea) = start(mesh("a")); |
| 1692 | let mut b = fake_up_as(&a, &ea, "b", 1); |
| 1693 | put(&mut b, frame::SIGNAL, &listed(nowhere)); |
| 1694 | until("B's list dropped", || report(&a, "b").dropped == 1); |
| 1695 | let seen = ea.during(Duration::from_millis(300)); |
| 1696 | assert!(!dialed(&seen, "z"), "{seen:?}"); |
| 1697 | // Nor does A take one malformed (its count, say, past what its bytes |
| 1698 | // hold): the connection stays up. |
| 1699 | let mut d = fake_up_with(&a, &ea, "c", 1, frame::FLAG_PEERS); |
| 1700 | put(&mut d, frame::SIGNAL, &[frame::PEERS, 1, 1, 0, 0]); |
| 1701 | put(&mut d, frame::SIGNAL, &[frame::PEERS, 1, 0xff, 0xff]); |
| 1702 | until("C's lists dropped", || report(&a, "c").dropped == 2); |
| 1703 | put(&mut d, frame::HEARTBEAT, &7u64.to_le_bytes()); |
| 1704 | loop { |
| 1705 | let (kind, body) = get(&mut d).expect("A still up with C"); |
| 1706 | if kind == frame::ECHO { |
| 1707 | assert_eq!(body, 7u64.to_le_bytes()); |
| 1708 | break; |
| 1709 | } |
| 1710 | } |
| 1711 | b.sock |
| 1712 | .set_read_timeout(Some(Duration::from_millis(500))) |
| 1713 | .expect("a timeout"); |
| 1714 | let to_b = until_closed(&mut b); |
| 1715 | assert!( |
| 1716 | to_b.iter().all(|(kind, _)| *kind != frame::SIGNAL), |
| 1717 | "{to_b:?}" |
| 1718 | ); |
| 1719 | // A does not discover: a list from a node that does is dropped. |
| 1720 | let (x, ex) = start(config("x", "node-impostor")); |
| 1721 | let mut b = fake_up_with(&x, &ex, "b", 1, frame::FLAG_PEERS); |
| 1722 | put(&mut b, frame::SIGNAL, &listed(nowhere)); |
| 1723 | until("B's list dropped by X", || report(&x, "b").dropped == 1); |
| 1724 | } |
| 1725 | |
| 1726 | // Second security review of #404 (dist/secreview2): confirming tests. |
| 1727 | mod secreview2; |