wasi-pg-client 0.1.0

PostgreSQL client library for WASI Preview 2
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
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
//! Async TLS transport using `rustls` over `AsyncTransport`.
//!
//! This module implements PostgreSQL's SSL negotiation protocol and provides
//! `TlsTransport` — a wrapper that encrypts an underlying `AsyncTransport`.

#[cfg(feature = "tls")]
use std::io::{Read, Write};
#[cfg(feature = "tls")]
use std::sync::Arc;

#[cfg(feature = "tls")]
use sha2::{Digest, Sha224, Sha256, Sha384, Sha512};

use super::{AsyncTransport, BufferedTransport, TransportError};

// ----------------------------------------------------------------------------
// TLS Configuration
// ----------------------------------------------------------------------------

/// TLS configuration for PostgreSQL connections.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct TlsConfig {
    /// SSL mode — controls whether and how TLS is negotiated.
    pub mode: SslMode,

    /// Server name for SNI and certificate validation.
    /// Defaults to the connection hostname.
    pub server_name: String,

    /// Custom CA certificate (PEM or DER format).
    /// If None, uses the embedded Mozilla CA roots.
    pub ca_cert: Option<Vec<u8>>,

    /// Client certificate for mTLS.
    pub client_cert: Option<Vec<u8>>,

    /// Client private key for mTLS.
    pub client_key: Option<Vec<u8>>,

    /// Accept invalid/self-signed certificates.
    /// **WARNING**: Only for development! Never use in production.
    ///
    /// When enabled, certificate-chain and hostname verification are both
    /// disabled regardless of `sslmode`.
    pub accept_invalid_certs: bool,

    /// Custom `rustls::crypto::CryptoProvider`.
    /// If None, uses the default provider for the target platform.
    #[cfg(feature = "tls")]
    pub crypto_provider: Option<Arc<rustls::crypto::CryptoProvider>>,
}

impl TlsConfig {
    /// Create a new `TlsConfig` with the given SSL mode and server name.
    ///
    /// All other fields are set to their defaults.
    pub fn new(mode: SslMode, server_name: impl Into<String>) -> Self {
        Self {
            mode,
            server_name: server_name.into(),
            ..Default::default()
        }
    }

    /// Set the SSL mode.
    pub fn mode(mut self, mode: SslMode) -> Self {
        self.mode = mode;
        self
    }

    /// Set the server name for SNI.
    pub fn server_name(mut self, name: impl Into<String>) -> Self {
        self.server_name = name.into();
        self
    }

    /// Set a custom CA certificate.
    pub fn ca_cert(mut self, cert: Vec<u8>) -> Self {
        self.ca_cert = Some(cert);
        self
    }

    /// Set the client certificate for mTLS.
    pub fn client_cert(mut self, cert: Vec<u8>) -> Self {
        self.client_cert = Some(cert);
        self
    }

    /// Set the client private key for mTLS.
    pub fn client_key(mut self, key: Vec<u8>) -> Self {
        self.client_key = Some(key);
        self
    }

    /// Accept invalid/self-signed certificates.
    /// **WARNING**: Only for development! Never use in production.
    pub fn accept_invalid_certs(mut self, accept: bool) -> Self {
        self.accept_invalid_certs = accept;
        self
    }
}

impl Default for TlsConfig {
    fn default() -> Self {
        Self {
            mode: SslMode::VerifyFull,
            server_name: String::new(),
            ca_cert: None,
            client_cert: None,
            client_key: None,
            accept_invalid_certs: false,
            #[cfg(feature = "tls")]
            crypto_provider: None,
        }
    }
}

/// SSL mode — mirrors PostgreSQL's `sslmode` connection parameter.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
#[non_exhaustive]
pub enum SslMode {
    /// Never use TLS. Connection is plaintext.
    Disable,

    /// Try TLS first; fall back to plaintext if the server doesn't support it.
    Prefer,

    /// Require TLS, but do not verify the server certificate.
    ///
    /// This is provided for PostgreSQL compatibility, but is not recommended
    /// for production use.
    Require,

    /// Require TLS and verify the certificate chain against the configured
    /// trust anchors, but do not verify the hostname.
    VerifyCa,

    /// Require TLS, verify CA and hostname. **Recommended for production.**
    VerifyFull,
}

impl SslMode {
    /// Parse from a PostgreSQL connection string `sslmode` value.
    #[allow(clippy::should_implement_trait)]
    pub fn from_str(s: &str) -> Result<Self, TransportError> {
        match s.to_lowercase().as_str() {
            "disable" => Ok(SslMode::Disable),
            "prefer" => Ok(SslMode::Prefer),
            "require" => Ok(SslMode::Require),
            "verify-ca" => Ok(SslMode::VerifyCa),
            "verify-full" => Ok(SslMode::VerifyFull),
            _ => Err(TransportError::InvalidConfig(format!(
                "invalid sslmode: {}",
                s
            ))),
        }
    }
}

