h3x 0.6.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
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
use dhttp_identity::identity::{self as authority, SignError, VerifyError};
use futures::future::BoxFuture;
use rustls::pki_types::{CertificateDer, SubjectPublicKeyInfoDer};

use super::serde_types::{SerdeCertificateDer, SerdeSubjectPublicKeyInfoDer};
use crate::quic;

/// Remote trait for [`authority::LocalAuthority`], exposing authority methods over remoc RTC.
#[remoc::rtc::remote]
pub trait LocalAuthority: Send + Sync {
    async fn name(&self) -> Result<String, quic::ConnectionError>;
    async fn cert_chain(&self) -> Result<Vec<SerdeCertificateDer>, quic::ConnectionError>;
    async fn sign(&self, data: Vec<u8>) -> Result<Vec<u8>, quic::ConnectionError>;
    async fn public_key(&self) -> Result<SerdeSubjectPublicKeyInfoDer, quic::ConnectionError>;
    async fn verify(
        &self,
        data: Vec<u8>,
        signature: Vec<u8>,
    ) -> Result<bool, quic::ConnectionError>;
}

/// Remote trait for [`authority::RemoteAuthority`], exposing authority methods over remoc RTC.
#[remoc::rtc::remote]
pub trait RemoteAuthority: Send + Sync {
    async fn name(&self) -> Result<String, quic::ConnectionError>;
    async fn cert_chain(&self) -> Result<Vec<SerdeCertificateDer>, quic::ConnectionError>;
    async fn public_key(&self) -> Result<SerdeSubjectPublicKeyInfoDer, quic::ConnectionError>;
    async fn verify(
        &self,
        data: Vec<u8>,
        signature: Vec<u8>,
    ) -> Result<bool, quic::ConnectionError>;
}

pub struct CachedLocalAuthority {
    client: LocalAuthorityClient,
    name: String,
    cert_chain: Vec<CertificateDer<'static>>,
}

impl std::fmt::Debug for CachedLocalAuthority {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("CachedRemoteLocalAuthority")
            .field("name", &self.name)
            .finish_non_exhaustive()
    }
}

impl CachedLocalAuthority {
    /// Create a new cached wrapper by eagerly fetching synchronous fields from
    /// the remote authority.
    pub async fn from_client(client: LocalAuthorityClient) -> Result<Self, quic::ConnectionError> {
        let name = client.name().await?;
        let cert_chain: Vec<CertificateDer<'static>> = client
            .cert_chain()
            .await?
            .into_iter()
            .map(Into::into)
            .collect();
        Ok(Self {
            client,
            name,
            cert_chain,
        })
    }
}

impl authority::LocalAuthority for CachedLocalAuthority {
    fn name(&self) -> &str {
        &self.name
    }

    fn cert_chain(&self) -> &[CertificateDer<'static>] {
        &self.cert_chain
    }

    fn sign(&self, data: &[u8]) -> BoxFuture<'_, Result<Vec<u8>, SignError>> {
        let owned_data = data.to_vec();
        let client = self.client.clone();
        Box::pin(async move {
            client
                .sign(owned_data)
                .await
                // lossy: rustls API requires String for General error variant
                .map_err(|e| SignError::Crypto {
                    source: rustls::Error::General(e.to_string()),
                })
        })
    }

    fn public_key(&self) -> SubjectPublicKeyInfoDer<'_> {
        authority::extract_public_key(authority::LocalAuthority::cert_chain(self))
    }

    fn verify(&self, data: &[u8], signature: &[u8]) -> BoxFuture<'_, Result<bool, VerifyError>> {
        let result = authority::verify_signature(
            authority::LocalAuthority::public_key(self),
            data,
            signature,
        );
        Box::pin(std::future::ready(result))
    }
}

pub struct CachedRemoteAuthority {
    #[allow(dead_code)]
    client: RemoteAuthorityClient,
    name: String,
    cert_chain: Vec<CertificateDer<'static>>,
}

impl std::fmt::Debug for CachedRemoteAuthority {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("CachedRemoteRemoteAuthority")
            .field("name", &self.name)
            .finish_non_exhaustive()
    }
}

impl CachedRemoteAuthority {
    /// Create a new cached wrapper by eagerly fetching synchronous fields from
    /// the remote authority.
    pub async fn from_client(client: RemoteAuthorityClient) -> Result<Self, quic::ConnectionError> {
        let name = client.name().await?;
        let cert_chain: Vec<CertificateDer<'static>> = client
            .cert_chain()
            .await?
            .into_iter()
            .map(Into::into)
            .collect();
        Ok(Self {
            client,
            name,
            cert_chain,
        })
    }
}

