uselesskey-rustls 0.8.0

rustls-pki-types and rustls config adapters for uselesskey X.509/key fixtures.
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
//! Convenience builders for `rustls::ServerConfig` and `rustls::ClientConfig`.

use std::sync::Arc;

use rustls::crypto::CryptoProvider;

#[cfg(feature = "x509")]
use crate::RustlsCertExt;
#[cfg(feature = "x509")]
use crate::RustlsChainExt;
#[cfg(feature = "server-config")]
use crate::RustlsPrivateKeyExt;

// ---------------------------------------------------------------------------
// ServerConfig
// ---------------------------------------------------------------------------

/// Extension trait that builds a `rustls::ServerConfig` from uselesskey fixtures.
#[cfg(feature = "server-config")]
pub trait RustlsServerConfigExt {
    /// Build a `ServerConfig` using the process-default `CryptoProvider`.
    fn server_config_rustls(&self) -> rustls::ServerConfig;

    /// Build a `ServerConfig` with an explicit `CryptoProvider`.
    fn server_config_rustls_with_provider(
        &self,
        provider: Arc<CryptoProvider>,
    ) -> rustls::ServerConfig;
}

#[cfg(all(feature = "x509", feature = "server-config"))]
impl RustlsServerConfigExt for uselesskey_x509::X509Chain {
    fn server_config_rustls(&self) -> rustls::ServerConfig {
        let private_key = self.private_key_der_rustls();
        let cert_chain = self.chain_der_rustls();
        rustls::ServerConfig::builder()
            .with_no_client_auth()
            .with_single_cert(cert_chain, private_key)
            .expect("valid server config")
    }

    fn server_config_rustls_with_provider(
        &self,
        provider: Arc<CryptoProvider>,
    ) -> rustls::ServerConfig {
        let private_key = self.private_key_der_rustls();
        let cert_chain = self.chain_der_rustls();
        rustls::ServerConfig::builder_with_provider(provider)
            .with_safe_default_protocol_versions()
            .expect("valid protocol versions")
            .with_no_client_auth()
            .with_single_cert(cert_chain, private_key)
            .expect("valid server config")
    }
}

#[cfg(all(feature = "x509", feature = "server-config"))]
impl RustlsServerConfigExt for uselesskey_x509::X509Cert {
    fn server_config_rustls(&self) -> rustls::ServerConfig {
        let private_key = self.private_key_der_rustls();
        let cert_chain = vec![self.certificate_der_rustls()];
        rustls::ServerConfig::builder()
            .with_no_client_auth()
            .with_single_cert(cert_chain, private_key)
            .expect("valid server config")
    }

    fn server_config_rustls_with_provider(
        &self,
        provider: Arc<CryptoProvider>,
    ) -> rustls::ServerConfig {
        let private_key = self.private_key_der_rustls();
        let cert_chain = vec![self.certificate_der_rustls()];
        rustls::ServerConfig::builder_with_provider(provider)
            .with_safe_default_protocol_versions()
            .expect("valid protocol versions")
            .with_no_client_auth()
            .with_single_cert(cert_chain, private_key)
            .expect("valid server config")
    }
}

// ---------------------------------------------------------------------------
// ClientConfig
// ---------------------------------------------------------------------------

/// Extension trait that builds a `rustls::ClientConfig` from uselesskey fixtures.
#[cfg(feature = "client-config")]
pub trait RustlsClientConfigExt {
    /// Build a `ClientConfig` that trusts the root CA, with no client certificate.
    fn client_config_rustls(&self) -> rustls::ClientConfig;

    /// Build a `ClientConfig` with an explicit `CryptoProvider`.
    fn client_config_rustls_with_provider(
        &self,
        provider: Arc<CryptoProvider>,
    ) -> rustls::ClientConfig;
}

#[cfg(all(feature = "x509", feature = "client-config"))]
impl RustlsClientConfigExt for uselesskey_x509::X509Chain {
    fn client_config_rustls(&self) -> rustls::ClientConfig {
        let mut root_store = rustls::RootCertStore::empty();
        root_store
            .add(self.root_certificate_der_rustls())
            .expect("valid root cert");
        rustls::ClientConfig::builder()
            .with_root_certificates(root_store)
            .with_no_client_auth()
    }

    fn client_config_rustls_with_provider(
        &self,
        provider: Arc<CryptoProvider>,
    ) -> rustls::ClientConfig {
        let mut root_store = rustls::RootCertStore::empty();
        root_store
            .add(self.root_certificate_der_rustls())
            .expect("valid root cert");
        rustls::ClientConfig::builder_with_provider(provider)
            .with_safe_default_protocol_versions()
            .expect("valid protocol versions")
            .with_root_certificates(root_store)
            .with_no_client_auth()
    }
}

