nautilus-network 0.67.0

Network communication machinery for the Nautilus trading engine
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
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
// -------------------------------------------------------------------------------------------------
//  Copyright (C) 2015-2026 Nautech Systems Pty Ltd. All rights reserved.
//  https://nautechsystems.io
//
//  Licensed under the GNU Lesser General Public License Version 3.0 (the "License");
//  You may not use this file except in compliance with the License.
//  You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.
// -------------------------------------------------------------------------------------------------

//! Wraps raw socket streams with TLS encryption and builds `rustls` client configurations from
//! certificate directories.
//!
//! A certificates directory acts as an additional trust store: every certificate that parses
//! from any file directly inside it, regardless of file name, becomes a trust anchor for each
//! connection built from the resulting `ClientConfig`, alongside the webpki roots. No CA or
//! self-signature checks are performed, and a certificate chain matched to a private key in the
//! directory is used as the client certificate instead. Write access to the directory is
//! therefore equivalent to control over which servers those connections trust. Each anchor
//! added this way is logged at INFO with its SHA-256 fingerprint so operators can audit exactly
//! what became trusted.

use std::{
    convert::TryFrom,
    fs::File,
    path::{Path, PathBuf},
    sync::Arc,
};

use anyhow::Context;
use aws_lc_rs::digest::{SHA256, digest};
use nautilus_core::hex;
use nautilus_cryptography::{providers::install_cryptographic_provider, tls::create_tls_config};
use rustls::{
    ClientConfig,
    pki_types::{
        CertificateDer, PrivateKeyDer, PrivatePkcs1KeyDer, PrivatePkcs8KeyDer, PrivateSec1KeyDer,
        ServerName,
        pem::{self, PemObject},
    },
};
use tokio::io::{AsyncRead, AsyncWrite};
use tokio_rustls::TlsConnector;
use tokio_tungstenite::{
    MaybeTlsStream,
    tungstenite::{Error, error::TlsError, handshake::client::Request, stream::Mode},
};

pub(crate) async fn tcp_tls<S>(
    request: &Request,
    mode: Mode,
    stream: S,
    connector: Option<Arc<ClientConfig>>,
) -> Result<MaybeTlsStream<S>, Error>
where
    S: 'static + AsyncRead + AsyncWrite + Send + Unpin,
    MaybeTlsStream<S>: Unpin,
{
    let domain = domain(request)?;

    wrap_stream(stream, domain, mode, connector).await
}

async fn wrap_stream<S>(
    socket: S,
    domain: String,
    mode: Mode,
    tls_config: Option<Arc<ClientConfig>>,
) -> Result<MaybeTlsStream<S>, Error>
where
    S: 'static + AsyncRead + AsyncWrite + Send + Unpin,
{
    match mode {
        Mode::Plain => Ok(MaybeTlsStream::Plain(socket)),
        Mode::Tls => {
            let config = tls_config.unwrap_or_else(create_tls_config);
            let domain = ServerName::try_from(domain.as_str())
                .map_err(|_| TlsError::InvalidDnsName)?
                .to_owned();
            let stream = TlsConnector::from(config).connect(domain, socket).await?;
            Ok(MaybeTlsStream::Rustls(stream))
        }
    }
}

/// Extracts the host name from the request URI.
///
/// # Errors
///
/// Returns an error if the request URI has no host component.
fn domain(request: &Request) -> Result<String, Error> {
    match request.uri().host() {
        // rustls expects IPv6 addresses without the surrounding [] brackets
        Some(d) if d.starts_with('[') && d.ends_with(']') => Ok(d[1..d.len() - 1].to_string()),
        Some(d) => Ok(d.to_string()),
        None => Err(Error::Io(std::io::Error::new(
            std::io::ErrorKind::InvalidInput,
            "Request URI missing host component",
        ))),
    }
}