impl authority::RemoteAuthority for CachedRemoteAuthority {
    fn name(&self) -> &str {
        &self.name
    }

    fn cert_chain(&self) -> &[CertificateDer<'static>] {
        &self.cert_chain
    }

    fn public_key(&self) -> SubjectPublicKeyInfoDer<'_> {
        authority::extract_public_key(authority::RemoteAuthority::cert_chain(self))
    }

    fn verify(&self, data: &[u8], signature: &[u8]) -> BoxFuture<'_, Result<bool, VerifyError>> {
        let result = authority::verify_signature(
            authority::RemoteAuthority::public_key(self),
            data,
            signature,
        );
        Box::pin(std::future::ready(result))
    }
}

impl<A> LocalAuthority for A
where
    A: authority::LocalAuthority + Send + Sync,
{
    async fn name(&self) -> Result<String, quic::ConnectionError> {
        Ok(authority::LocalAuthority::name(self).to_owned())
    }

    async fn cert_chain(&self) -> Result<Vec<SerdeCertificateDer>, quic::ConnectionError> {
        Ok(self
            .cert_chain()
            .iter()
            .cloned()
            .map(SerdeCertificateDer::from)
            .collect())
    }

    async fn sign(&self, data: Vec<u8>) -> Result<Vec<u8>, quic::ConnectionError> {
        authority::LocalAuthority::sign(self, &data)
            .await
            // lossy: TransportError.reason is a protocol string field
            .map_err(|e| quic::ConnectionError::Transport {
                source: quic::TransportError {
                    kind: crate::varint::VarInt::from_u32(0x01),
                    frame_type: crate::varint::VarInt::from_u32(0x00),
                    reason: format!("sign error: {e}").into(),
                },
            })
    }

    async fn public_key(&self) -> Result<SerdeSubjectPublicKeyInfoDer, quic::ConnectionError> {
        Ok(SerdeSubjectPublicKeyInfoDer::from(
            authority::LocalAuthority::public_key(self),
        ))
    }

    async fn verify(
        &self,
        data: Vec<u8>,
        signature: Vec<u8>,
    ) -> Result<bool, quic::ConnectionError> {
        authority::LocalAuthority::verify(self, &data, &signature)
            .await
            // lossy: TransportError.reason is a protocol string field
            .map_err(|e| quic::ConnectionError::Transport {
                source: quic::TransportError {
                    kind: crate::varint::VarInt::from_u32(0x01),
                    frame_type: crate::varint::VarInt::from_u32(0x00),
                    reason: format!("verify error: {e}").into(),
                },
            })
    }
}

impl<A> RemoteAuthority for A
where
    A: authority::RemoteAuthority + Send + Sync,
{
    async fn name(&self) -> Result<String, quic::ConnectionError> {
        Ok(authority::RemoteAuthority::name(self).to_owned())
    }

    async fn cert_chain(&self) -> Result<Vec<SerdeCertificateDer>, quic::ConnectionError> {
        Ok(self
            .cert_chain()
            .iter()
            .cloned()
            .map(SerdeCertificateDer::from)
            .collect())
    }

    async fn public_key(&self) -> Result<SerdeSubjectPublicKeyInfoDer, quic::ConnectionError> {
        Ok(SerdeSubjectPublicKeyInfoDer::from(
            authority::RemoteAuthority::public_key(self),
        ))
    }

    async fn verify(
        &self,
        data: Vec<u8>,
        signature: Vec<u8>,
    ) -> Result<bool, quic::ConnectionError> {
        authority::RemoteAuthority::verify(self, &data, &signature)
            .await
            // lossy: TransportError.reason is a protocol string field
            .map_err(|e| quic::ConnectionError::Transport {
                source: quic::TransportError {
                    kind: crate::varint::VarInt::from_u32(0x01),
                    frame_type: crate::varint::VarInt::from_u32(0x00),
                    reason: format!("verify error: {e}").into(),
                },
            })
    }
}

#[cfg(test)]
mod tests {
    use std::sync::Arc;

    use remoc::prelude::ServerShared;
    use tokio_util::task::AbortOnDropHandle;
    use tracing::Instrument;

    use super::*;
    use crate::dquic::cert::handy::ToCertificate;

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

    #[derive(Clone, Debug)]
    struct TestLocalAuthority {
        name: &'static str,
        cert_chain: Vec<CertificateDer<'static>>,
        fail_sign: bool,
    }

