h3x 0.6.0-beta.1

Peer-to-peer DHTTP/3 transport over QUIC
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
//! Client-side QUIC configuration types.
//!
//! [`ClientQuicConfig`] is the primary client-side configuration struct.
//! All fields are inlined directly — the former `CommonQuicConfig` and
//! `ClientSpecificConfig` wrappers have been flattened into this single type.
//!
//! All types provide [`Default`] so that client endpoints can be constructed
//! without the caller having to hand-roll configuration values.

use std::{sync::Arc, time::Duration};

use rustls::client::{WebPkiServerVerifier, danger::ServerCertVerifier};

use crate::dquic::{
    log::{QLog, handy::NoopLogger},
    param::{ClientParameters, handy::client_parameters},
    stream::{ProductStreamsConcurrencyController, handy::ConsistentConcurrency},
    token::{TokenSink, handy::NoopTokenRegistry},
};

// ---------------------------------------------------------------------------
// Client-only
// ---------------------------------------------------------------------------

/// Strategy for verifying the server's TLS certificate.
///
/// Kept as a small enum rather than a trait object so that
/// [`ClientQuicConfig::verifier`] composes cheaply. The `WebPki` and `Custom`
/// variants wrap their verifier in an [`Arc`] for cheap cloning.
#[derive(Clone, Default)]
pub enum ServerCertVerifierChoice {
    /// Accept any certificate. Intended for local testing only.
    #[default]
    Dangerous,
    /// Verify against a compiled webpki verifier.
    WebPki(Arc<WebPkiServerVerifier>),
    /// Delegate to a caller-supplied verifier.
    Custom(Arc<dyn ServerCertVerifier>),
}

impl std::fmt::Debug for ServerCertVerifierChoice {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Dangerous => f.debug_tuple("Dangerous").finish(),
            Self::WebPki(_) => f.debug_tuple("WebPki").finish(),
            Self::Custom(_) => f.debug_tuple("Custom").finish(),
        }
    }
}

impl PartialEq for ServerCertVerifierChoice {
    fn eq(&self, other: &Self) -> bool {
        match (self, other) {
            (Self::Dangerous, Self::Dangerous) => true,
            (Self::WebPki(a), Self::WebPki(b)) => Arc::ptr_eq(a, b),
            (Self::Custom(a), Self::Custom(b)) => Arc::ptr_eq(a, b),
            _ => false,
        }
    }
}

// --- legacy ClientSpecificConfig fields (flattened into ClientQuicConfig) ---
//
// /// Client-only configuration values.
// #[derive(Clone)]
// pub struct ClientSpecificConfig {
//     /// Transport parameters advertised by the client.
//     pub parameters: ClientParameters,
//     /// ALPN protocol identifiers to offer. Empty means no ALPN.
//     pub alpns: Vec<Vec<u8>>,
//     /// Address validation token sink.
//     pub token_sink: Arc<dyn TokenSink>,
//     /// How the server's certificate should be verified.
//     pub verifier: ServerCertVerifierChoice,
// }
//
// impl Default for ClientSpecificConfig { ... }
// impl Debug for ClientSpecificConfig { ... }
// impl PartialEq for ClientSpecificConfig { ... }

// ---------------------------------------------------------------------------
// Client composite (common + own)
// ---------------------------------------------------------------------------

/// Client-side QUIC configuration — common + client-only fields flattened.
#[derive(Clone)]
pub struct ClientQuicConfig {
    // --- common fields (from CommonQuicConfig) ---
    /// How long the connection should keep sending probe packets after going
    /// idle. `Duration::ZERO` (the default) disables deferred idle timeouts.
    pub defer_idle_timeout: Duration,
    /// Factory producing per-connection streams concurrency controllers.
    pub stream_strategy_factory: Arc<dyn ProductStreamsConcurrencyController>,
    /// QUIC-events logger (qlog). Defaults to a no-op logger.
    pub qlogger: Arc<dyn QLog + Send + Sync>,
    /// Whether 0-RTT should be enabled if the crypto context permits it.
    pub enable_0rtt: bool,
    /// Enable SSL key logging via `SSLKEYLOGFILE` for debugging captures.
    pub enable_sslkeylog: bool,

    // --- client-specific fields (from ClientSpecificConfig) ---
    /// Transport parameters advertised by the client.
    pub parameters: ClientParameters,
    /// ALPN protocol identifiers to offer. Empty means no ALPN.
    pub alpns: Vec<Vec<u8>>,
    /// Address validation token sink.
    pub token_sink: Arc<dyn TokenSink>,
    /// How the server's certificate should be verified.
    pub verifier: ServerCertVerifierChoice,
}