pub(crate) fn create_tls_config_from_certs_dir(
    certs_dir: &Path,
    require_client_auth: bool,
) -> anyhow::Result<rustls::ClientConfig> {
    install_cryptographic_provider();

    if !certs_dir.is_dir() {
        anyhow::bail!(
            "Certificate path is not a directory: {}",
            certs_dir.display()
        );
    }

    let mut all_certs: Vec<(std::path::PathBuf, Vec<CertificateDer<'static>>)> = Vec::new();
    let mut client_key = None;
    let mut root_store = rustls::RootCertStore::empty();
    root_store.extend(webpki_roots::TLS_SERVER_ROOTS.iter().cloned());

    for path in list_files(certs_dir)? {
        if client_key.is_none() {
            // No early continue: a combined PEM carries the certificate alongside
            // the key, so this file is still scanned for certificates below.
            client_key = load_private_key(&path)?;
        }

        let certs = load_certs(&path)?;
        if !certs.is_empty() {
            all_certs.push((path, certs));
        }
    }

    // If key found, find the matching client cert by trial validation
    let client_cert = if let Some(ref key) = client_key
        && !all_certs.is_empty()
    {
        let mut matched = None;

        for i in 0..all_certs.len() {
            let test_config = rustls::ClientConfig::builder()
                .with_root_certificates(rustls::RootCertStore::empty())
                .with_client_auth_cert(all_certs[i].1.clone(), key.clone_key());
            if test_config.is_ok() {
                let (path, cert) = all_certs.remove(i);
                log::debug!("Matched client certificate from {}", path.display());
                matched = Some(cert);
                break;
            }
        }

        if matched.is_none() {
            log::warn!(
                "Private key found but no matching client certificate in {}",
                certs_dir.display()
            );
        }

        matched
    } else {
        None
    };

    for (path, certs) in all_certs {
        for cert in certs {
            let fingerprint = fingerprint_sha256(&cert);
            match root_store.add(cert) {
                Ok(()) => log::info!(
                    "Trusting root certificate from {} (SHA-256 fingerprint: {fingerprint})",
                    path.display()
                ),
                Err(e) => log::warn!("Invalid certificate in {}: {e}", path.display()),
            }
        }
    }

    let builder = rustls::ClientConfig::builder().with_root_certificates(root_store);
    if let (Some(cert), Some(key)) = (client_cert, client_key) {
        return Ok(builder.with_client_auth_cert(cert, key)?);
    }

    if require_client_auth {
        anyhow::bail!(
            "Client certificate or private key missing in {} but client auth required",
            certs_dir.display(),
        );
    }

    log::debug!(
        "No TLS client certificate/key pair found in {}; proceeding without client authentication",
        certs_dir.display(),
    );

    Ok(builder.with_no_client_auth())
}

// Sorted for deterministic selection; unreadable metadata errors rather than reading as absent
fn list_files(dir: &Path) -> anyhow::Result<Vec<PathBuf>> {
    let mut paths = Vec::new();

    for entry in std::fs::read_dir(dir)? {
        let path = entry?.path();
        let metadata = std::fs::metadata(&path)
            .with_context(|| format!("failed to read metadata for {}", path.display()))?;

        if metadata.is_file() {
            paths.push(path);
        }
    }

    paths.sort();
    Ok(paths)
}

fn load_private_key(path: &Path) -> anyhow::Result<Option<PrivateKeyDer<'static>>> {
    if let Some(key) = read_pem_items::<PrivatePkcs8KeyDer>(path)?
        .into_iter()
        .next()
    {
        return Ok(Some(key.into()));
    }

    if let Some(key) = read_pem_items::<PrivatePkcs1KeyDer>(path)?
        .into_iter()
        .next()
    {
        return Ok(Some(key.into()));
    }

    let key = read_pem_items::<PrivateSec1KeyDer>(path)?
        .into_iter()
        .next();
    Ok(key.map(Into::into))
}

fn load_certs(path: &Path) -> anyhow::Result<Vec<CertificateDer<'static>>> {
    read_pem_items(path)
}

// Skips malformed PEM blocks but propagates I/O errors so unreadable is not read as empty
fn read_pem_items<T: PemObject>(path: &Path) -> anyhow::Result<Vec<T>> {
    let file = File::open(path).with_context(|| format!("failed to open {}", path.display()))?;
    let mut items = Vec::new();

    for item in T::pem_reader_iter(file) {
        match item {
            Ok(item) => items.push(item),
            Err(pem::Error::Io(e)) => {
                return Err(e).with_context(|| format!("failed to read {}", path.display()));
            }
            Err(_) => {}
        }
    }

    Ok(items)
}