impl std::fmt::Display for SslMode {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            SslMode::Disable => write!(f, "disable"),
            SslMode::Prefer => write!(f, "prefer"),
            SslMode::Require => write!(f, "require"),
            SslMode::VerifyCa => write!(f, "verify-ca"),
            SslMode::VerifyFull => write!(f, "verify-full"),
        }
    }
}

// ----------------------------------------------------------------------------
// rustls ClientConfig builder
// ----------------------------------------------------------------------------

#[cfg(feature = "tls")]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum TlsVerificationPolicy {
    InsecureNoVerify,
    VerifyCaOnly,
    VerifyFull,
}

#[cfg(feature = "tls")]
fn verification_policy(config: &TlsConfig) -> TlsVerificationPolicy {
    if config.accept_invalid_certs || matches!(config.mode, SslMode::Require) {
        TlsVerificationPolicy::InsecureNoVerify
    } else if matches!(config.mode, SslMode::VerifyCa) {
        TlsVerificationPolicy::VerifyCaOnly
    } else {
        TlsVerificationPolicy::VerifyFull
    }
}

#[cfg(feature = "tls")]
fn build_rustls_config(config: &TlsConfig) -> Result<Arc<rustls::ClientConfig>, TransportError> {
    use rustls::client::ClientConfig as RustlsClientConfig;

    // 1. Select CryptoProvider
    let crypto_provider = config
        .crypto_provider
        .clone()
        .unwrap_or_else(default_crypto_provider);

    // 2. Build ClientConfig
    let config_builder = RustlsClientConfig::builder_with_provider(crypto_provider.clone())
        .with_protocol_versions(&[&rustls::version::TLS13, &rustls::version::TLS12])
        .map_err(|e| {
            TransportError::TlsHandshake(format!("unsupported protocol versions: {}", e))
        })?;

    let client_config = match verification_policy(config) {
        TlsVerificationPolicy::InsecureNoVerify => config_builder
            .dangerous()
            .with_custom_certificate_verifier(Arc::new(NoVerifier))
            .with_no_client_auth(),
        TlsVerificationPolicy::VerifyCaOnly => {
            let root_store = build_root_store(config)?;
            let verifier = CertificateVerifier::new(
                Arc::new(root_store),
                crypto_provider.signature_verification_algorithms,
                false,
            );
            config_builder
                .dangerous()
                .with_custom_certificate_verifier(Arc::new(verifier))
                .with_no_client_auth()
        }
        TlsVerificationPolicy::VerifyFull => {
            let root_store = build_root_store(config)?;
            config_builder
                .with_root_certificates(root_store)
                .with_no_client_auth()
        }
    };

    // 3. Configure mTLS (client certificate) if provided
    let mut client_config = client_config;
    if let (Some(cert_bytes), Some(key_bytes)) = (&config.client_cert, &config.client_key) {
        let certs = parse_certs(cert_bytes)?;
        let key = parse_private_key(key_bytes)?;
        let certified_key = rustls::sign::CertifiedKey::from_der(certs, key, &crypto_provider)
            .map_err(|e| TransportError::TlsHandshake(format!("invalid client cert/key: {}", e)))?;
        client_config.client_auth_cert_resolver =
            Arc::new(rustls::sign::SingleCertAndKey::from(certified_key));
    }

    // 4. ALPN: PostgreSQL does not use ALPN
    client_config.alpn_protocols.clear();

    Ok(Arc::new(client_config))
}

#[cfg(feature = "tls")]
fn default_crypto_provider() -> Arc<rustls::crypto::CryptoProvider> {
    Arc::new(rustls_rustcrypto::provider())
}

#[cfg(feature = "tls")]
fn build_root_store(config: &TlsConfig) -> Result<rustls::RootCertStore, TransportError> {
    let mut root_store = rustls::RootCertStore::empty();

    if let Some(ref ca_bytes) = config.ca_cert {
        let certs = parse_certs(ca_bytes)?;
        for cert in certs {
            root_store.add(cert).map_err(|e| {
                TransportError::TlsHandshake(format!("failed to add CA certificate: {}", e))
            })?;
        }
    } else {
        root_store.extend(webpki_roots::TLS_SERVER_ROOTS.iter().cloned());
    }

    Ok(root_store)
}

#[cfg(feature = "tls")]
fn parse_certs(
    bytes: &[u8],
) -> Result<Vec<rustls::pki_types::CertificateDer<'static>>, TransportError> {
    // Try PEM first
    let mut cursor = std::io::Cursor::new(bytes);
    let pem_result: Result<Vec<_>, _> = rustls_pemfile::certs(&mut cursor).collect();
    if let Ok(certs) = pem_result {
        if !certs.is_empty() {
            return Ok(certs);
        }
    }

    // Try DER format
    Ok(vec![rustls::pki_types::CertificateDer::from(
        bytes.to_vec(),
    )])
}

