Debian Codegraph @

third_party/rust/neqo-http3/tests/httpconn.rs

raw
1 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
2 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
3 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
4 // option. This file may not be copied, modified, or distributed
5 // except according to those terms.
6
7 #![cfg(test)]
8
9 use std::time::{Duration, Instant};
10
11 use neqo_common::{event::Provider as _, qtrace, Datagram};
12 use neqo_crypto::{AuthenticationStatus, ResumptionToken};
13 use neqo_http3::{
14 Header, Http3Client, Http3ClientEvent, Http3OrWebTransportStream, Http3Parameters, Http3Server,
15 Http3ServerEvent, Http3State, Priority,
16 };
17 use neqo_transport::{CloseReason, ConnectionParameters, Error, Output, StreamType};
18 use test_fixture::*;
19
20 const RESPONSE_DATA: &[u8] = &[0x61, 0x62, 0x63];
21
22 fn receive_request(server: &Http3Server) -> Option<Http3OrWebTransportStream> {
23 while let Some(event) = server.next_event() {
24 if let Http3ServerEvent::Headers {
25 stream,
26 headers,
27 fin,
28 } = event
29 {
30 assert_eq!(
31 &headers,
32 &[
33 Header::new(":method", "GET"),
34 Header::new(":scheme", "https"),
35 Header::new(":authority", "something.com"),
36 Header::new(":path", "/")
37 ]
38 );
39 assert!(fin);
40
41 return Some(stream);
42 }
43 }
44 None
45 }
46
47 fn set_response(request: &Http3OrWebTransportStream) {
48 request
49 .send_headers(&[
50 Header::new(":status", "200"),
51 Header::new("content-length", "3"),
52 ])
53 .unwrap();
54 request.send_data(RESPONSE_DATA).unwrap();
55 request.stream_close_send().unwrap();
56 }
57
58 fn process_server_events(server: &Http3Server) {
59 let request = receive_request(server).unwrap();
60 set_response(&request);
61 }
62
63 fn process_client_events(conn: &mut Http3Client) {
64 let mut response_header_found = false;
65 let mut response_data_found = false;
66 while let Some(event) = conn.next_event() {
67 match event {
68 Http3ClientEvent::HeaderReady { headers, fin, .. } => {
69 assert_eq!(
70 &headers,
71 &[
72 Header::new(":status", "200"),
73 Header::new("content-length", "3"),
74 ]
75 );
76 assert!(!fin);
77 response_header_found = true;
78 }
79 Http3ClientEvent::DataReadable { stream_id } => {
80 let mut buf = [0u8; 100];
81 let (amount, fin) = conn.read_data(now(), stream_id, &mut buf).unwrap();
82 assert!(fin);
83 assert_eq!(amount, RESPONSE_DATA.len());
84 assert_eq!(&buf[..RESPONSE_DATA.len()], RESPONSE_DATA);
85 response_data_found = true;
86 }
87 _ => {}
88 }
89 }
90 assert!(response_header_found);
91 assert!(response_data_found);
92 }
93
94 fn connect_peers(hconn_c: &mut Http3Client, hconn_s: &mut Http3Server) -> Option<Datagram> {
95 assert_eq!(hconn_c.state(), Http3State::Initializing);
96 let out = hconn_c.process_output(now()); // Initial
97 let out2 = hconn_c.process_output(now()); // Initial
98 _ = hconn_s.process(out.dgram(), now()); // ACK
99 let out = hconn_s.process(out2.dgram(), now()); // Initial + Handshake
100 let out = hconn_c.process(out.dgram(), now());
101 let out = hconn_s.process(out.dgram(), now());
102 let out = hconn_c.process(out.dgram(), now());
103 drop(hconn_s.process(out.dgram(), now())); // consume ACK
104 let authentication_needed = |e| matches!(e, Http3ClientEvent::AuthenticationNeeded);
105 assert!(hconn_c.events().any(authentication_needed));
106 hconn_c.authenticated(AuthenticationStatus::Ok, now());
107 let out = hconn_c.process_output(now()); // Handshake
108 assert_eq!(hconn_c.state(), Http3State::Connected);
109 let out = hconn_s.process(out.dgram(), now()); // Handshake
110 let out = hconn_c.process(out.dgram(), now());
111 let out = hconn_s.process(out.dgram(), now());
112 // assert!(hconn_s.settings_received);
113 let out = hconn_c.process(out.dgram(), now());
114 // assert!(hconn_c.settings_received);
115
116 out.dgram()
117 }
118
119 fn connect_peers_with_network_propagation_delay(
120 hconn_c: &mut Http3Client,
121 hconn_s: &mut Http3Server,
122 net_delay: u64,
123 ) -> (Option<Datagram>, Instant) {
124 let net_delay = Duration::from_millis(net_delay);
125 assert_eq!(hconn_c.state(), Http3State::Initializing);
126 let mut now = now();
127 let out = hconn_c.process_output(now); // Initial
128 let out2 = hconn_c.process_output(now); // Initial
129 now += net_delay;
130 _ = hconn_s.process(out.dgram(), now); // ACK
131 let out = hconn_s.process(out2.dgram(), now);
132 now += net_delay;
133 let out = hconn_c.process(out.dgram(), now);
134 now += net_delay;
135 let out = hconn_s.process(out.dgram(), now);
136 now += net_delay;
137 let out = hconn_c.process(out.dgram(), now); // ACK
138 now += net_delay;
139 let out = hconn_s.process(out.dgram(), now); // consume ACK
140 assert!(out.dgram().is_none());
141 let authentication_needed = |e| matches!(e, Http3ClientEvent::AuthenticationNeeded);
142 assert!(hconn_c.events().any(authentication_needed));
143 now += net_delay;
144 hconn_c.authenticated(AuthenticationStatus::Ok, now);
145 let out = hconn_c.process_output(now); // Handshake
146 assert_eq!(hconn_c.state(), Http3State::Connected);
147 now += net_delay;
148 let out = hconn_s.process(out.dgram(), now); // HANDSHAKE_DONE
149 now += net_delay;
150 let out = hconn_c.process(out.dgram(), now); // Consume HANDSHAKE_DONE, send control streams.
151 now += net_delay;
152 let out = hconn_s.process(out.dgram(), now); // consume and send control streams.
153 now += net_delay;
154 let out = hconn_c.process(out.dgram(), now); // consume control streams.
155 (out.dgram(), now)
156 }
157
158 #[must_use]
159 pub fn connect() -> (Http3Client, Http3Server, Option<Datagram>) {
160 let mut hconn_c = default_http3_client();
161 let mut hconn_s = default_http3_server();
162
163 let out = connect_peers(&mut hconn_c, &mut hconn_s);
164 (hconn_c, hconn_s, out)
165 }
166
167 fn exchange_packets(client: &mut Http3Client, server: &mut Http3Server, out_ex: Option<Datagram>) {
168 let mut out = out_ex;
169 loop {
170 out = client.process(out, now()).dgram();
171 out = server.process(out, now()).dgram();
172 if out.is_none() {
173 break;
174 }
175 }
176 }
177
178 #[test]
179 fn simple_connect() {
180 let (_hconn_c, _hconn_s, _d) = connect();
181 }
182
183 #[test]
184 fn fetch() {
185 let (mut hconn_c, mut hconn_s, dgram) = connect();
186
187 qtrace!("-----client");
188 let req = hconn_c
189 .fetch(
190 now(),
191 "GET",
192 &("https", "something.com", "/"),
193 &[],
194 Priority::default(),
195 )
196 .unwrap();
197 assert_eq!(req, 0);
198 hconn_c.stream_close_send(req).unwrap();
199 let out = hconn_c.process(dgram, now());
200 qtrace!("-----server");
201 let out = hconn_s.process(out.dgram(), now());
202 drop(hconn_c.process(out.dgram(), now()));
203 process_server_events(&hconn_s);
204 let out = hconn_s.process(None::<Datagram>, now());
205
206 qtrace!("-----client");
207 drop(hconn_c.process(out.dgram(), now()));
208 let out = hconn_s.process(None::<Datagram>, now());
209 drop(hconn_c.process(out.dgram(), now()));
210 process_client_events(&mut hconn_c);
211 }
212
213 #[test]
214 fn response_103() {
215 let (mut hconn_c, mut hconn_s, dgram) = connect();
216
217 let req = hconn_c
218 .fetch(
219 now(),
220 "GET",
221 &("https", "something.com", "/"),
222 &[],
223 Priority::default(),
224 )
225 .unwrap();
226 assert_eq!(req, 0);
227 hconn_c.stream_close_send(req).unwrap();
228 let out = hconn_c.process(dgram, now());
229
230 let out = hconn_s.process(out.dgram(), now());
231 drop(hconn_c.process(out.dgram(), now()));
232 let request = receive_request(&hconn_s).unwrap();
233 let info_headers = [
234 Header::new(":status", "103"),
235 Header::new("link", "</style.css>; rel=preload; as=style"),
236 ];
237 // Send 103
238 request.send_headers(&info_headers).unwrap();
239 let out = hconn_s.process(None::<Datagram>, now());
240
241 drop(hconn_c.process(out.dgram(), now()));
242
243 let info_headers_event = |e| {
244 matches!(e, Http3ClientEvent::HeaderReady { headers,
245 interim,
246 fin, .. } if !fin && interim && headers.as_ref() == info_headers)
247 };
248 assert!(hconn_c.events().any(info_headers_event));
249
250 set_response(&request);
251 let out = hconn_s.process(None::<Datagram>, now());
252 drop(hconn_c.process(out.dgram(), now()));
253 process_client_events(&mut hconn_c);
254 }
255
256 /// Test [`neqo_http3::SendMessage::send_data`] to set
257 /// [`neqo_transport::SendStream::set_writable_event_low_watermark`].
258 #[expect(clippy::cast_possible_truncation, reason = "OK in a test.")]
259 #[test]
260 fn data_writable_events_low_watermark() -> Result<(), Box<dyn std::error::Error>> {
261 const STREAM_LIMIT: u64 = 5000;
262 const DATA_FRAME_HEADER_SIZE: usize = 3;
263
264 // Create a client and a server.
265 let mut hconn_c = http3_client_with_params(Http3Parameters::default().connection_parameters(
266 ConnectionParameters::default().max_stream_data(StreamType::BiDi, false, STREAM_LIMIT),
267 ));
268 let mut hconn_s = default_http3_server();
269 drop(connect_peers(&mut hconn_c, &mut hconn_s));
270
271 // Client sends GET to server.
272 let stream_id = hconn_c.fetch(
273 now(),
274 "GET",
275 &("https", "something.com", "/"),
276 &[],
277 Priority::default(),
278 )?;
279 hconn_c.stream_close_send(stream_id)?;
280 exchange_packets(&mut hconn_c, &mut hconn_s, None);
281
282 // Server receives GET and responds with headers.
283 let request = receive_request(&hconn_s).unwrap();
284 request.send_headers(&[Header::new(":status", "200")])?;
285
286 // Sending these headers clears the server's send stream buffer and thus
287 // emits a DataWritable event.
288 exchange_packets(&mut hconn_c, &mut hconn_s, None);
289 let data_writable = |e| {
290 matches!(
291 e,
292 Http3ServerEvent::DataWritable {
293 stream
294 } if stream.stream_id() == stream_id
295 )
296 };
297 assert!(hconn_s.events().any(data_writable));
298
299 // Have server fill entire send buffer minus 1 byte.
300 let all_but_one = request.available()? - DATA_FRAME_HEADER_SIZE - 1;
301 let buf = vec![1; all_but_one];
302 let sent = request.send_data(&buf)?;
303 assert_eq!(sent, all_but_one);
304 assert_eq!(request.available()?, 1);
305
306 // Sending the buffered data clears the send stream buffer and thus emits a
307 // DataWritable event.
308 exchange_packets(&mut hconn_c, &mut hconn_s, None);
309 assert!(hconn_s.events().any(data_writable));
310
311 // Sending more fails, given that each data frame needs to be preceded by a
312 // header, i.e. needs more than 1 byte of send space to send 1 byte payload.
313 assert_eq!(request.available()?, 1);
314 assert_eq!(request.send_data(&buf)?, 0);
315
316 // Have the client read all the pending data.
317 let mut recv_buf = vec![0_u8; all_but_one];
318 let (recvd, _) = hconn_c.read_data(now(), stream_id, &mut recv_buf)?;
319 assert_eq!(sent, recvd);
320 exchange_packets(&mut hconn_c, &mut hconn_s, None);
321
322 // Expect the server's available send space to be back to the stream limit.
323 assert_eq!(request.available()?, STREAM_LIMIT as usize);
324
325 // Expect the server to emit a DataWritable event, even though it always had
326 // at least 1 byte available to send, i.e. it never exhausted the entire
327 // available send space.
328 assert!(hconn_s.events().any(data_writable));
329
330 Ok(())
331 }
332
333 #[test]
334 fn data_writable_events() {
335 const STREAM_LIMIT: u64 = 5000;
336 const DATA_AMOUNT: usize = 10000;
337
338 let mut hconn_c = http3_client_with_params(Http3Parameters::default().connection_parameters(
339 ConnectionParameters::default().max_stream_data(StreamType::BiDi, false, STREAM_LIMIT),
340 ));
341 let mut hconn_s = default_http3_server();
342
343 drop(connect_peers(&mut hconn_c, &mut hconn_s));
344
345 // Create a request.
346 let req = hconn_c
347 .fetch(
348 now(),
349 "GET",
350 &("https", "something.com", "/"),
351 &[],
352 Priority::default(),
353 )
354 .unwrap();
355 hconn_c.stream_close_send(req).unwrap();
356 exchange_packets(&mut hconn_c, &mut hconn_s, None);
357
358 let request = receive_request(&hconn_s).unwrap();
359
360 request
361 .send_headers(&[
362 Header::new(":status", "200"),
363 Header::new("content-length", DATA_AMOUNT.to_string()),
364 ])
365 .unwrap();
366
367 // Send a lot of data
368 let buf = &[1; DATA_AMOUNT];
369 let mut sent = request.send_data(buf).unwrap();
370 assert!(sent < DATA_AMOUNT);
371
372 // Exchange packets and read the data on the client side.
373 exchange_packets(&mut hconn_c, &mut hconn_s, None);
374 let stream_id = request.stream_id();
375 let mut recv_buf = [0_u8; DATA_AMOUNT];
376 let (mut recvd, _) = hconn_c.read_data(now(), stream_id, &mut recv_buf).unwrap();
377 assert_eq!(sent, recvd);
378 exchange_packets(&mut hconn_c, &mut hconn_s, None);
379
380 let data_writable = |e| {
381 matches!(
382 e,
383 Http3ServerEvent::DataWritable {
384 stream
385 } if stream.stream_id() == stream_id
386 )
387 };
388 // Make sure we have a DataWritable event.
389 assert!(hconn_s.events().any(data_writable));
390 // Data can be sent again.
391 let s = request.send_data(&buf[sent..]).unwrap();
392 assert!(s > 0);
393 sent += s;
394
395 // Exchange packets and read the data on the client side.
396 exchange_packets(&mut hconn_c, &mut hconn_s, None);
397 let (r, _) = hconn_c
398 .read_data(now(), stream_id, &mut recv_buf[recvd..])
399 .unwrap();
400 recvd += r;
401 exchange_packets(&mut hconn_c, &mut hconn_s, None);
402 assert_eq!(sent, recvd);
403
404 // One more DataWritable event.
405 assert!(hconn_s.events().any(data_writable));
406 // Send more data.
407 let s = request.send_data(&buf[sent..]).unwrap();
408 assert!(s > 0);
409 sent += s;
410 assert_eq!(sent, DATA_AMOUNT);
411
412 exchange_packets(&mut hconn_c, &mut hconn_s, None);
413 let (r, _) = hconn_c
414 .read_data(now(), stream_id, &mut recv_buf[recvd..])
415 .unwrap();
416 recvd += r;
417
418 // Make sure all data is received by the client.
419 assert_eq!(recvd, DATA_AMOUNT);
420 assert_eq!(&recv_buf, buf);
421 }
422
423 fn get_token(client: &mut Http3Client) -> ResumptionToken {
424 assert_eq!(client.state(), Http3State::Connected);
425 client
426 .events()
427 .find_map(|e| {
428 if let Http3ClientEvent::ResumptionToken(token) = e {
429 Some(token)
430 } else {
431 None
432 }
433 })
434 .unwrap()
435 }
436
437 #[test]
438 fn zerortt() {
439 let (mut hconn_c, _, dgram) = connect();
440 let token = get_token(&mut hconn_c);
441
442 // Create a new connection with a resumption token.
443 let mut hconn_c = default_http3_client();
444 hconn_c
445 .enable_resumption(now(), &token)
446 .expect("Set resumption token");
447 let mut hconn_s = default_http3_server();
448
449 // Create a request.
450 let req = hconn_c
451 .fetch(
452 now(),
453 "GET",
454 &("https", "something.com", "/"),
455 &[],
456 Priority::default(),
457 )
458 .unwrap();
459 hconn_c.stream_close_send(req).unwrap();
460
461 let out = hconn_c.process(dgram, now());
462 let out2 = hconn_c.process_output(now());
463 _ = hconn_s.process(out.dgram(), now());
464 let out = hconn_s.process(out2.dgram(), now());
465
466 let out = hconn_c.process(out.dgram(), now());
467 let out = hconn_s.process(out.dgram(), now());
468
469 let mut request_stream = None;
470 let mut zerortt_state_change = false;
471 while let Some(event) = hconn_s.next_event() {
472 match event {
473 Http3ServerEvent::Headers {
474 stream,
475 headers,
476 fin,
477 } => {
478 assert_eq!(
479 &headers,
480 &[
481 Header::new(":method", "GET"),
482 Header::new(":scheme", "https"),
483 Header::new(":authority", "something.com"),
484 Header::new(":path", "/")
485 ]
486 );
487 assert!(fin);
488
489 request_stream = Some(stream);
490 }
491 Http3ServerEvent::StateChange { state, .. } => {
492 assert_eq!(state, Http3State::ZeroRtt);
493 zerortt_state_change = true;
494 }
495 _ => {}
496 }
497 }
498 assert!(zerortt_state_change);
499 let request_stream = request_stream.unwrap();
500
501 // Send a response
502 set_response(&request_stream);
503
504 // Receive the response
505 exchange_packets(&mut hconn_c, &mut hconn_s, out.dgram());
506 process_client_events(&mut hconn_c);
507 }
508
509 #[test]
510 /// When a client has an outstanding fetch, it will send keepalives.
511 /// Test that it will successfully run until the connection times out.
512 fn fetch_noresponse_will_idletimeout() {
513 let mut hconn_c = default_http3_client();
514 let mut hconn_s = default_http3_server();
515
516 let (dgram, mut now) =
517 connect_peers_with_network_propagation_delay(&mut hconn_c, &mut hconn_s, 10);
518
519 qtrace!("-----client");
520 let req = hconn_c
521 .fetch(
522 now,
523 "GET",
524 &("https", "something.com", "/"),
525 &[],
526 Priority::default(),
527 )
528 .unwrap();
529 assert_eq!(req, 0);
530 hconn_c.stream_close_send(req).unwrap();
531 let _out = hconn_c.process(dgram, now);
532 qtrace!("-----server");
533
534 let mut done = false;
535 while !done {
536 while let Some(event) = hconn_c.next_event() {
537 if let Http3ClientEvent::StateChange(
538 Http3State::Closing(error_code) | Http3State::Closed(error_code),
539 ) = event
540 {
541 assert_eq!(error_code, CloseReason::Transport(Error::IdleTimeout));
542 done = true;
543 }
544 }
545
546 if let Output::Callback(t) = hconn_c.process_output(now) {
547 now += t;
548 }
549 }
550 }