#[cfg(all(feature = "x509", feature = "client-config"))]
impl RustlsClientConfigExt for uselesskey_x509::X509Cert {
    fn client_config_rustls(&self) -> rustls::ClientConfig {
        let mut root_store = rustls::RootCertStore::empty();
        root_store
            .add(self.certificate_der_rustls())
            .expect("valid root cert");
        rustls::ClientConfig::builder()
            .with_root_certificates(root_store)
            .with_no_client_auth()
    }

    fn client_config_rustls_with_provider(
        &self,
        provider: Arc<CryptoProvider>,
    ) -> rustls::ClientConfig {
        let mut root_store = rustls::RootCertStore::empty();
        root_store
            .add(self.certificate_der_rustls())
            .expect("valid root cert");
        rustls::ClientConfig::builder_with_provider(provider)
            .with_safe_default_protocol_versions()
            .expect("valid protocol versions")
            .with_root_certificates(root_store)
            .with_no_client_auth()
    }
}

// ---------------------------------------------------------------------------
// mTLS
// ---------------------------------------------------------------------------

/// Extension trait for mutual TLS configurations.
#[cfg(all(feature = "server-config", feature = "client-config"))]
pub trait RustlsMtlsExt {
    /// Build a `ServerConfig` that requires client certificates verified against
    /// the chain's root CA.
    fn server_config_mtls_rustls(&self) -> rustls::ServerConfig;

    /// Build a `ServerConfig` for mTLS with an explicit `CryptoProvider`.
    fn server_config_mtls_rustls_with_provider(
        &self,
        provider: Arc<CryptoProvider>,
    ) -> rustls::ServerConfig;

    /// Build a `ClientConfig` that presents the leaf certificate as a client
    /// certificate and trusts the root CA.
    fn client_config_mtls_rustls(&self) -> rustls::ClientConfig;

    /// Build a `ClientConfig` for mTLS with an explicit `CryptoProvider`.
    fn client_config_mtls_rustls_with_provider(
        &self,
        provider: Arc<CryptoProvider>,
    ) -> rustls::ClientConfig;
}

#[cfg(all(feature = "x509", feature = "server-config", feature = "client-config"))]
impl RustlsMtlsExt for uselesskey_x509::X509Chain {
    fn server_config_mtls_rustls(&self) -> rustls::ServerConfig {
        let mut root_store = rustls::RootCertStore::empty();
        root_store
            .add(self.root_certificate_der_rustls())
            .expect("valid root cert");

        let client_verifier = rustls::server::WebPkiClientVerifier::builder(root_store.into())
            .build()
            .expect("valid client verifier");

        let private_key = self.private_key_der_rustls();
        let cert_chain = self.chain_der_rustls();

        rustls::ServerConfig::builder()
            .with_client_cert_verifier(client_verifier)
            .with_single_cert(cert_chain, private_key)
            .expect("valid mTLS server config")
    }

    fn server_config_mtls_rustls_with_provider(
        &self,
        provider: Arc<CryptoProvider>,
    ) -> rustls::ServerConfig {
        let mut root_store = rustls::RootCertStore::empty();
        root_store
            .add(self.root_certificate_der_rustls())
            .expect("valid root cert");

        let client_verifier = rustls::server::WebPkiClientVerifier::builder(root_store.into())
            .build()
            .expect("valid client verifier");

        let private_key = self.private_key_der_rustls();
        let cert_chain = self.chain_der_rustls();

        rustls::ServerConfig::builder_with_provider(provider)
            .with_safe_default_protocol_versions()
            .expect("valid protocol versions")
            .with_client_cert_verifier(client_verifier)
            .with_single_cert(cert_chain, private_key)
            .expect("valid mTLS server config")
    }

    fn client_config_mtls_rustls(&self) -> rustls::ClientConfig {
        let mut root_store = rustls::RootCertStore::empty();
        root_store
            .add(self.root_certificate_der_rustls())
            .expect("valid root cert");

        let private_key = self.private_key_der_rustls();
        let cert_chain = self.chain_der_rustls();

        rustls::ClientConfig::builder()
            .with_root_certificates(root_store)
            .with_client_auth_cert(cert_chain, private_key)
            .expect("valid mTLS client config")
    }