    impl TestLocalAuthority {
        fn new(name: &'static str) -> Self {
            Self {
                name,
                cert_chain: SERVER_CERT.to_certificate(),
                fail_sign: false,
            }
        }

        fn failing_signer() -> Self {
            Self {
                fail_sign: true,
                ..Self::new("failing-local")
            }
        }

        fn invalid_cert_chain(name: &'static str) -> Self {
            Self {
                name,
                cert_chain: vec![CertificateDer::from(vec![0x01, 0x02, 0x03])],
                fail_sign: false,
            }
        }
    }

    impl authority::LocalAuthority for TestLocalAuthority {
        fn name(&self) -> &str {
            self.name
        }

        fn cert_chain(&self) -> &[CertificateDer<'static>] {
            &self.cert_chain
        }

        fn sign(&self, data: &[u8]) -> BoxFuture<'_, Result<Vec<u8>, SignError>> {
            let fail_sign = self.fail_sign;
            let data = data.to_vec();
            Box::pin(async move {
                if fail_sign {
                    return Err(SignError::UnsupportedKey);
                }
                Ok(expected_signature(&data))
            })
        }
    }

    #[derive(Clone, Debug)]
    struct TestRemoteAuthority {
        name: &'static str,
        cert_chain: Vec<CertificateDer<'static>>,
    }

    impl TestRemoteAuthority {
        fn new(name: &'static str) -> Self {
            Self {
                name,
                cert_chain: SERVER_CERT.to_certificate(),
            }
        }

        fn invalid_cert_chain(name: &'static str) -> Self {
            Self {
                name,
                cert_chain: vec![CertificateDer::from(vec![0x04, 0x05, 0x06])],
            }
        }
    }

    impl authority::RemoteAuthority for TestRemoteAuthority {
        fn name(&self) -> &str {
            self.name
        }

        fn cert_chain(&self) -> &[CertificateDer<'static>] {
            &self.cert_chain
        }
    }

    fn expected_signature(data: &[u8]) -> Vec<u8> {
        let mut signature = b"canonical:".to_vec();
        signature.extend_from_slice(data);
        signature
    }

    fn assert_transport_reason(error: quic::ConnectionError, fragment: &str) {
        let quic::ConnectionError::Transport { source } = error else {
            panic!("expected transport error");
        };
        assert!(
            source.reason.contains(fragment),
            "transport reason {:?} should contain {fragment:?}",
            source.reason,
        );
    }

    fn spawn_local_authority_server(
        authority: TestLocalAuthority,
    ) -> (AbortOnDropHandle<()>, LocalAuthorityClient) {
        let (server, client) = LocalAuthorityServerShared::new(Arc::new(authority), 1);
        let task = AbortOnDropHandle::new(tokio::spawn(
            async move {
                let _ = server.serve(true).await;
            }
            .in_current_span(),
        ));
        (task, client)
    }

    fn spawn_remote_authority_server(
        authority: TestRemoteAuthority,
    ) -> (AbortOnDropHandle<()>, RemoteAuthorityClient) {
        let (server, client) = RemoteAuthorityServerShared::new(Arc::new(authority), 1);
        let task = AbortOnDropHandle::new(tokio::spawn(
            async move {
                let _ = server.serve(true).await;
            }
            .in_current_span(),
        ));
        (task, client)
    }

    #[tokio::test]
    async fn blanket_local_authority_delegates_all_methods() {
        let authority = TestLocalAuthority::new("local.example");

        assert_eq!(
            super::LocalAuthority::name(&authority).await.expect("name"),
            "local.example",
        );
        let certs = super::LocalAuthority::cert_chain(&authority)
            .await
            .expect("cert chain");
        let cert = CertificateDer::from(certs.into_iter().next().expect("certificate"));
        assert_eq!(cert.as_ref(), authority.cert_chain[0].as_ref());

        let signature = super::LocalAuthority::sign(&authority, b"payload".to_vec())
            .await
            .expect("sign");
        assert_eq!(signature, expected_signature(b"payload"));

        let public_key = SubjectPublicKeyInfoDer::from(
            super::LocalAuthority::public_key(&authority)
                .await
                .expect("public key"),
        );
        assert_eq!(
            public_key.as_ref(),
            authority::LocalAuthority::public_key(&authority).as_ref(),
        );

        let verified = super::LocalAuthority::verify(
            &authority,
            b"payload".to_vec(),
            b"not a real signature".to_vec(),
        )
        .await
        .expect("verify");
        assert!(!verified);
    }

    #[tokio::test]
    async fn blanket_remote_authority_delegates_all_methods() {
        let authority = TestRemoteAuthority::new("remote.example");

        assert_eq!(
            super::RemoteAuthority::name(&authority)
                .await
                .expect("name"),
            "remote.example",
        );
        let certs = super::RemoteAuthority::cert_chain(&authority)
            .await
            .expect("cert chain");
        let cert = CertificateDer::from(certs.into_iter().next().expect("certificate"));
        assert_eq!(cert.as_ref(), authority.cert_chain[0].as_ref());

        let public_key = SubjectPublicKeyInfoDer::from(
            super::RemoteAuthority::public_key(&authority)
                .await
                .expect("public key"),
        );
        assert_eq!(
            public_key.as_ref(),
            authority::RemoteAuthority::public_key(&authority).as_ref(),
        );

        let verified = super::RemoteAuthority::verify(
            &authority,
            b"payload".to_vec(),
            b"not a real signature".to_vec(),
        )
        .await
        .expect("verify");
        assert!(!verified);
    }

    #[tokio::test]
    async fn blanket_authority_errors_become_transport_errors() {
        let local = TestLocalAuthority::failing_signer();
        let local_with_invalid_key = TestLocalAuthority::invalid_cert_chain("invalid-local");
        let remote_with_invalid_key = TestRemoteAuthority::invalid_cert_chain("invalid-remote");

        let error = super::LocalAuthority::sign(&local, b"payload".to_vec())
            .await
            .expect_err("sign error should be mapped");
        assert_transport_reason(error, "sign error");

        let error = super::LocalAuthority::verify(
            &local_with_invalid_key,
            b"payload".to_vec(),
            b"signature".to_vec(),
        )
        .await
        .expect_err("local verify error should be mapped");
        assert_transport_reason(error, "verify error");

        let error = super::RemoteAuthority::verify(
            &remote_with_invalid_key,
            b"payload".to_vec(),
            b"signature".to_vec(),
        )
        .await
        .expect_err("remote verify error should be mapped");
        assert_transport_reason(error, "verify error");
    }

    #[tokio::test]
    async fn cached_local_authority_fetches_remote_fields_and_delegates_sign() {
        let authority = TestLocalAuthority::new("cached-local.example");
        let (_task, client) = spawn_local_authority_server(authority.clone());

        let cached = CachedLocalAuthority::from_client(client)
            .await
            .expect("cached local authority");

        assert_eq!(authority::LocalAuthority::name(&cached), authority.name);
        assert_eq!(
            authority::LocalAuthority::cert_chain(&cached)[0].as_ref(),
            authority.cert_chain[0].as_ref(),
        );
        assert!(
            format!("{cached:?}").contains("CachedRemoteLocalAuthority"),
            "debug output should name cached local authority",
        );

        let signature = authority::LocalAuthority::sign(&cached, b"payload")
            .await
            .expect("cached sign");
        assert_eq!(signature, expected_signature(b"payload"));

        let public_key = authority::LocalAuthority::public_key(&cached);
        assert_eq!(
            public_key.as_ref(),
            authority::LocalAuthority::public_key(&authority).as_ref()
        );
        let verified =
            authority::LocalAuthority::verify(&cached, b"payload", b"not a real signature")
                .await
                .expect("cached verify");
        assert!(!verified);
    }

    #[tokio::test]
    async fn cached_remote_authority_fetches_remote_fields() {
        let authority = TestRemoteAuthority::new("cached-remote.example");
        let (_task, client) = spawn_remote_authority_server(authority.clone());

        let cached = CachedRemoteAuthority::from_client(client)
            .await
            .expect("cached remote authority");

        assert_eq!(authority::RemoteAuthority::name(&cached), authority.name);
        assert_eq!(
            authority::RemoteAuthority::cert_chain(&cached)[0].as_ref(),
            authority.cert_chain[0].as_ref(),
        );
        assert!(
            format!("{cached:?}").contains("CachedRemoteRemoteAuthority"),
            "debug output should name cached remote authority",
        );

        let public_key = authority::RemoteAuthority::public_key(&cached);
        assert_eq!(
            public_key.as_ref(),
            authority::RemoteAuthority::public_key(&authority).as_ref(),
        );
        let verified =
            authority::RemoteAuthority::verify(&cached, b"payload", b"not a real signature")
                .await
                .expect("cached verify");
        assert!(!verified);
    }
}