rwebtransport 0.2.2 → 0.2.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (99) hide show
  1. package/Cargo.lock +523 -140
  2. package/Cargo.toml +5 -5
  3. package/README.md +8 -4
  4. package/crates/echo-server/src/bin/gen-test-cert.rs +1 -1
  5. package/crates/native/Cargo.toml +2 -0
  6. package/crates/native/src/config.rs +69 -8
  7. package/crates/native/src/driver.rs +253 -90
  8. package/crates/native/src/lib.rs +80 -57
  9. package/crates/native/src/parser_memory.rs +203 -0
  10. package/crates/native/src/server.rs +215 -183
  11. package/crates/native/src/session.rs +1341 -243
  12. package/crates/native/src/test_support.rs +119 -0
  13. package/crates/wtcore/Cargo.toml +1 -0
  14. package/crates/wtcore/src/h3.rs +250 -46
  15. package/dist/index.js +218 -75
  16. package/dist/index.js.map +7 -1
  17. package/dist/index.mjs +214 -69
  18. package/dist/index.mjs.map +7 -1
  19. package/dist/native.d.ts +10 -4
  20. package/dist/server.d.ts +1 -0
  21. package/package.json +84 -78
  22. package/prebuilds/darwin-arm64/rwebtransport.node +0 -0
  23. package/prebuilds/linux-arm64/rwebtransport.node +0 -0
  24. package/prebuilds/linux-x64/rwebtransport.node +0 -0
  25. package/prebuilds/win32-x64/rwebtransport.node +0 -0
  26. package/scripts/build-linux-prebuilt.sh +46 -0
  27. package/scripts/build-ts.js +41 -0
  28. package/scripts/build.js +10 -3
  29. package/vendor/quiche/AGENTS.md +10 -0
  30. package/vendor/quiche/Cargo.lock +239 -248
  31. package/vendor/quiche/Cargo.toml +23 -10
  32. package/vendor/quiche/examples/Makefile +4 -4
  33. package/vendor/quiche/examples/client.rs +10 -28
  34. package/vendor/quiche/examples/http3-client.rs +20 -34
  35. package/vendor/quiche/examples/http3-server.rs +47 -78
  36. package/vendor/quiche/examples/server.rs +19 -49
  37. package/vendor/quiche/include/quiche.h +35 -4
  38. package/vendor/quiche/src/build.rs +17 -0
  39. package/vendor/quiche/src/cid.rs +129 -61
  40. package/vendor/quiche/src/crypto/boringssl.rs +98 -86
  41. package/vendor/quiche/src/crypto/mod.rs +64 -77
  42. package/vendor/quiche/src/dgram.rs +2 -3
  43. package/vendor/quiche/src/error.rs +22 -20
  44. package/vendor/quiche/src/ffi.rs +558 -280
  45. package/vendor/quiche/src/flowcontrol.rs +0 -7
  46. package/vendor/quiche/src/frame.rs +134 -135
  47. package/vendor/quiche/src/h3/ffi.rs +73 -60
  48. package/vendor/quiche/src/h3/frame.rs +70 -90
  49. package/vendor/quiche/src/h3/mod.rs +1024 -593
  50. package/vendor/quiche/src/h3/qpack/decoder.rs +248 -34
  51. package/vendor/quiche/src/h3/qpack/dynamic_table.rs +859 -0
  52. package/vendor/quiche/src/h3/qpack/encoder.rs +14 -17
  53. package/vendor/quiche/src/h3/qpack/mod.rs +48 -0
  54. package/vendor/quiche/src/h3/qpack/static_table.rs +86 -73
  55. package/vendor/quiche/src/h3/stream.rs +1009 -194
  56. package/vendor/quiche/src/lib.rs +1361 -1195
  57. package/vendor/quiche/src/minmax.rs +2 -6
  58. package/vendor/quiche/src/packet.rs +420 -552
  59. package/vendor/quiche/src/path.rs +202 -72
  60. package/vendor/quiche/src/pmtud.rs +18 -16
  61. package/vendor/quiche/src/ranges.rs +184 -82
  62. package/vendor/quiche/src/recovery/AGENTS.md +5 -2
  63. package/vendor/quiche/src/recovery/bandwidth.rs +59 -40
  64. package/vendor/quiche/src/recovery/bytes_in_flight.rs +2 -2
  65. package/vendor/quiche/src/recovery/congestion/cubic.rs +38 -47
  66. package/vendor/quiche/src/recovery/congestion/delivery_rate.rs +54 -60
  67. package/vendor/quiche/src/recovery/congestion/hystart.rs +6 -10
  68. package/vendor/quiche/src/recovery/congestion/mod.rs +110 -42
  69. package/vendor/quiche/src/recovery/congestion/prr.rs +4 -1
  70. package/vendor/quiche/src/recovery/congestion/recovery.rs +91 -95
  71. package/vendor/quiche/src/recovery/congestion/reno.rs +17 -12
  72. package/vendor/quiche/src/recovery/congestion/test_sender.rs +8 -27
  73. package/vendor/quiche/src/recovery/gcongestion/bbr/bandwidth_sampler.rs +159 -247
  74. package/vendor/quiche/src/recovery/gcongestion/bbr/windowed_filter.rs +9 -14
  75. package/vendor/quiche/src/recovery/gcongestion/bbr2/drain.rs +18 -15
  76. package/vendor/quiche/src/recovery/gcongestion/bbr2/mode.rs +43 -28
  77. package/vendor/quiche/src/recovery/gcongestion/bbr2/network_model.rs +349 -76
  78. package/vendor/quiche/src/recovery/gcongestion/bbr2/probe_bw.rs +147 -195
  79. package/vendor/quiche/src/recovery/gcongestion/bbr2/probe_rtt.rs +29 -27
  80. package/vendor/quiche/src/recovery/gcongestion/bbr2/rtt_jump_detector/global_min.rs +180 -0
  81. package/vendor/quiche/src/recovery/gcongestion/bbr2/rtt_jump_detector/global_min_tests.rs +221 -0
  82. package/vendor/quiche/src/recovery/gcongestion/bbr2/rtt_jump_detector/hmm.rs +395 -0
  83. package/vendor/quiche/src/recovery/gcongestion/bbr2/rtt_jump_detector/hmm_tests.rs +473 -0
  84. package/vendor/quiche/src/recovery/gcongestion/bbr2/rtt_jump_detector/mod.rs +175 -0
  85. package/vendor/quiche/src/recovery/gcongestion/bbr2/startup.rs +33 -26
  86. package/vendor/quiche/src/recovery/gcongestion/bbr2.rs +107 -60
  87. package/vendor/quiche/src/recovery/gcongestion/mod.rs +64 -11
  88. package/vendor/quiche/src/recovery/gcongestion/pacer.rs +34 -25
  89. package/vendor/quiche/src/recovery/gcongestion/recovery.rs +81 -86
  90. package/vendor/quiche/src/recovery/mod.rs +414 -173
  91. package/vendor/quiche/src/recovery/rtt.rs +8 -5
  92. package/vendor/quiche/src/stream/mod.rs +864 -133
  93. package/vendor/quiche/src/stream/recv_buf.rs +476 -172
  94. package/vendor/quiche/src/stream/send_buf.rs +343 -81
  95. package/vendor/quiche/src/test_utils.rs +78 -64
  96. package/vendor/quiche/src/tests.rs +2559 -1335
  97. package/vendor/quiche/src/tls/boringssl.rs +60 -63
  98. package/vendor/quiche/src/tls/mod.rs +146 -193
  99. package/vendor/quiche/src/transport_params.rs +87 -103