#[cfg(feature = "tls")]
fn parse_private_key(
    bytes: &[u8],
) -> Result<rustls::pki_types::PrivateKeyDer<'static>, TransportError> {
    // Try PEM first
    let mut cursor = std::io::Cursor::new(bytes);
    if let Ok(Some(key)) = rustls_pemfile::private_key(&mut cursor) {
        return Ok(key);
    }

    // Try DER format (PKCS#8)
    Ok(rustls::pki_types::PrivateKeyDer::Pkcs8(
        rustls::pki_types::PrivatePkcs8KeyDer::from(bytes.to_vec()),
    ))
}

#[cfg(feature = "tls")]
fn compute_tls_server_end_point(
    cert: &rustls::pki_types::CertificateDer<'_>,
) -> Result<Option<Vec<u8>>, TransportError> {
    let (_, cert) = x509_parser::parse_x509_certificate(cert.as_ref()).map_err(|e| {
        TransportError::TlsHandshake(format!("failed to parse peer certificate: {e}"))
    })?;

    let signature_oid = cert.signature_algorithm.algorithm.to_id_string();
    let der = cert.as_ref();

    let digest = match signature_oid.as_str() {
        // md5WithRSAEncryption, sha1WithRSAEncryption, ecdsa-with-SHA1
        "1.2.840.113549.1.1.4" | "1.2.840.113549.1.1.5" | "1.2.840.10045.4.1" => {
            Sha256::digest(der).to_vec()
        }
        // sha224WithRSAEncryption, ecdsa-with-SHA224
        "1.2.840.113549.1.1.14" | "1.2.840.10045.4.3.1" => Sha224::digest(der).to_vec(),
        // sha256WithRSAEncryption, ecdsa-with-SHA256
        "1.2.840.113549.1.1.11" | "1.2.840.10045.4.3.2" => Sha256::digest(der).to_vec(),
        // sha384WithRSAEncryption, ecdsa-with-SHA384
        "1.2.840.113549.1.1.12" | "1.2.840.10045.4.3.3" => Sha384::digest(der).to_vec(),
        // sha512WithRSAEncryption, ecdsa-with-SHA512
        "1.2.840.113549.1.1.13" | "1.2.840.10045.4.3.4" => Sha512::digest(der).to_vec(),
        // Unsupported / currently unparsed signature algorithms (for example
        // RSASSA-PSS with parameters) fall back to non-channel-bound SCRAM.
        _ => return Ok(None),
    };

    Ok(Some(digest))
}

// ----------------------------------------------------------------------------
// Certificate verifiers
// ----------------------------------------------------------------------------

#[cfg(feature = "tls")]
#[derive(Debug)]
struct CertificateVerifier {
    roots: Arc<rustls::RootCertStore>,
    supported_algs: rustls::crypto::WebPkiSupportedAlgorithms,
    verify_hostname: bool,
}

#[cfg(feature = "tls")]
impl CertificateVerifier {
    fn new(
        roots: Arc<rustls::RootCertStore>,
        supported_algs: rustls::crypto::WebPkiSupportedAlgorithms,
        verify_hostname: bool,
    ) -> Self {
        Self {
            roots,
            supported_algs,
            verify_hostname,
        }
    }
}