impl Default for ClientQuicConfig {
    fn default() -> Self {
        Self {
            // CommonQuicConfig::default() values
            defer_idle_timeout: Duration::ZERO,
            stream_strategy_factory: Arc::new(ConsistentConcurrency::new),
            qlogger: Arc::new(NoopLogger),
            enable_0rtt: false,
            enable_sslkeylog: false,
            // ClientSpecificConfig::default() values
            parameters: client_parameters(),
            alpns: Vec::new(),
            token_sink: Arc::new(NoopTokenRegistry),
            verifier: ServerCertVerifierChoice::default(),
        }
    }
}

impl std::fmt::Debug for ClientQuicConfig {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ClientQuicConfig")
            .field("defer_idle_timeout", &self.defer_idle_timeout)
            .field("enable_0rtt", &self.enable_0rtt)
            .field("enable_sslkeylog", &self.enable_sslkeylog)
            .field("alpns", &self.alpns.len())
            .field("verifier", &self.verifier)
            .finish_non_exhaustive()
    }
}

impl PartialEq for ClientQuicConfig {
    fn eq(&self, other: &Self) -> bool {
        self.defer_idle_timeout == other.defer_idle_timeout
            && self.enable_0rtt == other.enable_0rtt
            && self.enable_sslkeylog == other.enable_sslkeylog
            && self.parameters == other.parameters
            && self.alpns == other.alpns
            && self.verifier == other.verifier
            && Arc::ptr_eq(
                &self.stream_strategy_factory,
                &other.stream_strategy_factory,
            )
            && Arc::ptr_eq(&self.qlogger, &other.qlogger)
            && Arc::ptr_eq(&self.token_sink, &other.token_sink)
    }
}