@@ -0,0 +1,119 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ //! Real QUIC pairs for native protocol regression tests.
3
+ use crate::config::{build_config, build_server_config, ClientConfigParams};
4
+ use boring::{
5
+ asn1::Asn1Time,
6
+ bn::BigNum,
7
+ ec::{EcGroup, EcKey},
8
+ hash::MessageDigest,
9
+ nid::Nid,
10
+ pkey::PKey,
11
+ x509::{
12
+ extension::{BasicConstraints, SubjectAlternativeName},
13
+ X509NameBuilder, X509,
14
+ },
15
+ };
16
+ use std::sync::atomic::{AtomicU64, Ordering};
17
+
18
+ pub fn pair(
19
+ expected_ip: Option<std::net::IpAddr>,
20
+ name: Option<&str>,
21
+ ip_san: bool,
22
+ ) -> (quiche::Connection, quiche::Connection) {
23
+ let group = EcGroup::from_curve_name(Nid::X9_62_PRIME256V1).unwrap();
24
+ let key = PKey::from_ec_key(EcKey::generate(&group).unwrap()).unwrap();
25
+ let mut subject = X509NameBuilder::new().unwrap();
26
+ subject.append_entry_by_text("CN", "wrong.example").unwrap();
27
+ let subject = subject.build();
28
+ let mut cert = X509::builder().unwrap();
29
+ cert.set_version(2).unwrap();
30
+ cert.set_serial_number(&BigNum::from_u32(1).unwrap().to_asn1_integer().unwrap())
31
+ .unwrap();
32
+ cert.set_subject_name(&subject).unwrap();
33
+ cert.set_issuer_name(&subject).unwrap();
34
+ cert.set_pubkey(&key).unwrap();
35
+ cert.set_not_before(&Asn1Time::days_from_now(0).unwrap())
36
+ .unwrap();
37
+ cert.set_not_after(&Asn1Time::days_from_now(1).unwrap())
38
+ .unwrap();
39
+ cert.append_extension(&BasicConstraints::new().critical().ca().build().unwrap())
40
+ .unwrap();
41
+ let mut san = SubjectAlternativeName::new();
42
+ san.dns("wrong.example");
43
+ if ip_san {
44
+ san.ip("127.0.0.1").ip("::1");
45
+ }
46
+ let san = san.build(&cert.x509v3_context(None, None)).unwrap();
47
+ cert.append_extension(&san).unwrap();
48
+ cert.sign(&key, MessageDigest::sha256()).unwrap();
49
+ static NEXT: AtomicU64 = AtomicU64::new(0);
50
+ let dir = std::env::temp_dir().join(format!(
51
+ "rwt-native-test-{}-{}",
52
+ std::process::id(),
53
+ NEXT.fetch_add(1, Ordering::Relaxed)
54
+ ));
55
+ std::fs::create_dir(&dir).unwrap();
56
+ let cert_path = dir.join("cert.pem");
57
+ let key_path = dir.join("key.pem");
58
+ std::fs::write(&cert_path, cert.build().to_pem().unwrap()).unwrap();
59
+ std::fs::write(&key_path, key.private_key_to_pem_pkcs8().unwrap()).unwrap();
60
+ let mut cc = build_config(&ClientConfigParams {
61
+ expected_ip,
62
+ ..Default::default()
63
+ })
64
+ .unwrap();
65
+ cc.load_verify_locations_from_file(cert_path.to_str().unwrap())
66
+ .unwrap();
67
+ let mut sc =
68
+ build_server_config(cert_path.to_str().unwrap(), key_path.to_str().unwrap()).unwrap();
69
+ std::fs::remove_dir_all(&dir).unwrap();
70
+ let ca = "127.0.0.1:1234".parse().unwrap();
71
+ let sa = "127.0.0.1:4433".parse().unwrap();
72
+ let client = quiche::connect(
73
+ name,
74
+ &quiche::ConnectionId::from_ref(&[1; 16]),
75
+ ca,
76
+ sa,
77
+ &mut cc,
78
+ )
79
+ .unwrap();
80
+ let server = quiche::accept(
81
+ &quiche::ConnectionId::from_ref(&[2; 16]),
82
+ None,
83
+ sa,
84
+ ca,
85
+ &mut sc,
86
+ )
87
+ .unwrap();
88
+ (client, server)
89
+ }
90
+
91
+ pub fn exchange(client: &mut quiche::Connection, server: &mut quiche::Connection) {
92
+ let mut buf = [0; 1350];
93
+ for _ in 0..100 {
94
+ let mut moved = false;
95
+ while let Ok((n, info)) = client.send(&mut buf) {
96
+ moved = true;
97
+ let _ = server.recv(
98
+ &mut buf[..n],
99
+ quiche::RecvInfo {
100
+ from: info.from,
101
+ to: info.to,
102
+ },
103
+ );
104
+ }
105
+ while let Ok((n, info)) = server.send(&mut buf) {
106
+ moved = true;
107
+ let _ = client.recv(
108
+ &mut buf[..n],
109
+ quiche::RecvInfo {
110
+ from: info.from,
111
+ to: info.to,
112
+ },
113
+ );
114
+ }
115
+ if !moved {
116
+ break;
117
+ }
118
+ }
119
+ }
@@ -13,3 +13,4 @@ path = "src/lib.rs"
13
13
  [dependencies]