fn fingerprint_sha256(cert: &CertificateDer<'_>) -> String {
    hex::encode(digest(&SHA256, cert.as_ref()))
}

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

    #[cfg(target_os = "linux")]
    #[cfg(not(all(feature = "simulation", madsim)))]
    use log::Level;
    use rstest::rstest;
    use rustls::{
        ClientConnection, Connection, ServerConnection,
        pki_types::{PrivatePkcs1KeyDer, PrivatePkcs8KeyDer, PrivateSec1KeyDer, ServerName},
        server::WebPkiClientVerifier,
    };
    use tokio::io::{AsyncReadExt, AsyncWriteExt};
    use tokio_rustls::TlsAcceptor;

    use super::*;
    #[cfg(target_os = "linux")]
    #[cfg(not(all(feature = "simulation", madsim)))]
    use crate::logging::tests::capture_logs_for;

    // Test certificates generated with:
    // openssl req -x509 -newkey rsa:2048 -keyout key.pem -out cert.pem -days 3650 -nodes
    const TEST_CERT: &str = "-----BEGIN CERTIFICATE-----
MIIDCTCCAfGgAwIBAgIUXzkvs6Ax5p8YYbc6KPC4x1sZuqgwDQYJKoZIhvcNAQEL
BQAwFDESMBAGA1UEAwwJbG9jYWxob3N0MB4XDTI2MDEwODIzNTYxMVoXDTM2MDEw
NjIzNTYxMVowFDESMBAGA1UEAwwJbG9jYWxob3N0MIIBIjANBgkqhkiG9w0BAQEF
AAOCAQ8AMIIBCgKCAQEAsa03TrY+zTXNonP40Fa8Ui9y6WMG8KmclvHl6nDLxiXb
CwxDHRCP2g7ThaWrqUaise1/K4LA5yH1+l4qUZ3MmpLo5f4RgyzgOc9OPoRT/weh
O78G+6+O82MCYxGUMDAya6Q6k7Zvc/HfdoUJhkDpiWVBQpWOH+kpM5O084MRGucn
AdhbuPVo/V5w9++td1rUcv75NhGxI47A/yy/ZffCRklnh+M8YejjwRJI14uhAAnO
h6el8A9Qwgb2nuyUg7pAKenkIuYFMidqnCwEAcE9ix0re+A+H11MqWVIUeHW6fI2
gfv9FWkZDka/76YAuCe2eLZ6WR6ubk3wcSuqdx898wIDAQABo1MwUTAdBgNVHQ4E
FgQUew+Y/26vcPPfyLkqc7pGMvOlNigwHwYDVR0jBBgwFoAUew+Y/26vcPPfyLkq
c7pGMvOlNigwDwYDVR0TAQH/BAUwAwEB/zANBgkqhkiG9w0BAQsFAAOCAQEATTd1
Jsi3yi3MXf3GPAohdbVBdOixQj5/m8Ne/w3YtYBtUhViAiXxYyDPZeKmRd35dxyr
0Mb0NT6TAitchhKnHej4tQrco6Ou/cBUX5Wp5AmCXqCbG8st/iFUnfuxZ8khdVx9
nLkvYWLN+KVV8rAs+dYnHhWZhXaso28/1XP81iT27uXMlUv0LsTXn0+EsA5q1fSE
+6vX6mRHix+Y5FOuBTN5WpdJSA6ReBnIwikMq4r5oZw7uvnv0boMCrc/Ob/OLEBO
p7IFiQUGnQjf+3/xxKYEB9X8RiWFAeL73HRQDZNoAxcavPgUD2zir7W18phYC0RB
QnLUubWTCa8z45k3oQ==
-----END CERTIFICATE-----";

    // Second test CA certificate (CN=test-ca-2, different key material)
    const TEST_CA_CERT_2: &str = "-----BEGIN CERTIFICATE-----