#[cfg(feature = "tls")]
impl rustls::client::danger::ServerCertVerifier for CertificateVerifier {
    fn verify_server_cert(
        &self,
        end_entity: &rustls::pki_types::CertificateDer<'_>,
        intermediates: &[rustls::pki_types::CertificateDer<'_>],
        server_name: &rustls::pki_types::ServerName<'_>,
        _ocsp_response: &[u8],
        now: rustls::pki_types::UnixTime,
    ) -> Result<rustls::client::danger::ServerCertVerified, rustls::Error> {
        let cert = rustls::server::ParsedCertificate::try_from(end_entity)?;
        rustls::client::verify_server_cert_signed_by_trust_anchor(
            &cert,
            &self.roots,
            intermediates,
            now,
            self.supported_algs.all,
        )?;
        if self.verify_hostname {
            rustls::client::verify_server_name(&cert, server_name)?;
        }
        Ok(rustls::client::danger::ServerCertVerified::assertion())
    }

    fn verify_tls12_signature(
        &self,
        message: &[u8],
        cert: &rustls::pki_types::CertificateDer<'_>,
        dss: &rustls::DigitallySignedStruct,
    ) -> Result<rustls::client::danger::HandshakeSignatureValid, rustls::Error> {
        rustls::crypto::verify_tls12_signature(message, cert, dss, &self.supported_algs)
    }

    fn verify_tls13_signature(
        &self,
        message: &[u8],
        cert: &rustls::pki_types::CertificateDer<'_>,
        dss: &rustls::DigitallySignedStruct,
    ) -> Result<rustls::client::danger::HandshakeSignatureValid, rustls::Error> {
        rustls::crypto::verify_tls13_signature(message, cert, dss, &self.supported_algs)
    }

    fn supported_verify_schemes(&self) -> Vec<rustls::SignatureScheme> {
        self.supported_algs.supported_schemes()
    }
}

#[cfg(feature = "tls")]
#[derive(Debug)]
struct NoVerifier;

#[cfg(feature = "tls")]
impl rustls::client::danger::ServerCertVerifier for NoVerifier {
    fn verify_server_cert(
        &self,
        _end_entity: &rustls::pki_types::CertificateDer<'_>,
        _intermediates: &[rustls::pki_types::CertificateDer<'_>],
        _server_name: &rustls::pki_types::ServerName<'_>,
        _ocsp_response: &[u8],
        _now: rustls::pki_types::UnixTime,
    ) -> Result<rustls::client::danger::ServerCertVerified, rustls::Error> {
        Ok(rustls::client::danger::ServerCertVerified::assertion())
    }

    fn verify_tls12_signature(
        &self,
        _message: &[u8],
        _cert: &rustls::pki_types::CertificateDer<'_>,
        _dss: &rustls::DigitallySignedStruct,
    ) -> Result<rustls::client::danger::HandshakeSignatureValid, rustls::Error> {
        Ok(rustls::client::danger::HandshakeSignatureValid::assertion())
    }

    fn verify_tls13_signature(
        &self,
        _message: &[u8],
        _cert: &rustls::pki_types::CertificateDer<'_>,
        _dss: &rustls::DigitallySignedStruct,
    ) -> Result<rustls::client::danger::HandshakeSignatureValid, rustls::Error> {
        Ok(rustls::client::danger::HandshakeSignatureValid::assertion())
    }

    fn supported_verify_schemes(&self) -> Vec<rustls::SignatureScheme> {
        vec![
            rustls::SignatureScheme::ECDSA_NISTP256_SHA256,
            rustls::SignatureScheme::ECDSA_NISTP384_SHA384,
            rustls::SignatureScheme::ED25519,
            rustls::SignatureScheme::RSA_PKCS1_SHA256,
            rustls::SignatureScheme::RSA_PKCS1_SHA384,
            rustls::SignatureScheme::RSA_PKCS1_SHA512,
            rustls::SignatureScheme::RSA_PSS_SHA256,
            rustls::SignatureScheme::RSA_PSS_SHA384,
        ]
    }
}

// ----------------------------------------------------------------------------
// Async TLS transport
// ----------------------------------------------------------------------------

#[cfg(feature = "tls")]
pub struct TlsTransport<T: AsyncTransport> {
    tls_conn: rustls::ClientConnection,
    inner: T,
    tls_server_end_point: Option<Vec<u8>>,
}

#[cfg(feature = "tls")]
impl<T: AsyncTransport> TlsTransport<T> {
    /// Perform an async TLS handshake over the given transport.
    pub async fn handshake(
        inner: T,
        config: Arc<rustls::ClientConfig>,
        server_name: &str,
    ) -> Result<Self, TransportError> {
        let server_name = rustls::pki_types::ServerName::try_from(server_name.to_string())
            .map_err(|e| {
                TransportError::TlsHandshake(format!(
                    "invalid server name '{}': {}",
                    server_name, e
                ))
            })?;

        let mut tls_conn = rustls::ClientConnection::new(config, server_name).map_err(|e| {
            TransportError::TlsHandshake(format!("TLS connection creation failed: {}", e))
        })?;

        let mut inner = inner;
        let mut handshake_buf = [0u8; 8192];

        let mut iterations = 0;
        const MAX_HANDSHAKE_ITERATIONS: u32 = 100;

        loop {
            iterations += 1;
            if iterations > MAX_HANDSHAKE_ITERATIONS {
                return Err(TransportError::TlsHandshake(
                    "TLS handshake did not complete within iteration limit".into(),
                ));
            }

            // 1. Write any pending outgoing TLS data
            let mut outgoing = Vec::new();
            tls_conn
                .write_tls(&mut outgoing)
                .map_err(|e| TransportError::TlsHandshake(format!("write_tls: {}", e)))?;
            if !outgoing.is_empty() {
                inner.write_all(&outgoing).await?;
                inner.flush().await?;
            }

            // 2. Check if handshake is complete
            if !tls_conn.is_handshaking() {
                break;
            }

            // 3. Read incoming TLS data
            let n = inner.read(&mut handshake_buf).await?;
            if n == 0 {
                return Err(TransportError::UnexpectedEof);
            }

            // 4. Feed data to rustls and process
            let bytes_read = tls_conn
                .read_tls(&mut &handshake_buf[..n])
                .map_err(|e| TransportError::TlsHandshake(format!("read_tls: {}", e)))?;

            if bytes_read == 0 {
                return Err(TransportError::TlsHandshake(
                    "TLS handshake stalled: no data consumed".into(),
                ));
            }

            tls_conn
                .process_new_packets()
                .map_err(|e| TransportError::TlsHandshake(format!("process_new_packets: {}", e)))?;
        }

        if tls_conn.is_handshaking() {
            return Err(TransportError::TlsHandshake(
                "TLS handshake incomplete after loop exit".into(),
            ));
        }

        let tls_server_end_point = tls_conn
            .peer_certificates()
            .and_then(|certs| certs.first())
            .map(compute_tls_server_end_point)
            .transpose()?
            .flatten();

        Ok(TlsTransport {
            tls_conn,
            inner,
            tls_server_end_point,
        })
    }