14
14
  quiche.workspace = true
15
15
  octets.workspace = true
16
+ sfv = "0.16"
@@ -33,6 +33,25 @@ pub const SETTINGS_H3_DATAGRAM: u64 = 0x33;
33
33
  pub const SETTINGS_WT_MAX_SESSIONS: u64 = 0x14e9_cd29;
34
34
  /// Older draft `SETTINGS_ENABLE_WEBTRANSPORT` (kept for maximum compatibility).
35
35
  pub const SETTINGS_ENABLE_WEBTRANSPORT: u64 = 0x2b60_3742;
36
+ /// draft-ietf-webtrans-http3-17 SETTINGS_WT_ENABLED.
37
+ pub const SETTINGS_WT_ENABLED: u64 = 0x20b8_933b;
38
+ pub const SETTINGS_WT_ENABLED_DRAFT15: u64 = 0x2c7c_f000;
39
+ pub const LEGACY_WT_TOKEN: &[u8] = b"webtransport";
40
+ pub const WT_H3_TOKEN: &[u8] = b"webtransport-h3";
41
+ pub const WT_EXPORTER_LABEL: &[u8] = b"EXPORTER-WebTransport";
42
+
43
+ /// Serialize the session-bound exporter context from WebTransport-H3 §4.8.
44
+ pub fn exporter_context(session_id: u64, label: &[u8], context: &[u8]) -> Option<Vec<u8>> {
45
+ let label_len = u8::try_from(label.len()).ok()?;
46
+ let context_len = u8::try_from(context.len()).ok()?;
47
+ let mut output = Vec::with_capacity(10 + label.len() + context.len());
48
+ output.extend_from_slice(&session_id.to_be_bytes());
49
+ output.push(label_len);
50
+ output.extend_from_slice(label);
51
+ output.push(context_len);
52
+ output.extend_from_slice(context);
53
+ Some(output)
54
+ }
36
55
  /// `SETTINGS_WT_INITIAL_MAX_DATA`: initial per-session send-data allowance.