    fn client_config_mtls_rustls_with_provider(
        &self,
        provider: Arc<CryptoProvider>,
    ) -> rustls::ClientConfig {
        let mut root_store = rustls::RootCertStore::empty();
        root_store
            .add(self.root_certificate_der_rustls())
            .expect("valid root cert");

        let private_key = self.private_key_der_rustls();
        let cert_chain = self.chain_der_rustls();

        rustls::ClientConfig::builder_with_provider(provider)
            .with_safe_default_protocol_versions()
            .expect("valid protocol versions")
            .with_root_certificates(root_store)
            .with_client_auth_cert(cert_chain, private_key)
            .expect("valid mTLS client config")
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
#[cfg(all(feature = "server-config", feature = "client-config"))]
mod tests {
    use super::*;
    use uselesskey_x509::{ChainSpec, X509FactoryExt, X509Spec};

    use std::sync::Once;
    static INIT: Once = Once::new();

    fn install_provider() {
        INIT.call_once(|| {
            // When both `rustls-ring` and `rustls-aws-lc-rs` features are
            // enabled (e.g. via `--all-features`), another provider may
            // already be set as process-default. Ignore the error — the
            // explicit-provider tests cover the critical paths.
            let _ = rustls::crypto::ring::default_provider().install_default();
        });
    }

    fn ring_provider() -> Arc<CryptoProvider> {
        Arc::new(rustls::crypto::ring::default_provider())
    }

    // Maximum iterations for TLS handshake loops to prevent infinite loops
    // A normal TLS handshake completes in well under 10 iterations
    const MAX_HANDSHAKE_ITERATIONS: usize = 10;

    #[test]
    fn server_config_from_chain() {
        install_provider();
        let fx = super::super::testutil::fx();
        let chain = fx.x509_chain("test", ChainSpec::new("test.example.com"));
        // Succeeds without panic = config was built with valid cert/key
        let _cfg = chain.server_config_rustls();
    }

    #[test]
    fn server_config_from_chain_with_provider() {
        install_provider();
        let fx = super::super::testutil::fx();
        let chain = fx.x509_chain("test-provider", ChainSpec::new("test.example.com"));
        let _cfg = chain.server_config_rustls_with_provider(ring_provider());
    }

    #[test]
    fn client_config_from_chain() {
        install_provider();
        let fx = super::super::testutil::fx();
        let chain = fx.x509_chain("test", ChainSpec::new("test.example.com"));
        let _cfg = chain.client_config_rustls();
    }

    #[test]
    fn client_config_from_chain_with_provider() {
        install_provider();
        let fx = super::super::testutil::fx();
        let chain = fx.x509_chain("test-provider", ChainSpec::new("test.example.com"));
        let _cfg = chain.client_config_rustls_with_provider(ring_provider());
    }

    #[test]
    fn server_config_from_self_signed() {
        install_provider();
        let fx = super::super::testutil::fx();
        let cert = fx.x509_self_signed("test", X509Spec::self_signed("test.example.com"));
        let _cfg = cert.server_config_rustls();
    }

    #[test]
    fn server_config_from_self_signed_with_provider() {
        install_provider();
        let fx = super::super::testutil::fx();
        let cert = fx.x509_self_signed("test-provider", X509Spec::self_signed("test.example.com"));
        let _cfg = cert.server_config_rustls_with_provider(ring_provider());
    }

    #[test]
    fn client_config_from_self_signed() {
        install_provider();
        let fx = super::super::testutil::fx();
        let cert = fx.x509_self_signed("test", X509Spec::self_signed("test.example.com"));
        let _cfg = cert.client_config_rustls();
    }

    #[test]
    fn client_config_from_self_signed_with_provider() {
        install_provider();
        let fx = super::super::testutil::fx();
        let cert = fx.x509_self_signed("test-provider", X509Spec::self_signed("test.example.com"));
        let _cfg = cert.client_config_rustls_with_provider(ring_provider());
    }

    #[test]
    fn tls_handshake_roundtrip() {
        let fx = super::super::testutil::fx();
        let chain = fx.x509_chain("tls-test", ChainSpec::new("test.example.com"));

        let provider = ring_provider();
        let server_config = Arc::new(chain.server_config_rustls_with_provider(provider.clone()));
        let client_config = Arc::new(chain.client_config_rustls_with_provider(provider));

        let server_name: rustls::pki_types::ServerName<'_> = "test.example.com".try_into().unwrap();
        let mut server = rustls::ServerConnection::new(server_config).unwrap();
        let mut client =
            rustls::ClientConnection::new(client_config, server_name.to_owned()).unwrap();

        // Drive the handshake to completion by transferring bytes between
        // client and server until neither side needs to write.
        let mut buf = Vec::new();
        for iteration in 0..MAX_HANDSHAKE_ITERATIONS {
            let mut progress = false;

            // client -> server
            buf.clear();
            if client.wants_write() {
                client.write_tls(&mut buf).unwrap();
                if !buf.is_empty() {
                    server.read_tls(&mut &buf[..]).unwrap();
                    server.process_new_packets().unwrap();
                    progress = true;
                }
            }

            // server -> client
            buf.clear();
            if server.wants_write() {
                server.write_tls(&mut buf).unwrap();
                if !buf.is_empty() {
                    client.read_tls(&mut &buf[..]).unwrap();
                    client.process_new_packets().unwrap();
                    progress = true;
                }
            }

            if !progress {
                break;
            }

            // Safety check: if we've exhausted iterations without completing,
            // something is wrong with the handshake state machine
            assert!(
                iteration < MAX_HANDSHAKE_ITERATIONS - 1,
                "TLS handshake did not complete within {} iterations",
                MAX_HANDSHAKE_ITERATIONS
            );
        }

        assert!(!client.is_handshaking());
        assert!(!server.is_handshaking());
    }

    #[test]
    fn mtls_with_provider_roundtrip() {
        let fx = super::super::testutil::fx();
        let chain = fx.x509_chain("mtls-provider-test", ChainSpec::new("test.example.com"));

        let provider = ring_provider();
        let server_config =
            Arc::new(chain.server_config_mtls_rustls_with_provider(provider.clone()));
        let client_config = Arc::new(chain.client_config_mtls_rustls_with_provider(provider));

        let server_name: rustls::pki_types::ServerName<'_> = "test.example.com".try_into().unwrap();
        let mut server = rustls::ServerConnection::new(server_config).unwrap();
        let mut client =
            rustls::ClientConnection::new(client_config, server_name.to_owned()).unwrap();

        let mut buf = Vec::new();
        for iteration in 0..MAX_HANDSHAKE_ITERATIONS {
            let mut progress = false;

            buf.clear();
            if client.wants_write() {
                client.write_tls(&mut buf).unwrap();
                if !buf.is_empty() {
                    server.read_tls(&mut &buf[..]).unwrap();
                    server.process_new_packets().unwrap();
                    progress = true;
                }
            }

            buf.clear();
            if server.wants_write() {
                server.write_tls(&mut buf).unwrap();
                if !buf.is_empty() {
                    client.read_tls(&mut &buf[..]).unwrap();
                    client.process_new_packets().unwrap();
                    progress = true;
                }
            }

            if !progress {
                break;
            }

            // Safety check: if we've exhausted iterations without completing,
            // something is wrong with the handshake state machine
            assert!(
                iteration < MAX_HANDSHAKE_ITERATIONS - 1,
                "mTLS handshake did not complete within {} iterations",
                MAX_HANDSHAKE_ITERATIONS
            );
        }

        assert!(!client.is_handshaking());
        assert!(!server.is_handshaking());
    }

    #[test]
    fn mtls_roundtrip() {
        let fx = super::super::testutil::fx();
        let chain = fx.x509_chain("mtls-test", ChainSpec::new("test.example.com"));

        let provider = ring_provider();
        let server_config =
            Arc::new(chain.server_config_mtls_rustls_with_provider(provider.clone()));
        let client_config = Arc::new(chain.client_config_mtls_rustls_with_provider(provider));

        let server_name: rustls::pki_types::ServerName<'_> = "test.example.com".try_into().unwrap();
        let mut server = rustls::ServerConnection::new(server_config).unwrap();
        let mut client =
            rustls::ClientConnection::new(client_config, server_name.to_owned()).unwrap();

        let mut buf = Vec::new();
        for iteration in 0..MAX_HANDSHAKE_ITERATIONS {
            let mut progress = false;

            buf.clear();
            if client.wants_write() {
                client.write_tls(&mut buf).unwrap();
                if !buf.is_empty() {
                    server.read_tls(&mut &buf[..]).unwrap();
                    server.process_new_packets().unwrap();
                    progress = true;
                }
            }

            buf.clear();
            if server.wants_write() {
                server.write_tls(&mut buf).unwrap();
                if !buf.is_empty() {
                    client.read_tls(&mut &buf[..]).unwrap();
                    client.process_new_packets().unwrap();
                    progress = true;
                }
            }

            if !progress {
                break;
            }

            // Safety check: if we've exhausted iterations without completing,
            // something is wrong with the handshake state machine
            assert!(
                iteration < MAX_HANDSHAKE_ITERATIONS - 1,
                "mTLS handshake did not complete within {} iterations",
                MAX_HANDSHAKE_ITERATIONS
            );
        }

        assert!(!client.is_handshaking());
        assert!(!server.is_handshaking());
    }
}