    /// Get the negotiated TLS protocol version (e.g., TLS 1.3).
    pub fn protocol_version(&self) -> Option<rustls::ProtocolVersion> {
        self.tls_conn.protocol_version()
    }

    /// Get the negotiated cipher suite.
    pub fn negotiated_cipher_suite(&self) -> Option<rustls::SupportedCipherSuite> {
        self.tls_conn.negotiated_cipher_suite()
    }

    /// Get the server's peer certificate (if any).
    pub fn peer_certificate(&self) -> Option<rustls::pki_types::CertificateDer<'static>> {
        self.tls_conn
            .peer_certificates()
            .and_then(|certs| certs.first())
            .cloned()
    }

    /// Flush TLS ciphertext from rustls to the underlying async transport.
    async fn flush_tls_outgoing(&mut self) -> Result<(), TransportError> {
        let mut outgoing = Vec::new();
        self.tls_conn
            .write_tls(&mut outgoing)
            .map_err(|e| TransportError::TlsHandshake(format!("write_tls: {}", e)))?;
        if !outgoing.is_empty() {
            self.inner.write_all(&outgoing).await?;
        }
        Ok(())
    }
}

#[cfg(feature = "tls")]
impl<T: AsyncTransport> AsyncTransport for TlsTransport<T> {
    fn is_secure(&self) -> bool {
        true
    }

    fn tls_server_end_point(&self) -> Option<Vec<u8>> {
        self.tls_server_end_point.clone()
    }

    async fn read(&mut self, buf: &mut [u8]) -> Result<usize, TransportError> {
        loop {
            match self.tls_conn.reader().read(buf) {
                Ok(n) => {
                    if n == 0 {
                        return Ok(0);
                    }
                    return Ok(n);
                }
                Err(ref e) if e.kind() == std::io::ErrorKind::WouldBlock => {}
                Err(ref e) if e.kind() == std::io::ErrorKind::ConnectionAborted => {
                    return Ok(0);
                }
                Err(e) => {
                    return Err(TransportError::TlsHandshake(format!("TLS read: {}", e)));
                }
            }

            let mut cipher_buf = [0u8; 8192];
            let n = self.inner.read(&mut cipher_buf).await?;
            if n == 0 {
                return Err(TransportError::UnexpectedEof);
            }

            self.tls_conn
                .read_tls(&mut &cipher_buf[..n])
                .map_err(|e| TransportError::TlsHandshake(format!("read_tls: {}", e)))?;
            self.tls_conn
                .process_new_packets()
                .map_err(|e| TransportError::TlsHandshake(format!("process_new_packets: {}", e)))?;
        }
    }

    async fn write(&mut self, buf: &[u8]) -> Result<usize, TransportError> {
        let n = self
            .tls_conn
            .writer()
            .write(buf)
            .map_err(|e| TransportError::TlsHandshake(format!("TLS write: {}", e)))?;
        self.flush_tls_outgoing().await?;
        Ok(n)
    }

    async fn write_all(&mut self, buf: &[u8]) -> Result<(), TransportError> {
        let mut written = 0;
        while written < buf.len() {
            let n = self
                .tls_conn
                .writer()
                .write(&buf[written..])
                .map_err(|e| TransportError::TlsHandshake(format!("TLS write: {}", e)))?;
            written += n;
        }
        self.flush_tls_outgoing().await?;
        Ok(())
    }

    async fn read_exact(&mut self, buf: &mut [u8]) -> Result<(), TransportError> {
        let mut filled = 0;
        while filled < buf.len() {
            let n = self.read(&mut buf[filled..]).await?;
            if n == 0 {
                return Err(TransportError::UnexpectedEof);
            }
            filled += n;
        }
        Ok(())
    }

    async fn flush(&mut self) -> Result<(), TransportError> {
        self.tls_conn
            .writer()
            .flush()
            .map_err(|e| TransportError::TlsHandshake(format!("TLS flush: {}", e)))?;
        self.flush_tls_outgoing().await?;
        self.inner.flush().await
    }