37
56
  pub const SETTINGS_WT_INITIAL_MAX_DATA: u64 = 0x2b61;
38
57
  /// `SETTINGS_WT_INITIAL_MAX_STREAMS_UNI`: initial per-session uni stream limit.
@@ -171,9 +190,20 @@ pub fn frame(ty: u64, payload: &[u8]) -> Vec<u8> {
171
190
  /// Bytes for the client control stream: the stream-type prefix followed by our
172
191
  /// SETTINGS frame.
173
192
  pub fn control_stream_prefix() -> Vec<u8> {
193
+ control_stream_prefix_for(false)
194
+ }
195
+
196
+ pub fn control_stream_prefix_for(reliable_reset: bool) -> Vec<u8> {
174
197
  let mut out = Vec::new();
175
198
  put_varint(H3_CONTROL_STREAM_TYPE, &mut out);
176
- out.extend_from_slice(&frame(FRAME_SETTINGS, &settings_payload()));
199
+ let mut settings = settings_payload();
200
+ if reliable_reset {
201
+ put_varint(SETTINGS_WT_ENABLED, &mut settings);
202
+ put_varint(1, &mut settings);
203
+ put_varint(SETTINGS_WT_ENABLED_DRAFT15, &mut settings);
204
+ put_varint(1, &mut settings);
205
+ }
206
+ out.extend_from_slice(&frame(FRAME_SETTINGS, &settings));
177
207
  out
178
208
  }
179
209
 
@@ -188,7 +218,7 @@ pub fn settings_payload() -> Vec<u8> {
188
218
  (SETTINGS_ENABLE_CONNECT_PROTOCOL, 1),
189
219
  (SETTINGS_H3_DATAGRAM, 1),
190
220
  (SETTINGS_ENABLE_WEBTRANSPORT, 1),
191
- (SETTINGS_WT_MAX_SESSIONS, 256),
221
+ (SETTINGS_WT_MAX_SESSIONS, 1),
192
222
  (SETTINGS_WT_INITIAL_MAX_DATA, WT_INITIAL_MAX_DATA),
193
223
  (SETTINGS_WT_INITIAL_MAX_STREAMS_BIDI, WT_INITIAL_MAX_STREAMS),
194
224
  (SETTINGS_WT_INITIAL_MAX_STREAMS_UNI, WT_INITIAL_MAX_STREAMS),
@@ -206,6 +236,8 @@ pub struct PeerSettings {
206
236
  pub enable_connect_protocol: bool,
207
237
  pub h3_datagram: bool,
208
238
  pub enable_webtransport: bool,
239
+ pub wt_enabled: bool,
240
+ pub wt_enabled_draft15: bool,
209
241
  pub wt_max_sessions: u64,
210
242
  /// Peer's initial per-session send-data allowance (SETTINGS_WT_INITIAL_MAX_DATA).
211
243
  pub wt_initial_max_data: u64,
@@ -225,19 +257,38 @@ impl PeerSettings {
225
257
  }
226
258
 
227
259
  /// Parse a SETTINGS frame payload. Unknown identifiers are ignored (as required).
228
- pub fn parse_settings(mut payload: &[u8]) -> PeerSettings {
260
+ pub fn parse_settings(mut payload: &[u8]) -> Result<PeerSettings, String> {
261
+ let mut seen = std::collections::HashSet::new();
229
262
  let mut s = PeerSettings::default();
230
263
  while !payload.is_empty() {
231
- let Some((id, n1)) = read_varint(payload) else {
232
- break;
233
- };
234
- let Some((val, n2)) = read_varint(&payload[n1..]) else {
235
- break;
236
- };
264
+ let (id, n1) = read_varint(payload).ok_or("truncated SETTINGS identifier")?;
265
+ let (val, n2) = read_varint(&payload[n1..]).ok_or("truncated SETTINGS value")?;
266
+ if !seen.insert(id) || matches!(id, 0x2..=0x5) {
267
+ return Err("duplicate or reserved SETTINGS identifier".into());
268
+ }
269
+ if matches!(
270
+ id,
271
+ SETTINGS_ENABLE_CONNECT_PROTOCOL
272
+ | SETTINGS_H3_DATAGRAM
273
+ | SETTINGS_ENABLE_WEBTRANSPORT
274
+ | SETTINGS_WT_ENABLED
275
+ ) && val > 1
276
+ {
277
+ return Err("invalid boolean SETTINGS value".into());
278
+ }
279
+ if matches!(
280
+ id,
281
+ SETTINGS_WT_INITIAL_MAX_STREAMS_BIDI | SETTINGS_WT_INITIAL_MAX_STREAMS_UNI
282
+ ) && val > (1 << 60)
283
+ {
284
+ return Err("invalid WebTransport stream limit".into());
285
+ }
237
286
  match id {
238
287
  SETTINGS_ENABLE_CONNECT_PROTOCOL => s.enable_connect_protocol = val != 0,
239
288
  SETTINGS_H3_DATAGRAM => s.h3_datagram = val != 0,
240
289
  SETTINGS_ENABLE_WEBTRANSPORT => s.enable_webtransport = val != 0,
290
+ SETTINGS_WT_ENABLED => s.wt_enabled = val != 0,
291
+ SETTINGS_WT_ENABLED_DRAFT15 => s.wt_enabled_draft15 = val != 0,
241
292
  SETTINGS_WT_MAX_SESSIONS => s.wt_max_sessions = val,
242
293
  SETTINGS_WT_INITIAL_MAX_DATA => s.wt_initial_max_data = val,
243
294
  SETTINGS_WT_INITIAL_MAX_STREAMS_BIDI => s.wt_initial_max_streams_bidi = val,
@@ -246,7 +297,7 @@ pub fn parse_settings(mut payload: &[u8]) -> PeerSettings {
246
297
  }
247
298
  payload = &payload[n1 + n2..];
248
299
  }
249
- s
300
+ Ok(s)
250
301
  }
251
302
 
252
303
  /// Request header carrying the client's offered WebTransport subprotocols
@@ -256,6 +307,84 @@ pub const WT_AVAILABLE_PROTOCOLS: &[u8] = b"wt-available-protocols";
256
307
  /// Structured-Field Item String.
257
308
  pub const WT_PROTOCOL: &[u8] = b"wt-protocol";
258
309
 
310
+ /// Validated request routing fields and the selected HTTP upgrade token.
311
+ pub struct ConnectTarget<'a> {
312
+ pub protocol: &'a [u8],
313
+ pub authority: &'a str,
314
+ pub path: &'a str,
315
+ pub origin: Option<&'a str>,
316
+ }
317
+
318
+ pub fn validate_connect_headers(headers: &[Header]) -> Option<ConnectTarget<'_>> {
319
+ use quiche::h3::NameValue;
320
+
321
+ let (mut method, mut protocol, mut scheme, mut authority, mut path, mut origin) =
322
+ (None, None, None, None, None, None);
323
+ let mut regular = false;
324
+ for header in headers {
325
+ let (name, value) = (header.name(), header.value());
326
+ if value.iter().any(|&b| b == 0 || b == b'\r' || b == b'\n') {
327
+ return None;
328
+ }
329
+ if name.first() == Some(&b':') {
330
+ if regular {
331
+ return None;
332
+ }
333
+ let field = match name {
334
+ b":method" => &mut method,
335
+ b":protocol" => &mut protocol,
336
+ b":scheme" => &mut scheme,
337
+ b":authority" => &mut authority,
338
+ b":path" => &mut path,
339
+ _ => return None,
340
+ };
341
+ if field.replace(value).is_some() {
342
+ return None;
343
+ }
344
+ } else {
345
+ regular = true;
346
+ if name.is_empty()
347
+ || !name.iter().all(|b| {
348
+ b.is_ascii_lowercase() || b.is_ascii_digit() || b"!#$%&'*+-.^_`|~".contains(b)
349
+ })
350
+ || matches!(
351
+ name,
352
+ b"connection"
353
+ | b"proxy-connection"
354
+ | b"keep-alive"
355
+ | b"transfer-encoding"
356
+ | b"upgrade"
357
+ )
358
+ || (name == b"te" && !value.eq_ignore_ascii_case(b"trailers"))
359
+ {
360
+ return None;
361
+ }
362
+ if name == b"origin" && origin.replace(std::str::from_utf8(value).ok()?).is_some() {
363
+ return None;
364
+ }
365
+ }
366
+ }
367
+ let authority = std::str::from_utf8(authority?).ok()?;
368
+ let path = std::str::from_utf8(path?).ok()?;
369
+ if method? != b"CONNECT"
370
+ || scheme? != b"https"
371
+ || authority.is_empty()
372
+ || authority
373
+ .bytes()
374
+ .any(|b| !b.is_ascii_graphic() || b"@/?#".contains(&b))
375
+ || !path.starts_with('/')
376
+ || path.bytes().any(|b| !b.is_ascii_graphic() || b == b'#')
377
+ {
378
+ return None;
379
+ }
380
+ Some(ConnectTarget {
381
+ protocol: protocol?,
382
+ authority,
383
+ path,
384
+ origin,
385
+ })
386
+ }
387
+
259
388
  /// Build the Extended CONNECT request header list for a WebTransport session.
260
389
  pub fn connect_headers(
261
390
  authority: &str,
@@ -263,10 +392,21 @@ pub fn connect_headers(
263
392
  origin: Option<&str>,
264
393
  extra: &[(String, String)],
265
394
  protocols: &[String],
395
+ ) -> Vec<Header> {
396
+ connect_headers_for(LEGACY_WT_TOKEN, authority, path, origin, extra, protocols)
397
+ }
398
+
399
+ pub fn connect_headers_for(
400
+ token: &[u8],
401
+ authority: &str,
402
+ path: &str,
403
+ origin: Option<&str>,
404
+ extra: &[(String, String)],
405
+ protocols: &[String],
266
406
  ) -> Vec<Header> {
267
407
  let mut h = vec![
268
408
  Header::new(b":method", b"CONNECT"),
269
- Header::new(b":protocol", b"webtransport"),
409
+ Header::new(b":protocol", token),
270
410
  Header::new(b":scheme", b"https"),
271
411
  Header::new(b":authority", authority.as_bytes()),
272
412
  Header::new(b":path", path.as_bytes()),
@@ -313,37 +453,29 @@ pub fn serialize_sf_string_list(items: &[String]) -> String {
313
453
  /// Parse a single RFC 9651 Structured-Field String item (a double-quoted,
314
454
  /// backslash-escaped token). Returns `None` if it is not a well-formed sf-string.
315
455
  pub fn parse_sf_string_item(value: &str) -> Option<String> {
316
- let bytes = value.as_bytes();
317
- if bytes.len() < 2 || bytes[0] != b'"' {
318
- return None;
319
- }
320
- let mut out = String::new();
321
- let mut i = 1;
322
- while i < bytes.len() {
323
- match bytes[i] {
324
- b'\\' => {
325
- i += 1;
326
- match bytes.get(i) {
327
- Some(&e) if e == b'"' || e == b'\\' => out.push(e as char),
328
- _ => return None,
329
- }
330
- }
331
- b'"' => return (i == bytes.len() - 1).then_some(out),
332
- b @ 0x20..=0x7e => out.push(b as char),
333
- _ => return None,
334
- }
335
- i += 1;
456
+ let item: sfv::Item = sfv::Parser::new(value).parse().ok()?;
457
+ match item.bare_item {
458
+ sfv::BareItem::String(value) => Some(value.to_string()),
459
+ _ => None,
336
460
  }
337
- None
338
461
  }
339
462
 
340
- /// Parse an RFC 9651 Structured-Field List of Strings into tokens, tolerating
341
- /// surrounding whitespace and skipping malformed items.
463
+ /// Parse an RFC 9651 Structured-Field List of Strings into tokens, ignoring item parameters.
464
+ /// A malformed field is ignored in its entirety.
342
465
  pub fn parse_sf_string_list(value: &str) -> Vec<String> {
343
- value
344
- .split(',')
345
- .filter_map(|part| parse_sf_string_item(part.trim()))
346
- .collect()
466
+ let Ok(list) = sfv::Parser::new(value).parse::<sfv::List>() else {
467
+ return Vec::new();
468
+ };
469
+ list.into_iter()
470
+ .map(|entry| match entry {
471
+ sfv::ListEntry::Item(item) => match item.bare_item {
472
+ sfv::BareItem::String(value) => Some(value.to_string()),
473
+ _ => None,
474
+ },
475
+ _ => None,
476
+ })
477
+ .collect::<Option<Vec<_>>>()
478
+ .unwrap_or_default()
347
479
  }
348
480
 
349
481
  /// Find the first header value for a (lowercase) name.
@@ -353,7 +485,11 @@ pub fn header_value<'a>(headers: &'a [Header], name: &[u8]) -> Option<&'a [u8]>
353
485
 
354
486
  /// Parse the `wt-protocol` response header into the selected subprotocol token.
355
487
  pub fn wt_protocol_of(headers: &[Header]) -> Option<String> {
356
- let v = header_value(headers, WT_PROTOCOL)?;
488
+ let mut values = headers.iter().filter(|h| h.name() == WT_PROTOCOL);
489
+ let v = values.next()?.value();
490
+ if values.next().is_some() {
491
+ return None;
492
+ }
357
493
  parse_sf_string_item(std::str::from_utf8(v).ok()?.trim())
358
494
  }
359
495
 
@@ -398,18 +534,86 @@ pub fn decode_header_block(block: &[u8]) -> Result<Vec<Header>, String> {
398
534
 
399
535
  /// Extract the numeric `:status` from a decoded response header list.
400
536
  pub fn status_of(headers: &[Header]) -> Option<u16> {
401
- for h in headers {
402
- if h.name() == b":status" {
403
- return std::str::from_utf8(h.value()).ok()?.trim().parse().ok();
404
- }
537
+ let (first, rest) = headers.split_first()?;
538
+ let status = first.value();
539
+ if first.name() != b":status"
540
+ || status.len() != 3
541
+ || !status.iter().all(u8::is_ascii_digit)
542
+ || rest.iter().any(|field| field.name().starts_with(b":"))
543
+ {
544
+ return None;
405
545
  }
406
- None
546
+ let status = std::str::from_utf8(status).ok()?.parse().ok()?;
547
+ ((100..600).contains(&status) && status != 101).then_some(status)
407
548
  }
408
549
 
409
550
  #[cfg(test)]
410
551
  mod tests {
411
552
  use super::*;
412
553
 
554
+ #[test]
555
+ fn validates_extended_connect_routing_fields() {
556
+ let mut request =
557
+ connect_headers_for(WT_H3_TOKEN, "example.test", "/x?q=1", None, &[], &[]);
558
+ assert_eq!(
559
+ validate_connect_headers(&request).unwrap().protocol,
560
+ WT_H3_TOKEN
561
+ );
562
+ request.push(Header::new(b":path", b"/other"));
563
+ assert!(validate_connect_headers(&request).is_none());
564
+ request.pop();
565
+ request.remove(2);
566
+ assert!(validate_connect_headers(&request).is_none());
567
+ }
568
+
569
+ #[test]
570
+ fn exporter_context_includes_session_id_and_both_field_lengths() {
571
+ assert_eq!(
572
+ exporter_context(4, b"ab", b"c").unwrap(),
573
+ [0, 0, 0, 0, 0, 0, 0, 4, 2, b'a', b'b', 1, b'c']
574
+ );
575
+ assert!(exporter_context(0, &[0; 256], b"").is_none());
576
+ assert!(exporter_context(0, b"", &[0; 256]).is_none());
577
+ }
578
+
579
+ #[test]
580
+ fn settings_reject_truncation_duplicates_and_invalid_boolean_values() {
581
+ for pairs in [
582
+ vec![(SETTINGS_ENABLE_CONNECT_PROTOCOL, 2)],
583
+ vec![(SETTINGS_H3_DATAGRAM, 1), (SETTINGS_H3_DATAGRAM, 1)],
584
+ vec![(SETTINGS_WT_INITIAL_MAX_STREAMS_UNI, (1 << 60) + 1)],
585
+ vec![(0x2, 0)],
586
+ ] {
587
+ let mut payload = Vec::new();
588
+ for (id, value) in pairs {
589
+ put_varint(id, &mut payload);
590
+ put_varint(value, &mut payload);
591
+ }
592
+ assert!(parse_settings(&payload).is_err());
593
+ }
594
+ assert!(parse_settings(&[0x40]).is_err());
595
+ assert!(parse_settings(&[0x1]).is_err());
596
+ }
597
+
598
+ #[test]
599
+ fn structured_fields_preserve_commas_ignore_parameters_and_reject_whole_invalid_lists() {
600
+ assert_eq!(
601
+ parse_sf_string_list(r#""a,b";q=1, "c";ignored="x,y""#),
602
+ vec!["a,b", "c"]
603
+ );
604
+ assert_eq!(
605
+ parse_sf_string_item(r#""a,b";ignored=?1"#).as_deref(),
606
+ Some("a,b")
607
+ );
608
+ for value in [
609
+ r#""valid", invalid"#,
610
+ r#""valid", "unterminated"#,
611
+ r#""valid", ("inner")"#,
612
+ ] {
613
+ assert!(parse_sf_string_list(value).is_empty());
614
+ }
615
+ }
616
+
413
617
  #[test]
414
618
  fn error_code_mapping_roundtrips() {
415
619
  assert_eq!(webtransport_code_to_http_code(0), WT_APP_ERROR_FIRST);
@@ -476,9 +680,9 @@ mod tests {
476
680
 
477
681
  #[test]
478
682
  fn settings_advertise_and_parse_wt_flow_control() {
479
- let s = parse_settings(&settings_payload());
683
+ let s = parse_settings(&settings_payload()).unwrap();
480
684
  assert!(s.webtransport_ok());
481
- assert_eq!(s.wt_max_sessions, 256);
685
+ assert_eq!(s.wt_max_sessions, 1);
482
686
  assert_eq!(s.wt_initial_max_data, WT_INITIAL_MAX_DATA);
483
687
  assert_eq!(s.wt_initial_max_streams_bidi, WT_INITIAL_MAX_STREAMS);
484
688
  assert_eq!(s.wt_initial_max_streams_uni, WT_INITIAL_MAX_STREAMS);