MIIDCTCCAfGgAwIBAgIUdVEP5pTvhV0TAFlTYkuV0cSQVowwDQYJKoZIhvcNAQEL
BQAwFDESMBAGA1UEAwwJdGVzdC1jYS0yMB4XDTI2MDEwOTAwMDgyNFoXDTM2MDEw
NzAwMDgyNFowFDESMBAGA1UEAwwJdGVzdC1jYS0yMIIBIjANBgkqhkiG9w0BAQEF
AAOCAQ8AMIIBCgKCAQEAtU4t5l7XTH5+NSxwweWmW3iWmIb1H/FpmN53SWFShKS4
yhSiWLBT6SiPArsKFFaQkFM04oLhYQD1V0sL0SlabkRfKbYvXJ1x2gc0UCJWbV0e
0WfVc0fEyjpOnX0+EAKWqQl671UZzbt+lVNj9LIMNsglTRgbFK/CtxKu10eyYK8k
/bFVUpHoacIaEWFk0bbhLS4IO2xfKDEcf29gTUs9wAsYlSOaR+gVlLr0fs7v02tM
Ex7Idkgo43D3tQlL0wqEU5T5+QzqSY3BbMfzySr4I+T1t0Q4WY7F3GrlvbC7zMCW
DBzQ9Gt6MMKf7qqdSsS4YFKGP20kccn3hlXsM3gXnwIDAQABo1MwUTAdBgNVHQ4E
FgQUM+3XKol4ODEuqJWJKN7oh3uKihQwHwYDVR0jBBgwFoAUM+3XKol4ODEuqJWJ
KN7oh3uKihQwDwYDVR0TAQH/BAUwAwEB/zANBgkqhkiG9w0BAQsFAAOCAQEATFm/
ufbzleLM2258Pd/wJUxE/Bs4zPrXpi0aHfVFbakvRoOJvcpuQi8vGaVPApriQhp/
8u94E8Owhi+bqZzcjXBg8d4wRGGeG2WdZ1ROEpu7uHHNGuXP12ndz/LnZUMtTD7H
R/mOrHN4JnUw91q5QdKxbsHGHR+pFl662Yc7pewJ8FloxoFxD6igZG/1TdpdK4ii
1bBxQD0CS9mD0tD2CXi/mFwbLTsY4qpoOT1TJJJcq/MldTcWAVEJpJ9UhblDtSy+
zhxL/14wqaVBwUW6/RNRr9hz6MkFFC8Uced5obScy8kOI0bMbeIC4ftNGG9pUdms
3BSW8BRUdXasnBkWIg==
-----END CERTIFICATE-----";

    struct TestIdentity {
        key_pem: String,
        cert_pem: String,
        key_der: PrivateKeyDer<'static>,
        cert_der: CertificateDer<'static>,
    }

    fn generate_identity() -> TestIdentity {
        let key_pair = rcgen::KeyPair::generate().unwrap();
        let cert = rcgen::CertificateParams::new(vec!["localhost".to_string()])
            .unwrap()
            .self_signed(&key_pair)
            .unwrap();

        TestIdentity {
            key_pem: key_pair.serialize_pem(),
            cert_pem: cert.pem(),
            key_der: PrivatePkcs8KeyDer::from(key_pair.serialize_der()).into(),
            cert_der: cert.der().clone(),
        }
    }

    #[tokio::test]
    async fn test_tcp_tls_wraps_stream_and_transfers_data() {
        install_cryptographic_provider();
        let server_identity = generate_identity();
        let mut roots = rustls::RootCertStore::empty();
        roots.add(server_identity.cert_der.clone()).unwrap();
        let client_config = rustls::ClientConfig::builder()
            .with_root_certificates(roots)
            .with_no_client_auth();
        let server_config = rustls::ServerConfig::builder()
            .with_no_client_auth()
            .with_single_cert(
                vec![server_identity.cert_der],
                server_identity.key_der.clone_key(),
            )
            .unwrap();
        let request = Request::builder()
            .uri("wss://localhost/socket")
            .body(())
            .unwrap();
        let (client_socket, server_socket) = tokio::io::duplex(1024);

        let server_task = tokio::spawn(async move {
            let mut stream = TlsAcceptor::from(Arc::new(server_config))
                .accept(server_socket)
                .await
                .unwrap();
            let mut request = [0u8; 4];
            stream.read_exact(&mut request).await.unwrap();
            stream.write_all(b"pong").await.unwrap();
            request
        });

        let mut stream = tcp_tls(
            &request,
            Mode::Tls,
            client_socket,
            Some(Arc::new(client_config)),
        )
        .await
        .unwrap();
        let is_tls = matches!(&stream, MaybeTlsStream::Rustls(_));
        stream.write_all(b"ping").await.unwrap();
        let mut response = [0u8; 4];
        stream.read_exact(&mut response).await.unwrap();
        let received = server_task.await.unwrap();

        assert!(is_tls);
        assert_eq!(received, *b"ping");
        assert_eq!(response, *b"pong");
    }

    #[rstest]
    #[case::combined(true)]
    #[case::separate(false)]
    fn test_client_auth_files_complete_mutual_tls_handshake(#[case] combined: bool) {
        let client_identity = generate_identity();
        let server_identity = generate_identity();
        let temp_dir = tempfile::tempdir().unwrap();

        if combined {
            std::fs::write(
                temp_dir.path().join("client.pem"),
                format!("{}{}", client_identity.key_pem, client_identity.cert_pem),
            )
            .unwrap();
        } else {
            std::fs::write(
                temp_dir.path().join("client-key.pem"),
                &client_identity.key_pem,
            )
            .unwrap();
            std::fs::write(
                temp_dir.path().join("client-cert.pem"),
                &client_identity.cert_pem,
            )
            .unwrap();
        }

        std::fs::write(
            temp_dir.path().join("server.pem"),
            &server_identity.cert_pem,
        )
        .unwrap();

        let client_config = create_tls_config_from_certs_dir(temp_dir.path(), true).unwrap();

        assert_mutual_tls_handshake(client_config, &client_identity, server_identity);
    }

    #[rstest]
    fn test_ca_only_directory_succeeds() {
        let temp_dir = tempfile::tempdir().unwrap();
        let ca1_path = temp_dir.path().join("ca1.pem");
        let ca2_path = temp_dir.path().join("ca2.pem");
        std::fs::write(&ca1_path, TEST_CERT).unwrap();
        std::fs::write(&ca2_path, TEST_CA_CERT_2).unwrap();

        let result = create_tls_config_from_certs_dir(temp_dir.path(), false);

        let config = result.unwrap();
        assert!(!config.client_auth_cert_resolver.has_certs());
    }

    #[rstest]
    fn test_ca_only_directory_fails_when_client_auth_required() {
        let temp_dir = tempfile::tempdir().unwrap();
        let ca_path = temp_dir.path().join("ca.pem");
        std::fs::write(&ca_path, TEST_CERT).unwrap();

        let result = create_tls_config_from_certs_dir(temp_dir.path(), true);

        assert!(
            result.is_err(),
            "Should fail when client auth required but no key present"
        );
        let err_msg = result.unwrap_err().to_string();
        assert!(
            err_msg.contains("client auth required"),
            "Error should mention client auth required: {err_msg}"
        );
    }

    #[rstest]
    fn test_empty_directory_succeeds_without_client_auth() {
        let temp_dir = tempfile::tempdir().unwrap();

        let result = create_tls_config_from_certs_dir(temp_dir.path(), false);

        assert!(
            result.is_ok(),
            "Empty directory should succeed without client auth: {:?}",
            result.err()
        );
    }

    #[rstest]
    fn test_not_a_directory_fails() {
        let temp_dir = tempfile::tempdir().unwrap();
        let file_path = temp_dir.path().join("not_a_dir.txt");
        std::fs::write(&file_path, "test").unwrap();

        let result = create_tls_config_from_certs_dir(&file_path, false);
        assert!(result.is_err(), "Non-directory path should fail");

        let err_msg = result.unwrap_err().to_string();
        assert!(
            err_msg.contains("not a directory"),
            "Error should mention not a directory: {err_msg}"
        );
    }

    #[rstest]
    fn test_invalid_cert_file_ignored() {
        let temp_dir = tempfile::tempdir().unwrap();
        let ca_path = temp_dir.path().join("ca.pem");
        let invalid_path = temp_dir.path().join("invalid.pem");
        std::fs::write(&ca_path, TEST_CERT).unwrap();
        std::fs::write(&invalid_path, "not a valid certificate").unwrap();

        let result = create_tls_config_from_certs_dir(temp_dir.path(), false);
        assert!(
            result.is_ok(),
            "Should succeed ignoring invalid cert file: {:?}",
            result.err()
        );
    }

    #[cfg(target_os = "linux")]
    #[cfg(not(all(feature = "simulation", madsim)))]
    #[tokio::test]
    async fn test_dropped_pem_is_surfaced_as_trusted_root() {
        let temp_dir = tempfile::tempdir().unwrap();
        // Any file dropped into the directory that carries a valid PEM certificate becomes a
        // trust anchor, regardless of name, so the load must be surfaced to the operator
        let dropped_path = temp_dir.path().join("notes.txt");
        std::fs::write(&dropped_path, TEST_CERT).unwrap();

        let capture = capture_logs_for(&["nautilus_network::tls"]).await;
        let config = create_tls_config_from_certs_dir(temp_dir.path(), false).unwrap();
        // The capture buffer is process-global and only target-filtered, so parallel tests
        // reaching the loader can add records; this test's records are the ones naming the
        // unique dropped path
        let dropped = dropped_path.display().to_string();
        let trust_messages: Vec<String> = capture
            .messages()
            .into_iter()
            .filter(|(level, _)| *level == Level::Info)
            .filter(|(_, message)| message.contains(&dropped))
            .map(|(_, message)| message)
            .collect();

        assert!(!config.client_auth_cert_resolver.has_certs());
        assert_eq!(
            trust_messages,
            vec![format!(
                "Trusting root certificate from {} (SHA-256 fingerprint: {})",
                dropped,
                // SHA-256 of the TEST_CERT DER bytes
                "e56da924fb335d2e54b94f8fe44a2b4c6dac3ab868bbbd8d41bb0596541019a3",
            )]
        );
    }

    #[rstest]
    fn test_load_private_key_reads_supported_formats() {
        let temp_dir = tempfile::tempdir().unwrap();
        let path = temp_dir.path().join("key.pem");
        let expected_der = vec![1, 2, 3, 4];
        let cases = [
            (
                "PRIVATE KEY",
                PrivateKeyDer::Pkcs8(PrivatePkcs8KeyDer::from(expected_der.clone())),
            ),
            (
                "RSA PRIVATE KEY",
                PrivateKeyDer::Pkcs1(PrivatePkcs1KeyDer::from(expected_der.clone())),
            ),
            (
                "EC PRIVATE KEY",
                PrivateKeyDer::Sec1(PrivateSec1KeyDer::from(expected_der)),
            ),
        ];

        for (label, expected) in cases {
            std::fs::write(&path, pem_block(label, "AQIDBA==")).unwrap();

            let key = load_private_key(&path).unwrap();

            assert_eq!(key, Some(expected));
        }
    }

    #[rstest]
    fn test_load_private_key_preserves_format_priority() {
        let temp_dir = tempfile::tempdir().unwrap();
        let path = temp_dir.path().join("keys.pem");
        let pem = [
            pem_block("RSA PRIVATE KEY", "AQ=="),
            pem_block("EC PRIVATE KEY", "Ag=="),
            pem_block("PRIVATE KEY", "Aw=="),
        ]
        .concat();
        std::fs::write(&path, pem).unwrap();

        let key = load_private_key(&path).unwrap();

        assert_eq!(
            key,
            Some(PrivateKeyDer::Pkcs8(PrivatePkcs8KeyDer::from(vec![3])))
        );
    }

    #[rstest]
    fn test_load_private_key_skips_malformed_blocks() {
        let temp_dir = tempfile::tempdir().unwrap();
        let path = temp_dir.path().join("key.pem");
        let pem = [
            pem_block("PRIVATE KEY", "invalid!"),
            pem_block("PRIVATE KEY", "BQYH"),
        ]
        .concat();
        std::fs::write(&path, pem).unwrap();

        let key = load_private_key(&path).unwrap();

        assert_eq!(
            key,
            Some(PrivateKeyDer::Pkcs8(PrivatePkcs8KeyDer::from(vec![
                5, 6, 7
            ])))
        );
    }

    #[rstest]
    fn test_load_private_key_returns_none_for_file_without_key() {
        let temp_dir = tempfile::tempdir().unwrap();
        let path = temp_dir.path().join("cert.pem");
        std::fs::write(&path, pem_block("CERTIFICATE", "AQ==")).unwrap();

        let key = load_private_key(&path).unwrap();

        assert_eq!(key, None);
    }

    #[rstest]
    fn test_load_certs_fails_on_read_error() {
        // A directory fails on read (Unix) or on open (Windows)
        let temp_dir = tempfile::tempdir().unwrap();

        let error = load_certs(temp_dir.path()).unwrap_err();

        let expected_prefix = if cfg!(windows) {
            "failed to open"
        } else {
            "failed to read"
        };

        assert_eq!(
            error.to_string(),
            format!("{expected_prefix} {}", temp_dir.path().display())
        );
    }

    #[rstest]
    fn test_certs_directory_skips_subdirectories() {
        let temp_dir = tempfile::tempdir().unwrap();
        std::fs::write(temp_dir.path().join("ca.pem"), TEST_CERT).unwrap();
        std::fs::create_dir(temp_dir.path().join("archive")).unwrap();

        let config = create_tls_config_from_certs_dir(temp_dir.path(), false).unwrap();

        assert!(!config.client_auth_cert_resolver.has_certs());
    }

    #[cfg(unix)]
    #[rstest]
    fn test_certs_directory_fails_on_dangling_symlink() {
        let temp_dir = tempfile::tempdir().unwrap();
        std::fs::write(temp_dir.path().join("ca.pem"), TEST_CERT).unwrap();
        let link_path = temp_dir.path().join("client.key");
        std::os::unix::fs::symlink(temp_dir.path().join("missing.key"), &link_path).unwrap();

        let error = create_tls_config_from_certs_dir(temp_dir.path(), false).unwrap_err();

        assert_eq!(
            error.to_string(),
            format!("failed to read metadata for {}", link_path.display())
        );
    }

    #[cfg(unix)]
    #[rstest]
    fn test_certs_directory_fails_on_unreadable_key_file() {
        use std::os::unix::fs::PermissionsExt;

        let temp_dir = tempfile::tempdir().unwrap();
        let identity = generate_identity();
        std::fs::write(temp_dir.path().join("client.crt"), &identity.cert_pem).unwrap();
        let key_path = temp_dir.path().join("client.key");
        std::fs::write(&key_path, &identity.key_pem).unwrap();
        std::fs::set_permissions(&key_path, std::fs::Permissions::from_mode(0o000)).unwrap();

        // Privileged users bypass file permissions, so the failure cannot be simulated
        if File::open(&key_path).is_ok() {
            return;
        }

        let error = create_tls_config_from_certs_dir(temp_dir.path(), false).unwrap_err();

        assert_eq!(
            error.to_string(),
            format!("failed to open {}", key_path.display())
        );
    }

    #[rstest]
    fn test_load_certs_reads_all_valid_certificate_blocks() {
        let temp_dir = tempfile::tempdir().unwrap();
        let path = temp_dir.path().join("mixed.pem");
        let pem = [
            pem_block("PRIVATE KEY", "AQ=="),
            pem_block("CERTIFICATE", "invalid!"),
            pem_block("CERTIFICATE", "AgM="),
            pem_block("CERTIFICATE", "BAU="),
        ]
        .concat();
        std::fs::write(&path, pem).unwrap();

        let certs = load_certs(&path).unwrap();

        assert_eq!(
            certs,
            vec![
                CertificateDer::from(vec![2, 3]),
                CertificateDer::from(vec![4, 5]),
            ]
        );
    }

    fn pem_block(label: &str, payload: &str) -> String {
        format!(
            "-----{} {label}-----\n{payload}\n-----{} {label}-----\n",
            "BEGIN", "END"
        )
    }

    fn assert_mutual_tls_handshake(
        client_config: rustls::ClientConfig,
        client_identity: &TestIdentity,
        server_identity: TestIdentity,
    ) {
        let mut client_roots = rustls::RootCertStore::empty();
        client_roots.add(client_identity.cert_der.clone()).unwrap();
        let verifier = WebPkiClientVerifier::builder(Arc::new(client_roots))
            .build()
            .unwrap();
        let server_config = rustls::ServerConfig::builder()
            .with_client_cert_verifier(verifier)
            .with_single_cert(
                vec![server_identity.cert_der],
                server_identity.key_der.clone_key(),
            )
            .unwrap();
        let server_name = ServerName::try_from("localhost").unwrap();
        let mut client = Connection::Client(
            ClientConnection::new(Arc::new(client_config), server_name).unwrap(),
        );
        let mut server =
            Connection::Server(ServerConnection::new(Arc::new(server_config)).unwrap());

        for _ in 0..10 {
            transfer_tls(&mut client, &mut server);
            transfer_tls(&mut server, &mut client);
            if !client.is_handshaking() && !server.is_handshaking() {
                break;
            }
        }

        assert!(!client.is_handshaking());
        assert!(!server.is_handshaking());
        assert_eq!(
            server.peer_certificates().unwrap(),
            std::slice::from_ref(&client_identity.cert_der)
        );
    }

    fn transfer_tls(from: &mut Connection, to: &mut Connection) {
        let mut bytes = Vec::new();
        from.write_tls(&mut bytes).unwrap();
        if bytes.is_empty() {
            return;
        }

        to.read_tls(&mut Cursor::new(bytes)).unwrap();
        to.process_new_packets().unwrap();
    }
}