    async fn shutdown(&mut self) -> Result<(), TransportError> {
        self.tls_conn.send_close_notify();
        self.flush_tls_outgoing().await?;
        self.inner.shutdown().await
    }
}

// ----------------------------------------------------------------------------
// PostgreSQL SSL negotiation
// ----------------------------------------------------------------------------

/// Result of PostgreSQL SSL negotiation.
#[allow(clippy::large_enum_variant)]
pub enum PgTransport<T: AsyncTransport> {
    /// Plaintext connection (no TLS).
    Plain(BufferedTransport<T>),
    /// TLS-encrypted connection.
    #[cfg(feature = "tls")]
    Tls(BufferedTransport<TlsTransport<T>>),
}

impl<T: AsyncTransport> AsyncTransport for PgTransport<T> {
    fn is_secure(&self) -> bool {
        #[cfg(feature = "tls")]
        {
            self.is_tls()
        }
        #[cfg(not(feature = "tls"))]
        {
            false
        }
    }

    fn tls_server_end_point(&self) -> Option<Vec<u8>> {
        match self {
            Self::Plain(t) => t.tls_server_end_point(),
            #[cfg(feature = "tls")]
            Self::Tls(t) => t.tls_server_end_point(),
        }
    }

    async fn read(&mut self, buf: &mut [u8]) -> Result<usize, TransportError> {
        match self {
            Self::Plain(t) => t.read(buf).await,
            #[cfg(feature = "tls")]
            Self::Tls(t) => t.read(buf).await,
        }
    }

    async fn write(&mut self, buf: &[u8]) -> Result<usize, TransportError> {
        match self {
            Self::Plain(t) => t.write(buf).await,
            #[cfg(feature = "tls")]
            Self::Tls(t) => t.write(buf).await,
        }
    }

    async fn write_all(&mut self, buf: &[u8]) -> Result<(), TransportError> {
        match self {
            Self::Plain(t) => t.write_all(buf).await,
            #[cfg(feature = "tls")]
            Self::Tls(t) => t.write_all(buf).await,
        }
    }

    async fn read_exact(&mut self, buf: &mut [u8]) -> Result<(), TransportError> {
        match self {
            Self::Plain(t) => t.read_exact(buf).await,
            #[cfg(feature = "tls")]
            Self::Tls(t) => t.read_exact(buf).await,
        }
    }

    async fn flush(&mut self) -> Result<(), TransportError> {
        match self {
            Self::Plain(t) => t.flush().await,
            #[cfg(feature = "tls")]
            Self::Tls(t) => t.flush().await,
        }
    }

    async fn shutdown(&mut self) -> Result<(), TransportError> {
        match self {
            Self::Plain(t) => t.shutdown().await,
            #[cfg(feature = "tls")]
            Self::Tls(t) => t.shutdown().await,
        }
    }
}

impl<T: AsyncTransport> PgTransport<T> {
    /// Returns true if this transport is using TLS.
    #[cfg(feature = "tls")]
    pub fn is_tls(&self) -> bool {
        matches!(self, Self::Tls(_))
    }

    /// Returns true if this transport is using TLS.
    #[cfg(not(feature = "tls"))]
    pub fn is_tls(&self) -> bool {
        false
    }

    /// Get TLS info if the connection is encrypted.
    #[cfg(feature = "tls")]
    pub fn tls_info(&self) -> Option<TlsInfo> {
        match self {
            Self::Tls(t) => {
                let inner = t.inner();
                Some(TlsInfo {
                    protocol_version: inner.protocol_version().map(|v| format!("{:?}", v)),
                    cipher_suite: inner.negotiated_cipher_suite().map(|v| format!("{:?}", v)),
                    peer_certificate: inner.peer_certificate().map(|c| c.to_vec()),
                })
            }
            Self::Plain(_) => None,
        }
    }