// ---------------------------------------------------------------------------
// Unit tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod client_tests {
    use std::{sync::Arc, time::Duration};

    use rustls::{
        RootCertStore,
        client::{WebPkiServerVerifier, danger::ServerCertVerifier},
    };

    use crate::{
        dquic::{client::*, common::*, prelude::handy::ToCertificate},
        util::tls::DangerousServerCertVerifier,
    };

    const CA_CERT: &[u8] = include_bytes!("../../tests/keychain/localhost/ca.cert");

    fn root_store_with_ca() -> RootCertStore {
        let mut store = RootCertStore::empty();
        store.add_parsable_certificates(CA_CERT.to_certificate());
        store
    }

    // -- CommonQuicConfig ---------------------------------------------------

    #[test]
    fn test_common_quic_config_default() {
        let cfg = CommonQuicConfig::default();
        assert_eq!(cfg.defer_idle_timeout, Duration::ZERO);
        assert!(!cfg.enable_0rtt);
        assert!(!cfg.enable_sslkeylog);
    }

    #[test]
    fn test_common_quic_config_partial_eq_different_timeout() {
        let a = CommonQuicConfig::default();
        let mut b = a.clone();
        b.defer_idle_timeout = Duration::from_secs(30);
        assert_ne!(a, b);
    }

    #[test]
    fn test_common_quic_config_clone() {
        let a = CommonQuicConfig::default();
        let b = a.clone();
        // Clone shares the same Arcs
        assert!(Arc::ptr_eq(
            &a.stream_strategy_factory,
            &b.stream_strategy_factory
        ));
        assert!(Arc::ptr_eq(&a.qlogger, &b.qlogger));
        // Scalar values are copied
        assert_eq!(a.defer_idle_timeout, b.defer_idle_timeout);
        assert_eq!(a.enable_0rtt, b.enable_0rtt);
        assert_eq!(a.enable_sslkeylog, b.enable_sslkeylog);
    }

    // -- ServerCertVerifierChoice -------------------------------------------

    #[test]
    fn test_verifier_choice_dangerous_ne_webpki() {
        let store = root_store_with_ca();
        let webpki = WebPkiServerVerifier::builder(Arc::new(store))
            .build()
            .unwrap();
        assert_ne!(
            ServerCertVerifierChoice::Dangerous,
            ServerCertVerifierChoice::WebPki(webpki)
        );
    }

    #[test]
    fn test_verifier_choice_webpki_same_arc_eq() {
        let store = root_store_with_ca();
        let webpki = WebPkiServerVerifier::builder(Arc::new(store))
            .build()
            .unwrap();
        // webpki is already Arc<WebPkiServerVerifier>
        // Two clones of the same Arc should be equal (ptr_eq)
        let a = ServerCertVerifierChoice::WebPki(webpki.clone());
        let b = ServerCertVerifierChoice::WebPki(webpki.clone());
        assert_eq!(a, b);
    }

    #[test]
    fn test_verifier_choice_webpki_different_arc_ne() {
        let store1 = root_store_with_ca();
        let store2 = root_store_with_ca();
        let webpki1 = WebPkiServerVerifier::builder(Arc::new(store1))
            .build()
            .unwrap();
        let webpki2 = WebPkiServerVerifier::builder(Arc::new(store2))
            .build()
            .unwrap();
        assert_ne!(
            ServerCertVerifierChoice::WebPki(webpki1),
            ServerCertVerifierChoice::WebPki(webpki2)
        );
    }

    #[test]
    fn test_verifier_choice_custom_same_arc_eq() {
        let verifier: Arc<dyn ServerCertVerifier> = Arc::new(DangerousServerCertVerifier);
        let a = ServerCertVerifierChoice::Custom(verifier.clone());
        let b = ServerCertVerifierChoice::Custom(verifier.clone());
        assert_eq!(a, b);
    }

    #[test]
    fn test_verifier_choice_custom_different_arc_ne() {
        let a: Arc<dyn ServerCertVerifier> = Arc::new(DangerousServerCertVerifier);
        let b: Arc<dyn ServerCertVerifier> = Arc::new(DangerousServerCertVerifier);
        assert_ne!(
            ServerCertVerifierChoice::Custom(a),
            ServerCertVerifierChoice::Custom(b)
        );
    }

    #[test]
    fn test_verifier_choice_cross_variant_not_equal() {
        let verifier: Arc<dyn ServerCertVerifier> = Arc::new(DangerousServerCertVerifier);
        assert_ne!(
            ServerCertVerifierChoice::Dangerous,
            ServerCertVerifierChoice::Custom(verifier.clone())
        );
        assert_ne!(
            ServerCertVerifierChoice::WebPki(
                WebPkiServerVerifier::builder(Arc::new(root_store_with_ca()))
                    .build()
                    .unwrap()
            ),
            ServerCertVerifierChoice::Custom(verifier)
        );
    }

    #[test]
    fn test_verifier_choice_debug_variants() {
        let store = root_store_with_ca();
        let webpki = WebPkiServerVerifier::builder(Arc::new(store))
            .build()
            .unwrap();

        let dangerous = ServerCertVerifierChoice::Dangerous;
        let custom: Arc<dyn ServerCertVerifier> = Arc::new(DangerousServerCertVerifier);

        assert_eq!(format!("{:?}", dangerous), "Dangerous");
        assert_eq!(
            format!("{:?}", ServerCertVerifierChoice::WebPki(webpki)),
            "WebPki"
        );
        assert_eq!(
            format!("{:?}", ServerCertVerifierChoice::Custom(custom)),
            "Custom"
        );
    }

    #[test]
    fn test_verifier_choice_default_is_dangerous() {
        assert_eq!(
            ServerCertVerifierChoice::default(),
            ServerCertVerifierChoice::Dangerous
        );
    }

    // -- ClientQuicConfig ---------------------------------------------------

    #[test]
    fn test_client_quic_config_default() {
        let cfg = ClientQuicConfig::default();
        // Common fields
        assert_eq!(cfg.defer_idle_timeout, Duration::ZERO);
        assert!(!cfg.enable_0rtt);
        assert!(!cfg.enable_sslkeylog);
        // Client-specific fields
        assert!(
            matches!(&cfg.verifier, ServerCertVerifierChoice::Dangerous),
            "default verifier should be Dangerous"
        );
        assert!(cfg.alpns.is_empty(), "default alpns should be empty");
    }

    #[test]
    fn test_client_quic_config_partial_eq_different_timeout() {
        let a = ClientQuicConfig::default();
        let mut b = a.clone();
        b.defer_idle_timeout = Duration::from_secs(99);
        assert_ne!(a, b);
    }

    #[test]
    fn test_client_quic_config_partial_eq_different_verifier() {
        let a = ClientQuicConfig::default();
        let store = root_store_with_ca();
        let webpki = WebPkiServerVerifier::builder(Arc::new(store))
            .build()
            .unwrap();

        let mut custom = a.clone();
        custom.verifier = ServerCertVerifierChoice::Custom(Arc::new(DangerousServerCertVerifier));
        assert_ne!(a, custom);

        let mut webpki_choice = a.clone();
        webpki_choice.verifier = ServerCertVerifierChoice::WebPki(webpki);
        assert_ne!(a, webpki_choice);
    }

    #[test]
    fn test_client_quic_config_partial_eq_different_components() {
        let a = ClientQuicConfig::default();

        let mut strategy = a.clone();
        strategy.stream_strategy_factory = Arc::new(ConsistentConcurrency::new);
        assert_ne!(a, strategy);

        let mut qlogger = a.clone();
        qlogger.qlogger = Arc::new(NoopLogger);
        assert_ne!(a, qlogger);

        let mut token_sink = a.clone();
        token_sink.token_sink = Arc::new(NoopTokenRegistry);
        assert_ne!(a, token_sink);
    }

    #[test]
    fn test_client_quic_config_debug() {
        let cfg = ClientQuicConfig {
            alpns: vec![b"h3".to_vec()],
            ..ClientQuicConfig::default()
        };

        let rendered = format!("{cfg:?}");
        assert!(rendered.contains("ClientQuicConfig"));
        assert!(rendered.contains("defer_idle_timeout: 0ns"));
        assert!(rendered.contains("enable_0rtt: false"));
        assert!(rendered.contains("enable_sslkeylog: false"));
        assert!(rendered.contains("alpns: 1"));
        assert!(rendered.contains("verifier: Dangerous"));
        assert!(rendered.contains(".."));
        assert!(!rendered.contains("stream_strategy_factory"));
    }

    #[test]
    fn test_client_quic_config_clone() {
        let a = ClientQuicConfig::default();
        let b = a.clone();
        // Trait-object Arcs are shared by pointer after clone
        assert!(Arc::ptr_eq(
            &a.stream_strategy_factory,
            &b.stream_strategy_factory
        ));
        assert!(Arc::ptr_eq(&a.qlogger, &b.qlogger));
        assert!(Arc::ptr_eq(&a.token_sink, &b.token_sink));
        // Scalar / owned values are equal by value
        assert_eq!(a.defer_idle_timeout, b.defer_idle_timeout);
        assert_eq!(a.enable_0rtt, b.enable_0rtt);
        assert_eq!(a.enable_sslkeylog, b.enable_sslkeylog);
        assert_eq!(a.parameters, b.parameters);
        assert_eq!(a.alpns, b.alpns);
        assert_eq!(a.verifier, b.verifier);
    }

    #[test]
    fn test_client_quic_config_mutate_does_not_affect_clone() {
        let a = ClientQuicConfig::default();
        let mut b = a.clone();

        // Mutate b — should not affect a since fields are copied/cloned
        b.defer_idle_timeout = Duration::from_secs(99);
        b.alpns.push(b"h3".to_vec());

        // Original is unchanged
        assert_eq!(a.defer_idle_timeout, Duration::ZERO);
        assert!(a.alpns.is_empty());
        // b has the new values
        assert_eq!(b.defer_idle_timeout, Duration::from_secs(99));
        assert!(!b.alpns.is_empty());
    }

    #[test]
    fn test_client_quic_config_mutate_arc_fields_does_not_affect_clone() {
        let a = ClientQuicConfig::default();
        let mut b = a.clone();

        // Replace trait-object Arcs in the clone.
        b.stream_strategy_factory = Arc::new(ConsistentConcurrency::new);
        b.qlogger = Arc::new(NoopLogger);
        b.token_sink = Arc::new(NoopTokenRegistry);

        // Other value fields stay unchanged and only trait-object identities diverge.
        assert_eq!(a.defer_idle_timeout, b.defer_idle_timeout);
        assert_eq!(a.enable_0rtt, b.enable_0rtt);
        assert_eq!(a.enable_sslkeylog, b.enable_sslkeylog);
        assert_eq!(a.parameters, b.parameters);
        assert_eq!(a.alpns, b.alpns);
        assert_eq!(a.verifier, b.verifier);
        assert!(!Arc::ptr_eq(
            &a.stream_strategy_factory,
            &b.stream_strategy_factory
        ));
        assert!(!Arc::ptr_eq(&a.qlogger, &b.qlogger));
        assert!(!Arc::ptr_eq(&a.token_sink, &b.token_sink));
    }
}