    /// Get TLS info if the connection is encrypted.
    #[cfg(not(feature = "tls"))]
    pub fn tls_info(&self) -> Option<TlsInfo> {
        None
    }
}

/// Information about the TLS connection (if any).
#[derive(Debug)]
#[non_exhaustive]
pub struct TlsInfo {
    pub protocol_version: Option<String>,
    pub cipher_suite: Option<String>,
    pub peer_certificate: Option<Vec<u8>>,
}

/// Verify that `SystemTime::now()` works on this platform.
fn check_time_available() -> Result<(), TransportError> {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map_err(|e| {
            TransportError::TlsHandshake(format!(
                "SystemTime::now() is not available on this platform. \
                 TLS certificate validation requires the current time. \
                 Error: {}",
                e
            ))
        })?;
    Ok(())
}

/// Negotiate TLS with a PostgreSQL server.
///
/// This implements the PostgreSQL SSL negotiation protocol:
/// 1. Send SSLRequest message
/// 2. Read server response (single byte: 'S' or 'N')
/// 3. If 'S', perform TLS handshake
/// 4. If 'N', handle based on SslMode
#[cfg(feature = "tls")]
pub async fn negotiate_tls<T: AsyncTransport>(
    tcp: T,
    config: &TlsConfig,
) -> Result<PgTransport<T>, TransportError> {
    const MAX_SSL_NEGOTIATION_ERROR_LEN: usize = 8 * 1024;
    // Early check: TLS needs current time for certificate validation
    check_time_available()?;

    let mut tcp = tcp;

    // Send SSLRequest message: length=8, code=80877103
    let ssl_request: [u8; 8] = [
        0x00, 0x00, 0x00, 0x08, // length = 8
        0x04, 0xD2, 0x16, 0x2F, // code = 80877103
    ];
    tcp.write_all(&ssl_request).await?;
    tcp.flush().await?;

    // Read server response (single byte)
    let mut response = [0u8; 1];
    tcp.read_exact(&mut response).await?;

    match response[0] {
        b'S' => {
            let tls_config = build_rustls_config(config)?;
            let tls = TlsTransport::handshake(tcp, tls_config, &config.server_name).await?;
            Ok(PgTransport::Tls(BufferedTransport::new(tls)))
        }
        b'N' => match config.mode {
            SslMode::Disable => Ok(PgTransport::Plain(BufferedTransport::new(tcp))),
            SslMode::Prefer => {
                #[cfg(feature = "tracing")]
                tracing::warn!(
                    server_name = %config.server_name,
                    "Server does not support TLS; falling back to plaintext"
                );
                Ok(PgTransport::Plain(BufferedTransport::new(tcp)))
            }
            SslMode::Require | SslMode::VerifyCa | SslMode::VerifyFull => {
                Err(TransportError::TlsNotSupported)
            }
        },
        b'E' => {
            let mut len_buf = [0u8; 4];
            tcp.read_exact(&mut len_buf).await?;
            let len = i32::from_be_bytes(len_buf);
            if len < 4 {
                return Err(TransportError::TlsHandshake(
                    "server sent malformed error response during SSL negotiation".into(),
                ));
            }
            let len = len as usize;
            if len > MAX_SSL_NEGOTIATION_ERROR_LEN {
                return Err(TransportError::TlsHandshake(format!(
                    "server sent oversized SSL negotiation error response: {} bytes",
                    len
                )));
            }
            let mut error_buf = vec![0u8; len - 4];
            tcp.read_exact(&mut error_buf).await?;
            Err(TransportError::TlsHandshake(format!(
                "server rejected SSL request: {:?}",
                String::from_utf8_lossy(&error_buf)
            )))
        }
        other => Err(TransportError::TlsHandshake(format!(
            "unexpected response byte during SSL negotiation: 0x{:02x} ('{}')",
            other,
            char::from_u32(other as u32).unwrap_or('?')
        ))),
    }
}

/// Non-TLS negotiation (when tls feature is disabled).
#[cfg(not(feature = "tls"))]
pub async fn negotiate_tls<T: AsyncTransport>(
    tcp: T,
    config: &TlsConfig,
) -> Result<PgTransport<T>, TransportError> {
    match config.mode {
        SslMode::Disable => Ok(PgTransport::Plain(BufferedTransport::new(tcp))),
        _ => Err(TransportError::TlsHandshake(
            "TLS support is not compiled in. Enable the 'tls' feature flag.".into(),
        )),
    }
}

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

#[cfg(test)]
mod tests {
    use super::*;
    #[allow(unused_imports)]
    use crate::transport::MockTransport;

    #[test]
    fn test_ssl_mode_from_str() {
        assert_eq!(SslMode::from_str("disable").unwrap(), SslMode::Disable);
        assert_eq!(SslMode::from_str("prefer").unwrap(), SslMode::Prefer);
        assert_eq!(SslMode::from_str("require").unwrap(), SslMode::Require);
        assert_eq!(SslMode::from_str("verify-ca").unwrap(), SslMode::VerifyCa);
        assert_eq!(
            SslMode::from_str("verify-full").unwrap(),
            SslMode::VerifyFull
        );
        assert!(matches!(
            SslMode::from_str("invalid"),
            Err(TransportError::InvalidConfig(_))
        ));
    }

    #[test]
    fn test_ssl_mode_display() {
        assert_eq!(SslMode::Disable.to_string(), "disable");
        assert_eq!(SslMode::Prefer.to_string(), "prefer");
        assert_eq!(SslMode::Require.to_string(), "require");
        assert_eq!(SslMode::VerifyCa.to_string(), "verify-ca");
        assert_eq!(SslMode::VerifyFull.to_string(), "verify-full");
    }

    #[cfg(feature = "tls")]
    #[test]
    fn test_verification_policy_matrix() {
        let base = TlsConfig::new(SslMode::VerifyFull, "localhost");

        assert_eq!(
            verification_policy(&TlsConfig::new(SslMode::Require, "localhost")),
            TlsVerificationPolicy::InsecureNoVerify
        );
        assert_eq!(
            verification_policy(&TlsConfig::new(SslMode::VerifyCa, "localhost")),
            TlsVerificationPolicy::VerifyCaOnly
        );
        assert_eq!(
            verification_policy(&TlsConfig::new(SslMode::VerifyFull, "localhost")),
            TlsVerificationPolicy::VerifyFull
        );
        assert_eq!(
            verification_policy(&base.accept_invalid_certs(true)),
            TlsVerificationPolicy::InsecureNoVerify
        );
    }

    #[test]
    fn test_check_time_available() {
        // Should succeed on any platform that supports SystemTime::now
        assert!(check_time_available().is_ok());
    }

    #[test]
    #[cfg(feature = "tls")]
    fn test_parse_certs_der() {
        // A minimal invalid DER certificate (just to test the path)
        let der = vec![0x30, 0x03, 0x01, 0x01, 0xFF]; // SEQUENCE { BOOLEAN TRUE }
        let certs = parse_certs(&der).unwrap();
        assert_eq!(certs.len(), 1);
    }

    #[test]
    #[cfg(feature = "tls")]
    fn test_parse_private_key_der() {
        let der = vec![0x30, 0x03, 0x01, 0x01, 0xFF];
        let key = parse_private_key(&der).unwrap();
        assert!(matches!(key, rustls::pki_types::PrivateKeyDer::Pkcs8(_)));
    }

    #[tokio::test]
    #[cfg(feature = "tls")]
    async fn test_negotiate_tls_server_supports_ssl() {
        use crate::transport::MockTransport;

        // Server responds with 'S' (supports SSL)
        let mock = MockTransport::new(vec![b'S']);
        let config = TlsConfig {
            mode: SslMode::Require,
            server_name: "localhost".into(),
            accept_invalid_certs: true,
            ..Default::default()
        };

        // The handshake will fail because the mock can't provide valid TLS data,
        // but we can at least verify the SSLRequest was sent correctly.
        let result = negotiate_tls(mock, &config).await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_negotiate_tls_server_rejects_ssl() {
        use crate::transport::MockTransport;

        // Server responds with 'N' (no SSL)
        let mock = MockTransport::new(vec![b'N']);
        let config = TlsConfig {
            mode: SslMode::Disable,
            server_name: "localhost".into(),
            ..Default::default()
        };

        let result = negotiate_tls(mock, &config).await;
        assert!(result.is_ok());
        assert!(!result.unwrap().is_tls());
    }

    #[tokio::test]
    #[cfg(feature = "tls")]
    async fn test_negotiate_tls_server_rejects_ssl_require_mode() {
        use crate::transport::MockTransport;

        let mock = MockTransport::new(vec![b'N']);
        let config = TlsConfig {
            mode: SslMode::Require,
            server_name: "localhost".into(),
            ..Default::default()
        };

        let result = negotiate_tls(mock, &config).await;
        assert!(matches!(result, Err(TransportError::TlsNotSupported)));
    }

    #[tokio::test]
    #[cfg(feature = "tls")]
    async fn test_negotiate_tls_server_sends_error() {
        use crate::transport::MockTransport;

        // Server sends 'E' + error message
        let mut response = vec![b'E'];
        response.extend_from_slice(&i32::to_be_bytes(8)); // length = 8
        response.extend_from_slice(b"M\0test"); // message field

        let mock = MockTransport::new(response);
        let config = TlsConfig {
            mode: SslMode::Require,
            server_name: "localhost".into(),
            ..Default::default()
        };

        let result = negotiate_tls(mock, &config).await;
        assert!(matches!(result, Err(TransportError::TlsHandshake(_))));
    }

    #[tokio::test]
    #[cfg(feature = "tls")]
    async fn test_negotiate_tls_unexpected_byte() {
        use crate::transport::MockTransport;

        let mock = MockTransport::new(vec![b'X']);
        let config = TlsConfig {
            mode: SslMode::Require,
            server_name: "localhost".into(),
            ..Default::default()
        };

        let result = negotiate_tls(mock, &config).await;
        assert!(matches!(result, Err(TransportError::TlsHandshake(_))));
    }

    #[test]
    fn test_pg_transport_is_tls_without_feature() {
        let mock = MockTransport::new(vec![]);
        let buf = BufferedTransport::new(mock);
        let pg = PgTransport::Plain(buf);
        assert!(!pg.is_tls());
        assert!(pg.tls_info().is_none());
    }
}