pg_walstream 0.9.0

PostgreSQL logical replication protocol library - parse and handle PostgreSQL WAL streaming messages
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
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
//! TLS negotiation and PostgreSQL startup sequence.
//!
//! Handles:
//! 1. TCP connection
//! 2. SSLRequest → TLS handshake (via rustls) if required
//! 3. StartupMessage with protocol v3.0
//! 4. Authentication delegation to `auth.rs`
//! 5. Backend parameter processing until ReadyForQuery

use super::conninfo::{ConnInfo, SslMode, SslNegotiation, SSLROOTCERT_SYSTEM};
use super::wire;
use crate::error::ReplicationError;
use bytes::BytesMut;
use rustls::pki_types::pem::PemObject;
use std::sync::{Arc, LazyLock};
use std::time::Duration;
use tokio::io::{AsyncRead, AsyncWrite, BufReader};
use tokio::net::TcpStream;
use tokio_rustls::TlsConnector;

/// Lazily-initialized, cached crypto provider.
///
/// `aws_lc_rs::default_provider()` constructs a new `CryptoProvider` on each call.
/// Caching it via `LazyLock` ensures one-time initialization and reuse across
/// all TLS connections.
static CRYPTO_PROVIDER: LazyLock<Arc<rustls::crypto::CryptoProvider>> =
    LazyLock::new(|| Arc::new(rustls::crypto::aws_lc_rs::default_provider()));

/// Return a reference to the cached aws-lc-rs crypto provider.
///
/// aws-lc-rs leverages AES-NI, AVX2, and SHA-NI instructions for
/// high-throughput AES-GCM decryption during WAL streaming.
fn crypto_provider() -> Arc<rustls::crypto::CryptoProvider> {
    CRYPTO_PROVIDER.clone()
}

/// Size of the read buffer wrapping the TLS stream.
///
/// Wrapping the TLS stream in a `BufReader` reduces syscall overhead because
/// TLS record processing benefits from reading in larger chunks rather than
/// many small reads.
///
/// - A single TLS record payload is at most 16,384 bytes (2^14, per RFC 8446).
/// - `postgres-openssl` and `postgres-native-tls` use 8,192 (one typical record).
/// - For **replication streaming**, we use 65,536 so one `read()` can pull several maximum-size TLS records at once. The CopyData drain loop (`copy::drain_read_buffer`) then parses more WAL messages per wakeup,  cutting syscalls and — on the worker-thread driver — cross-thread batch handoffs during sustained high-throughput WAL consumption.
///
/// Exposed `pub(crate)` so `copy.rs` can pin its read-headroom invariant
/// (`MIN_HEADROOM > TLS_BUF_SIZE`) to this value at compile time, guaranteeing tokio's `BufReader` always bypasses its buffer on the CopyData hot path.
pub(crate) const TLS_BUF_SIZE: usize = 65_536;

/// The transport layer — either plain TCP or TLS-wrapped TCP.
///
/// The TLS variant wraps the `TlsStream` in a `BufReader` to reduce read
/// syscall frequency during high-throughput WAL streaming.
// One Transport per connection on the I/O hot path. Boxing the Tls variant to
// satisfy large_enum_variant would add a pointer indirection to every read and
// write, so the size gap is an intentional tradeoff.
#[allow(clippy::large_enum_variant)]
pub enum Transport {
    Plain(TcpStream),
    Tls(BufReader<tokio_rustls::client::TlsStream<TcpStream>>),
}

impl Transport {
    /// Get the TLS `tls-server-end-point` channel binding data, if this is a TLS connection.
    ///
    /// Per RFC 5929: hash the server's DER-encoded end-entity certificate.
    /// The hash algorithm depends on the certificate's signature algorithm:
    /// - MD5 or SHA-1 → use SHA-256
    /// - Otherwise → use the signature algorithm's hash (SHA-256, SHA-384, SHA-512)
    pub fn tls_server_end_point(&self) -> Option<Vec<u8>> {
        match self {
            Transport::Tls(buf_reader) => {
                let tls_stream = buf_reader.get_ref();
                let (_, conn) = tls_stream.get_ref();
                let certs = conn.peer_certificates()?;
                let ee_cert_der = certs.first()?;

                // Parse the certificate to determine the signature algorithm
                let hash = compute_tls_server_end_point_hash(ee_cert_der.as_ref())?;
                Some(hash)
            }
            Transport::Plain(_) => None,
        }
    }
}

/// Compute the `tls-server-end-point` hash per RFC 5929.
///
/// Parses the certificate's signature algorithm OID to select the correct
/// hash: MD5/SHA-1 → SHA-256, others → matching hash. Falls back to SHA-256
/// if the OID is unrecognized.
fn compute_tls_server_end_point_hash(cert_der: &[u8]) -> Option<Vec<u8>> {
    use aws_lc_rs::digest;

    // The signature algorithm OID is the second-to-last sequence in the
    // top-level certificate SEQUENCE. Rather than pulling in a full X.509
    // parser, we look for well-known OID byte patterns in the DER.
    //
    // Signature algorithm OIDs we care about:
    //   sha256WithRSAEncryption: 1.2.840.113549.1.1.11  → 06 09 2a 86 48 86 f7 0d 01 01 0b
    //   sha384WithRSAEncryption: 1.2.840.113549.1.1.12  → 06 09 2a 86 48 86 f7 0d 01 01 0c
    //   sha512WithRSAEncryption: 1.2.840.113549.1.1.13  → 06 09 2a 86 48 86 f7 0d 01 01 0d
    //   ecdsa-with-SHA256:       1.2.840.10045.4.3.2    → 06 08 2a 86 48 ce 3d 04 03 02
    //   ecdsa-with-SHA384:       1.2.840.10045.4.3.3    → 06 08 2a 86 48 ce 3d 04 03 03
    //   ecdsa-with-SHA512:       1.2.840.10045.4.3.4    → 06 08 2a 86 48 ce 3d 04 03 04
    //   md5WithRSAEncryption:    1.2.840.113549.1.1.4   → 06 09 2a 86 48 86 f7 0d 01 01 04
    //   sha1WithRSAEncryption:   1.2.840.113549.1.1.5   → 06 09 2a 86 48 86 f7 0d 01 01 05

    // RSA signature OID prefix: 2a 86 48 86 f7 0d 01 01
    let rsa_prefix = &[0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01];
    // ECDSA signature OID prefix: 2a 86 48 ce 3d 04 03
    let ecdsa_prefix = &[0x2a, 0x86, 0x48, 0xce, 0x3d, 0x04, 0x03];

    let algorithm = if let Some(pos) = find_subsequence(cert_der, rsa_prefix) {
        let suffix_pos = pos + rsa_prefix.len();
        if suffix_pos < cert_der.len() {
            match cert_der[suffix_pos] {
                0x04 | 0x05 => &digest::SHA256, // MD5 or SHA-1 → use SHA-256 per RFC 5929
                0x0b => &digest::SHA256,        // sha256WithRSA
                0x0c => &digest::SHA384,        // sha384WithRSA
                0x0d => &digest::SHA512,        // sha512WithRSA
                _ => &digest::SHA256,           // unknown → default to SHA-256
            }
        } else {
            &digest::SHA256
        }
    } else if let Some(pos) = find_subsequence(cert_der, ecdsa_prefix) {
        let suffix_pos = pos + ecdsa_prefix.len();
        if suffix_pos < cert_der.len() {
            match cert_der[suffix_pos] {
                0x02 => &digest::SHA256, // ecdsa-with-SHA256
                0x03 => &digest::SHA384, // ecdsa-with-SHA384
                0x04 => &digest::SHA512, // ecdsa-with-SHA512
                _ => &digest::SHA256,    // unknown → default to SHA-256
            }
        } else {
            &digest::SHA256
        }
    } else {
        // Unknown signature algorithm → default to SHA-256
        &digest::SHA256
    };

    let hash = digest::digest(algorithm, cert_der);
    Some(hash.as_ref().to_vec())
}

/// Find the first occurrence of `needle` in `haystack`.
fn find_subsequence(haystack: &[u8], needle: &[u8]) -> Option<usize> {
    haystack
        .windows(needle.len())
        .position(|window| window == needle)
}

impl AsyncRead for Transport {
    fn poll_read(
        self: std::pin::Pin<&mut Self>,
        cx: &mut std::task::Context<'_>,
        buf: &mut tokio::io::ReadBuf<'_>,
    ) -> std::task::Poll<std::io::Result<()>> {
        match self.get_mut() {
            Transport::Plain(ref mut s) => std::pin::Pin::new(s).poll_read(cx, buf),
            Transport::Tls(ref mut s) => std::pin::Pin::new(s).poll_read(cx, buf),
        }
    }
}

impl AsyncWrite for Transport {
    fn poll_write(
        self: std::pin::Pin<&mut Self>,
        cx: &mut std::task::Context<'_>,
        buf: &[u8],
    ) -> std::task::Poll<std::io::Result<usize>> {
        match self.get_mut() {
            Transport::Plain(ref mut s) => std::pin::Pin::new(s).poll_write(cx, buf),
            Transport::Tls(ref mut s) => std::pin::Pin::new(s).poll_write(cx, buf),
        }
    }

    fn poll_flush(
        self: std::pin::Pin<&mut Self>,
        cx: &mut std::task::Context<'_>,
    ) -> std::task::Poll<std::io::Result<()>> {
        match self.get_mut() {
            Transport::Plain(ref mut s) => std::pin::Pin::new(s).poll_flush(cx),
            Transport::Tls(ref mut s) => std::pin::Pin::new(s).poll_flush(cx),
        }
    }

    fn poll_shutdown(
        self: std::pin::Pin<&mut Self>,
        cx: &mut std::task::Context<'_>,
    ) -> std::task::Poll<std::io::Result<()>> {
        match self.get_mut() {
            Transport::Plain(ref mut s) => std::pin::Pin::new(s).poll_shutdown(cx),
            Transport::Tls(ref mut s) => std::pin::Pin::new(s).poll_shutdown(cx),
        }
    }
}

/// Establish a TCP connection, optionally upgrade to TLS, and perform the
/// PostgreSQL startup + authentication handshake.
///
/// Returns the established transport and server version.
///
/// `connect_timeout` bounds the **whole** establishment, not just the TCP handshake.
/// libpq documents it as "Maximum time to wait while connecting" — i.e. through
/// `CONNECTION_OK` — and the phases after the SYN are where a connection actually
/// parks: a stalled proxy, a half-dead load balancer or a `DROP`-after-accept
/// firewall completes the TCP handshake and then goes silent, leaving the TLS
/// negotiation or the auth exchange waiting on a read that never arrives.
/// `tcp_user_timeout` does not rescue that case — it is Linux-only and only fires on
/// *unacknowledged* writes, so a peer that ACKs and says nothing defeats it.
///
/// [`tcp_connect`] keeps its own inner timeout: it fires first for the common
/// SYN-timeout case and names the address, which is a better diagnostic than the
/// generic deadline below. The outer budget covers the phases that have none.
pub async fn connect(info: &ConnInfo) -> Result<(Transport, i32, BytesMut), ReplicationError> {
    if info.connect_timeout == 0 {
        return connect_inner(info).await;
    }

    let budget = Duration::from_secs(info.connect_timeout);
    tokio::time::timeout(budget, connect_inner(info))
        .await
        .map_err(|_| {
            ReplicationError::transient_connection(format!(
                "Connection to {}:{} timed out after {}s before the startup handshake completed",
                info.host, info.port, info.connect_timeout
            ))
        })?
}

async fn connect_inner(info: &ConnInfo) -> Result<(Transport, i32, BytesMut), ReplicationError> {
    let addr = format!("{}:{}", info.host, info.port);

    let tcp = tcp_connect(&addr, info).await?;

    let mut transport = match info.sslmode {
        SslMode::Disable => Transport::Plain(tcp),
        SslMode::Prefer | SslMode::Allow => {
            // For prefer/allow: attempt TLS, but fall back to a new plaintext.
            match negotiate_tls(tcp, info).await {
                Ok(t) => t,
                Err(e) => {
                    tracing::debug!("TLS negotiation failed, falling back to plain: {e}");
                    let tcp = tcp_connect(&addr, info).await?;
                    Transport::Plain(tcp)
                }
            }
        }
        _ => negotiate_tls(tcp, info).await?,
    };

    // Perform startup + auth
    let mut buf = BytesMut::with_capacity(8192);
    let server_version = startup_and_auth(&mut transport, &mut buf, info).await?;

    Ok((transport, server_version, buf))
}

/// Open a TCP connection with optional timeout, TCP_NODELAY, and keepalive.
async fn tcp_connect(addr: &str, info: &ConnInfo) -> Result<TcpStream, ReplicationError> {
    let tcp = if info.connect_timeout > 0 {
        let timeout = Duration::from_secs(info.connect_timeout);
        tokio::time::timeout(timeout, TcpStream::connect(addr))
            .await
            .map_err(|_| {
                ReplicationError::transient_connection(format!(
                    "Connection to {addr} timed out after {}s",
                    info.connect_timeout
                ))
            })?
            .map_err(|e| {
                ReplicationError::transient_connection(format!("Failed to connect to {addr}: {e}"))
            })?
    } else {
        TcpStream::connect(addr).await.map_err(|e| {
            ReplicationError::transient_connection(format!("Failed to connect to {addr}: {e}"))
        })?
    };

    tcp.set_nodelay(true).ok();

    if info.keepalives {
        configure_tcp_keepalive(&tcp, info);
    }

    if info.tcp_user_timeout > 0 {
        configure_tcp_user_timeout(&tcp, info);
    }

    Ok(tcp)
}

/// Configure TCP keepalive on the socket using socket2.
///
/// This is critical for long-running replication connections over cloud networks
/// where load balancers silently drop idle TCP connections.
fn configure_tcp_keepalive(tcp: &TcpStream, info: &ConnInfo) {
    use socket2::SockRef;

    let sock = SockRef::from(tcp);
    let keepalive = socket2::TcpKeepalive::new()
        .with_time(Duration::from_secs(info.keepalives_idle))
        .with_interval(Duration::from_secs(info.keepalives_interval));

    // retries/count is platform-specific
    #[cfg(any(
        target_os = "linux",
        target_os = "macos",
        target_os = "ios",
        target_os = "freebsd",
        target_os = "netbsd",
    ))]
    let keepalive = keepalive.with_retries(info.keepalives_count);

    if let Err(e) = sock.set_tcp_keepalive(&keepalive) {
        tracing::warn!("Failed to set TCP keepalive: {e}");
    } else {
        tracing::debug!(
            "TCP keepalive configured: idle={}s, interval={}s",
            info.keepalives_idle,
            info.keepalives_interval
        );
    }
}

/// Configure `TCP_USER_TIMEOUT` on the socket using socket2.
///
/// The only knob that bounds a blocking control-plane round-trip. Keepalives
/// bound the *idle* case; they never fire while a reply is outstanding, because
/// the connection is not idle. So a `DROP_REPLICATION_SLOT` issued from snapshot
/// cleanup in `Drop` against a peer that has silently gone away waits for the
/// keepalive cycle only because the socket eventually goes idle — this sets a
/// deadline on the unacknowledged write itself.
///
/// Best-effort on purpose: a sandbox that refuses the `setsockopt` must not fail
/// an otherwise-healthy connection, so this warns rather than returning `Err`.
#[cfg(any(
    target_os = "linux",
    target_os = "android",
    target_os = "fuchsia",
    target_os = "cygwin",
))]
fn configure_tcp_user_timeout(tcp: &TcpStream, info: &ConnInfo) {
    use socket2::SockRef;

    let sock = SockRef::from(tcp);
    // Milliseconds — libpq's unit for this option, unlike every other timeout
    // in `ConnInfo`, which is seconds.
    if let Err(e) = sock.set_tcp_user_timeout(Some(Duration::from_millis(info.tcp_user_timeout))) {
        tracing::warn!("Failed to set TCP_USER_TIMEOUT: {e}");
    } else {
        tracing::debug!("TCP_USER_TIMEOUT configured: {}ms", info.tcp_user_timeout);
    }
}

/// No-op fallback: `TCP_USER_TIMEOUT` is Linux-family only.
///
/// Warns rather than staying silent — the whole reason this option was wired up
/// is that it used to be accepted and then discarded with no diagnostic.
#[cfg(not(any(
    target_os = "linux",
    target_os = "android",
    target_os = "fuchsia",
    target_os = "cygwin",
)))]
fn configure_tcp_user_timeout(_tcp: &TcpStream, info: &ConnInfo) {
    tracing::warn!(
        "tcp_user_timeout={}ms ignored: TCP_USER_TIMEOUT is not available on this platform",
        info.tcp_user_timeout
    );
}

/// Perform TLS negotiation: send SSLRequest, check response, do handshake.
///
/// Supports two modes:
/// - **Postgres** (default): Send SSLRequest, wait for `'S'`/`'N'`, then handshake.
/// - **Direct** (PG 17+): Skip SSLRequest, send TLS ClientHello immediately with
///   ALPN `"postgresql"`. Falls back to standard negotiation on failure.
async fn negotiate_tls(tcp: TcpStream, info: &ConnInfo) -> Result<Transport, ReplicationError> {
    if info.sslnegotiation == SslNegotiation::Direct {
        // Direct mode: attempt TLS handshake immediately with ALPN.
        // On failure, fall back to standard SSLRequest negotiation with a fresh connection.
        match negotiate_tls_direct(tcp, info).await {
            Ok(transport) => return Ok(transport),
            Err(e) => {
                tracing::debug!(
                    "Direct SSL negotiation failed, falling back to standard SSLRequest: {e}"
                );
                // The TCP connection is consumed by the failed handshake attempt.
                // Open a new one for the standard SSLRequest fallback.
                let addr = format!("{}:{}", info.host, info.port);
                let tcp = tcp_connect(&addr, info).await?;
                return negotiate_tls_standard(tcp, info).await;
            }
        }
    }

    negotiate_tls_standard(tcp, info).await
}

/// Standard PostgreSQL TLS negotiation via SSLRequest.
async fn negotiate_tls_standard(
    mut tcp: TcpStream,
    info: &ConnInfo,
) -> Result<Transport, ReplicationError> {
    // Send SSLRequest
    let ssl_req = wire::build_ssl_request();
    wire::write_all(&mut tcp, &ssl_req).await?;
    wire::flush(&mut tcp).await?;

    let response = wire::read_byte(&mut tcp).await?;

    match response {
        b'S' => {
            // Server supports SSL — do the handshake
            let tls_config = build_tls_config(info)?;
            let connector = TlsConnector::from(Arc::new(tls_config));

            let server_name = rustls::pki_types::ServerName::try_from(info.host.as_str())
                .map_err(|e| {
                    ReplicationError::permanent_connection(format!(
                        "Invalid server name for TLS: {e}"
                    ))
                })?
                .to_owned();

            let tls_stream = connector.connect(server_name, tcp).await.map_err(|e| {
                ReplicationError::transient_connection(format!("TLS handshake failed: {e}"))
            })?;

            tracing::debug!("TLS connection established");
            log_negotiated_suite(&tls_stream);
            Ok(Transport::Tls(BufReader::with_capacity(
                TLS_BUF_SIZE,
                tls_stream,
            )))
        }
        b'N' => {
            // Server does not support SSL
            match info.sslmode {
                SslMode::Require | SslMode::VerifyCa | SslMode::VerifyFull => {
                    Err(ReplicationError::permanent_connection(
                        "Server does not support SSL but sslmode=require".to_string(),
                    ))
                }
                _ => {
                    tracing::debug!("Server doesn't support SSL, falling back to plain");
                    Ok(Transport::Plain(tcp))
                }
            }
        }
        other => Err(ReplicationError::protocol(format!(
            "Unexpected SSLRequest response: 0x{other:02x}"
        ))),
    }
}

/// Direct TLS negotiation (PostgreSQL 17+).
///
/// Skips the SSLRequest round-trip entirely: sends TLS ClientHello immediately
/// with ALPN protocol `"postgresql"` so the server knows this is a PostgreSQL
/// connection rather than HTTPS or another protocol.
///
/// This saves one full network round-trip compared to standard negotiation.
async fn negotiate_tls_direct(
    tcp: TcpStream,
    info: &ConnInfo,
) -> Result<Transport, ReplicationError> {
    let mut tls_config = build_tls_config(info)?;

    // Set ALPN to "postgresql" — this is how the server distinguishes a direct
    // TLS PostgreSQL connection from other protocols.
    tls_config.alpn_protocols = vec![b"postgresql".to_vec()];

    let connector = TlsConnector::from(Arc::new(tls_config));

    let server_name = rustls::pki_types::ServerName::try_from(info.host.as_str())
        .map_err(|e| {
            ReplicationError::permanent_connection(format!("Invalid server name for TLS: {e}"))
        })?
        .to_owned();

    let tls_stream = connector.connect(server_name, tcp).await.map_err(|e| {
        ReplicationError::transient_connection(format!("Direct TLS handshake failed: {e}"))
    })?;

    tracing::debug!("Direct TLS connection established (ALPN postgresql)");
    log_negotiated_suite(&tls_stream);
    Ok(Transport::Tls(BufReader::with_capacity(
        TLS_BUF_SIZE,
        tls_stream,
    )))
}

/// Log the negotiated TLS cipher suite for verification that hardware-accelerated
/// AES-GCM (via aws-lc-rs) was selected rather than an unexpected fallback.
fn log_negotiated_suite(tls_stream: &tokio_rustls::client::TlsStream<TcpStream>) {
    if let Some(suite) = tls_stream.get_ref().1.negotiated_cipher_suite() {
        tracing::info!("TLS negotiated cipher suite: {:?}", suite.suite());
    }
}

/// Build a rustls `ClientConfig` based on the sslmode.
fn build_tls_config(info: &ConnInfo) -> Result<rustls::ClientConfig, ReplicationError> {
    let provider = crypto_provider();

    match info.sslmode {
        SslMode::VerifyFull => {
            // Full verification: check cert chain + hostname
            let root_store = build_root_store(info.sslrootcert.as_deref())?;
            let config = rustls::ClientConfig::builder_with_provider(provider)
                .with_safe_default_protocol_versions()
                .map_err(|e| {
                    ReplicationError::permanent_connection(format!(
                        "Failed to configure TLS protocol versions: {e}"
                    ))
                })?
                .with_root_certificates(root_store)
                .with_no_client_auth();
            Ok(config)
        }
        SslMode::VerifyCa => {
            // Verify cert chain but NOT hostname.
            let root_store = build_root_store(info.sslrootcert.as_deref())?;
            let verifier = NoHostnameVerifier::new(root_store, provider.clone());

            let config = rustls::ClientConfig::builder_with_provider(provider)
                .with_safe_default_protocol_versions()
                .map_err(|e| {
                    ReplicationError::permanent_connection(format!(
                        "Failed to configure TLS protocol versions: {e}"
                    ))
                })?
                .dangerous()
                .with_custom_certificate_verifier(Arc::new(verifier))
                .with_no_client_auth();
            Ok(config)
        }
        SslMode::Require | SslMode::Prefer | SslMode::Allow => {
            // Encrypt but skip certificate verification entirely.
            // This matches libpq's `sslmode=require` behavior.
            let config = rustls::ClientConfig::builder_with_provider(provider.clone())
                .with_safe_default_protocol_versions()
                .map_err(|e| {
                    ReplicationError::permanent_connection(format!(
                        "Failed to configure TLS protocol versions: {e}"
                    ))
                })?
                .dangerous()
                .with_custom_certificate_verifier(Arc::new(NoVerification(provider)))
                .with_no_client_auth();
            Ok(config)
        }
        SslMode::Disable => {
            unreachable!("TLS config not needed when sslmode=disable")
        }
    }
}

/// Build a `RootCertStore` from available certificate sources.
///
/// Priority:
/// 1. If `sslrootcert` is provided, load ONLY those CAs (exclusive).
/// 2. Otherwise, load the bundled Mozilla CA set via `webpki-roots`.
fn build_root_store(sslrootcert: Option<&str>) -> Result<rustls::RootCertStore, ReplicationError> {
    let mut store = rustls::RootCertStore::empty();

    // 1. `system` is libpq's reserved word for "the trusted CA roots from the SSL
    //    implementation" (PG16+), not a file path. Opening it as one would look
    //    for a file literally named `system`. Fall through to the bundled roots.
    if sslrootcert == Some(SSLROOTCERT_SYSTEM) {
        store.extend(webpki_roots::TLS_SERVER_ROOTS.iter().cloned());
        return Ok(store);
    }

    // 2. Custom CA file — if specified, use ONLY these CAs
    if let Some(path) = sslrootcert {
        let file = std::fs::File::open(path).map_err(|e| {
            ReplicationError::permanent_connection(format!(
                "Failed to open sslrootcert file '{path}': {e}"
            ))
        })?;
        let mut reader = std::io::BufReader::new(file);
        let certs: Vec<rustls::pki_types::CertificateDer<'static>> =
            rustls::pki_types::CertificateDer::pem_reader_iter(&mut reader)
                .collect::<Result<Vec<_>, _>>()
                .map_err(|e| {
                    ReplicationError::permanent_connection(format!(
                        "Failed to parse PEM certificates from '{path}': {e}"
                    ))
                })?;
        if certs.is_empty() {
            return Err(ReplicationError::permanent_connection(format!(
                "No certificates found in sslrootcert file '{path}'"
            )));
        }
        for cert in certs {
            store.add(cert).map_err(|e| {
                ReplicationError::permanent_connection(format!(
                    "Failed to add certificate from '{path}': {e}"
                ))
            })?;
        }
        return Ok(store);
    }

    // 3. Mozilla CA bundle via webpki-roots
    store.extend(webpki_roots::TLS_SERVER_ROOTS.iter().cloned());

    Ok(store)
}

/// A certificate verifier that accepts any certificate (no verification).
/// Used for `sslmode=require` which only requires encryption, not authentication.
#[derive(Debug)]
struct NoVerification(Arc<rustls::crypto::CryptoProvider>);

impl rustls::client::danger::ServerCertVerifier for NoVerification {
    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> {
        self.0.signature_verification_algorithms.supported_schemes()
    }
}

/// A certificate verifier that checks the certificate chain against the root
/// store but does NOT verify the hostname. Used for `sslmode=verify-ca`.
#[derive(Debug)]
struct NoHostnameVerifier {
    inner: Arc<rustls::client::WebPkiServerVerifier>,
}

impl NoHostnameVerifier {
    fn new(roots: rustls::RootCertStore, provider: Arc<rustls::crypto::CryptoProvider>) -> Self {
        let inner =
            rustls::client::WebPkiServerVerifier::builder_with_provider(Arc::new(roots), provider)
                .build()
                .expect("failed to build WebPkiServerVerifier");
        Self { inner }
    }
}

impl rustls::client::danger::ServerCertVerifier for NoHostnameVerifier {
    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> {
        // Delegate to the inner WebPki verifier. If it succeeds, great.
        // If it fails ONLY because of hostname mismatch, that's OK for verify-ca.
        // All other errors (expired, untrusted CA, revoked, etc.) must propagate.
        match self.inner.verify_server_cert(
            end_entity,
            intermediates,
            server_name,
            ocsp_response,
            now,
        ) {
            Ok(v) => Ok(v),
            Err(rustls::Error::InvalidCertificate(rustls::CertificateError::NotValidForName)) => {
                // Hostname mismatch is expected and OK for verify-ca
                Ok(rustls::client::danger::ServerCertVerified::assertion())
            }
            Err(rustls::Error::InvalidCertificate(
                rustls::CertificateError::NotValidForNameContext { .. },
            )) => {
                // Same as NotValidForName but with context info
                Ok(rustls::client::danger::ServerCertVerified::assertion())
            }
            Err(other) => Err(other), // Propagate all real errors
        }
    }

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

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

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

/// Send the StartupMessage and handle authentication + parameter negotiation.
///
/// Returns the server version number (e.g. 160001 for 16.1).
async fn startup_and_auth(
    transport: &mut Transport,
    buf: &mut BytesMut,
    info: &ConnInfo,
) -> Result<i32, ReplicationError> {
    // Build startup parameters
    let replication_str;
    let mut params: Vec<(&str, &str)> = vec![
        ("user", &info.user),
        ("database", &info.dbname),
        ("client_encoding", "UTF8"),
    ];

    match info.replication {
        super::conninfo::ReplicationMode::Database => {
            replication_str = "database".to_string();
            params.push(("replication", &replication_str));
        }
        super::conninfo::ReplicationMode::Physical => {
            replication_str = "true".to_string();
            params.push(("replication", &replication_str));
        }
        super::conninfo::ReplicationMode::None => {}
    }

    let startup_msg = wire::build_startup_message(&params);
    wire::write_all(transport, &startup_msg).await?;
    wire::flush(transport).await?;

    // Authenticate (with channel binding if TLS is active)
    let tls_server_end_point = transport.tls_server_end_point();
    super::auth::authenticate(
        transport,
        buf,
        &info.user,
        info.password.as_deref(),
        tls_server_end_point,
    )
    .await?;

    // Process post-auth messages: ParameterStatus, BackendKeyData, ReadyForQuery
    let mut server_version = 0i32;

    loop {
        let msg = wire::read_message(transport, buf).await?;
        if msg.is_empty() {
            continue;
        }

        match msg[0] {
            b'S' => {
                // ParameterStatus: key\0value\0
                let payload = &msg[5..];
                let (key, consumed) = wire::read_cstring(payload);
                let (value, _) = wire::read_cstring(&payload[consumed..]);
                tracing::debug!("ParameterStatus: {key}={value}");

                if key == "server_version" {
                    server_version = parse_server_version(value);
                }
            }
            b'K' => {
                // BackendKeyData: pid(4) + secret_key(4)
                tracing::debug!("Received BackendKeyData");
            }
            b'Z' => {
                // ReadyForQuery — startup complete
                tracing::debug!("Startup complete, server ready");
                break;
            }
            b'E' => {
                let fields = super::error::parse_error_fields(&msg[5..]);
                return Err(ReplicationError::from_sqlstate_startup(
                    &fields.code,
                    format!("Server error during startup: {fields}"),
                ));
            }
            b'N' => {
                // NoticeResponse — log and continue
                let fields = super::error::parse_error_fields(&msg[5..]);
                tracing::info!("Server notice: {}", fields);
            }
            _ => {
                tracing::debug!("Skipping message type '{}' during startup", msg[0] as char);
            }
        }
    }

    if server_version < 140000 {
        return Err(ReplicationError::permanent_connection(format!(
            "PostgreSQL version {} is not supported. Requires 14+",
            server_version
        )));
    }

    Ok(server_version)
}

/// Leading ASCII-digit run of `s`, or 0. Pre-release servers report
/// "19beta3"/"19rc1"/"19devel"; a plain `parse` yields 0 for those, which the
/// caller's `< 140000` floor then rejects as "version 0".
fn leading_num(s: &str) -> i32 {
    s.split(|c: char| !c.is_ascii_digit())
        .next()
        .unwrap_or("")
        .parse()
        .unwrap_or(0)
}

/// Parse a server_version string like "16.1" or "16.1 (Debian 16.1-1)"
/// into the integer format used by libpq (e.g. 160001).
fn parse_server_version(version_str: &str) -> i32 {
    // Take the first word (before any space or parenthetical)
    let version = version_str.split_whitespace().next().unwrap_or("");

    let parts: Vec<&str> = version.split('.').collect();
    match parts.len() {
        1 => {
            // e.g. "16" → 160000, "19beta3" → 190000
            leading_num(parts[0]) * 10000
        }
        2 => {
            // e.g. "16.1" → 160001
            leading_num(parts[0]) * 10000 + leading_num(parts[1])
        }
        _ => {
            // e.g. "14.2.1" → 140201
            leading_num(parts[0]) * 10000 + leading_num(parts[1]) * 100 + leading_num(parts[2])
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    /// `sslrootcert=system` is libpq's reserved word for the platform trust
    /// store, not a path. Treating it as a path was the silent-downgrade bug:
    /// `build_root_store` is only reached from the verifying modes, so the bogus
    /// path never even produced a file-open error.
    #[test]
    fn build_root_store_maps_system_to_bundled_roots() {
        let store = build_root_store(Some(SSLROOTCERT_SYSTEM)).expect("system must resolve");
        assert!(!store.is_empty(), "system must load real CA roots");
        assert_eq!(
            store.len(),
            webpki_roots::TLS_SERVER_ROOTS.len(),
            "system must be exactly the bundled Mozilla set"
        );
    }

    /// No `sslrootcert` also uses the bundled roots — same outcome, different
    /// branch, so pin both to keep them from drifting apart.
    #[test]
    fn build_root_store_defaults_to_bundled_roots() {
        let store = build_root_store(None).expect("default must resolve");
        assert_eq!(store.len(), webpki_roots::TLS_SERVER_ROOTS.len());
    }

    /// An ordinary path is still opened as a file; `system` must not have turned
    /// every value into "use the bundled roots".
    #[test]
    fn build_root_store_still_reads_a_real_path() {
        let err = build_root_store(Some("/nonexistent/ca.pem"))
            .expect_err("a missing CA file must fail loudly");
        assert!(err.to_string().contains("/nonexistent/ca.pem"), "{err}");
    }

    /// Create a ConnInfo with test defaults, allowing override of specific fields.
    fn test_conninfo(sslmode: SslMode, sslrootcert: Option<String>) -> ConnInfo {
        ConnInfo {
            host: "localhost".to_string(),
            port: 5432,
            user: "test".to_string(),
            password: None,
            dbname: "test".to_string(),
            sslmode,
            sslrootcert,
            sslnegotiation: super::super::conninfo::SslNegotiation::Postgres,
            replication: super::super::conninfo::ReplicationMode::None,
            connect_timeout: 0,
            keepalives: true,
            keepalives_idle: 120,
            keepalives_interval: 10,
            keepalives_count: 3,
            tcp_user_timeout: 0,
        }
    }

    /// Reads the option back off a real socket, so it fails on the two traps the
    /// implementation actually has: treating the value as seconds (libpq's unit
    /// is milliseconds, unlike every other timeout in `ConnInfo`), and nesting
    /// the call inside the `keepalives` branch, which would make
    /// `keepalives=0 tcp_user_timeout=..` a silent no-op.
    #[cfg(any(
        target_os = "linux",
        target_os = "android",
        target_os = "fuchsia",
        target_os = "cygwin",
    ))]
    #[tokio::test]
    async fn tcp_user_timeout_reaches_the_socket_in_milliseconds() {
        use socket2::SockRef;
        use std::net::{TcpListener, TcpStream as StdTcpStream};

        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
        let std_stream = StdTcpStream::connect(listener.local_addr().unwrap()).unwrap();
        std_stream.set_nonblocking(true).unwrap();
        let tcp = TcpStream::from_std(std_stream).unwrap();

        let mut info = test_conninfo(SslMode::Disable, None);
        info.tcp_user_timeout = 15000;
        // Off, to prove the setting does not ride on the keepalive branch.
        info.keepalives = false;

        configure_tcp_user_timeout(&tcp, &info);

        assert_eq!(
            SockRef::from(&tcp).tcp_user_timeout().unwrap(),
            Some(Duration::from_millis(15000)),
            "15000 must land as 15s, not 15000s — libpq's unit here is milliseconds"
        );
    }

    /// The exact gap the outer deadline closes: the peer completes the TCP
    /// handshake and then says nothing. `connect_timeout` used to wrap only
    /// `TcpStream::connect`, so the auth exchange below waited forever — on the
    /// caller's thread, because `connect()` is reached through a blocking
    /// `ready_rx.recv()`. A stalled proxy or `DROP`-after-accept firewall is the
    /// real-world shape.
    #[tokio::test]
    async fn connect_timeout_bounds_the_handshake_not_just_the_syn() {
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();

        // Accept, hold the socket open, and never answer the StartupMessage.
        let _silent_peer = tokio::spawn(async move {
            let (_stream, _) = listener.accept().await.unwrap();
            std::future::pending::<()>().await;
        });

        let mut info = test_conninfo(SslMode::Disable, None);
        info.host = addr.ip().to_string();
        info.port = addr.port();
        info.connect_timeout = 1;

        let started = std::time::Instant::now();
        // `Transport` is not `Debug`, so `expect_err` is unavailable here.
        let err = match connect(&info).await {
            Ok(_) => panic!("a silent peer must not hang the connect"),
            Err(e) => e,
        };

        assert!(
            err.to_string().contains("timed out"),
            "expected a timeout, got: {err}"
        );
        assert!(
            started.elapsed() < Duration::from_secs(5),
            "deadline did not fire promptly: {:?}",
            started.elapsed()
        );
        // Transient: the peer may well be healthy on the next attempt.
        assert!(
            !err.is_permanent(),
            "a handshake timeout must stay retryable"
        );
    }

    #[test]
    fn test_parse_server_version() {
        assert_eq!(parse_server_version("16.1"), 160001);
        assert_eq!(parse_server_version("14.2"), 140002);
        assert_eq!(parse_server_version("16.1 (Debian 16.1-1)"), 160001);
        assert_eq!(parse_server_version("15"), 150000);
    }

    #[test]
    fn test_parse_server_version_three_part() {
        assert_eq!(parse_server_version("14.2.1"), 140201);
        assert_eq!(parse_server_version("9.6.24"), 90624);
    }

    #[test]
    fn test_parse_server_version_empty() {
        assert_eq!(parse_server_version(""), 0);
    }

    #[test]
    fn test_parse_server_version_garbage() {
        assert_eq!(parse_server_version("abc"), 0);
        assert_eq!(parse_server_version("not.a.version"), 0);
    }

    #[test]
    fn test_parse_server_version_with_extra_text() {
        assert_eq!(
            parse_server_version("16.4 (Ubuntu 16.4-1.pgdg22.04+1)"),
            160004
        );
        assert_eq!(parse_server_version("16.12 - Azure"), 160012);
    }

    /// Pre-release servers report a non-numeric major ("19beta3"). These must
    /// clear the 140000 floor, not parse to 0 and be rejected as unsupported.
    #[test]
    fn test_parse_server_version_prerelease() {
        assert_eq!(parse_server_version("19beta3"), 190000);
        assert_eq!(parse_server_version("19rc1"), 190000);
        assert_eq!(parse_server_version("19devel"), 190000);
        assert_eq!(parse_server_version("18beta1 (Debian 18~beta1-1)"), 180000);
    }

    #[test]
    fn test_build_tls_config_require() {
        // Install crypto provider for test
        let _ = rustls::crypto::aws_lc_rs::default_provider().install_default();

        let info = test_conninfo(SslMode::Require, None);
        let config = build_tls_config(&info);
        assert!(config.is_ok());
    }

    #[test]
    fn test_build_tls_config_verify_full() {
        let _ = rustls::crypto::aws_lc_rs::default_provider().install_default();

        let info = test_conninfo(SslMode::VerifyFull, None);
        let config = build_tls_config(&info);
        assert!(config.is_ok());
    }

    #[test]
    fn test_build_tls_config_verify_ca() {
        let _ = rustls::crypto::aws_lc_rs::default_provider().install_default();

        let info = test_conninfo(SslMode::VerifyCa, None);
        let config = build_tls_config(&info);
        assert!(config.is_ok());
    }

    #[test]
    fn test_build_root_store_default() {
        let _ = rustls::crypto::aws_lc_rs::default_provider().install_default();

        // No sslrootcert → should load Mozilla CA bundle
        let store = build_root_store(None).unwrap();
        // Mozilla bundle has 100+ certs
        assert!(store.len() > 50, "Expected many CAs, got {}", store.len());
    }

    #[test]
    fn test_build_root_store_custom_file() {
        let _ = rustls::crypto::aws_lc_rs::default_provider().install_default();

        // Create a temp PEM file with a self-signed cert for testing
        let pem_content = include_str!("../../../load-tests/fixtures/test_ca.pem");
        let dir = std::env::temp_dir().join("pg_walstream_test");
        std::fs::create_dir_all(&dir).unwrap();
        let pem_path = dir.join("test_ca.pem");
        std::fs::write(&pem_path, pem_content).unwrap();

        let store = build_root_store(Some(pem_path.to_str().unwrap())).unwrap();
        // Should contain ONLY the certs from our file, not the Mozilla bundle
        assert!(
            !store.is_empty(),
            "Expected at least 1 CA from custom file, got {}",
            store.len()
        );

        // Clean up
        let _ = std::fs::remove_file(&pem_path);
        let _ = std::fs::remove_dir(&dir);
    }

    #[test]
    fn test_build_root_store_missing_file() {
        let _ = rustls::crypto::aws_lc_rs::default_provider().install_default();

        let result = build_root_store(Some("/nonexistent/path/ca.pem"));
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(
            err.contains("sslrootcert"),
            "Error should mention sslrootcert: {err}"
        );
    }

    #[test]
    fn test_build_root_store_empty_pem_file() {
        let _ = rustls::crypto::aws_lc_rs::default_provider().install_default();

        let dir = std::env::temp_dir().join("pg_walstream_test_empty");
        std::fs::create_dir_all(&dir).unwrap();
        let pem_path = dir.join("empty.pem");
        std::fs::write(&pem_path, b"").unwrap();

        let result = build_root_store(Some(pem_path.to_str().unwrap()));
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(
            err.contains("No certificates found"),
            "Error should mention no certs: {err}"
        );

        let _ = std::fs::remove_file(&pem_path);
        let _ = std::fs::remove_dir(&dir);
    }

    #[test]
    fn test_build_root_store_malformed_pem_file() {
        let _ = rustls::crypto::aws_lc_rs::default_provider().install_default();

        let dir = std::env::temp_dir().join("pg_walstream_test_bad");
        std::fs::create_dir_all(&dir).unwrap();
        let pem_path = dir.join("bad.pem");
        // Valid PEM frame around garbage base64 payload — tickles the parse-error branch.
        std::fs::write(
            &pem_path,
            b"-----BEGIN CERTIFICATE-----\nnot-valid-base64-or-der!!!\n-----END CERTIFICATE-----\n",
        )
        .unwrap();

        let result = build_root_store(Some(pem_path.to_str().unwrap()));
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(
            err.to_lowercase().contains("pem") || err.contains("sslrootcert"),
            "Error should mention PEM/sslrootcert: {err}"
        );

        let _ = std::fs::remove_file(&pem_path);
        let _ = std::fs::remove_dir(&dir);
    }

    #[test]
    fn test_build_root_store_default_uses_webpki_roots() {
        let _ = rustls::crypto::aws_lc_rs::default_provider().install_default();

        // The default path must return exactly the Mozilla bundle size — this guards
        // against accidentally reintroducing a system-CA loader.
        let store = build_root_store(None).unwrap();
        assert_eq!(
            store.len(),
            webpki_roots::TLS_SERVER_ROOTS.len(),
            "Default root store should contain exactly the Mozilla bundle"
        );
    }

    #[test]
    fn test_build_tls_config_verify_full_with_custom_ca() {
        let _ = rustls::crypto::aws_lc_rs::default_provider().install_default();

        let info = test_conninfo(SslMode::VerifyFull, Some("/nonexistent/ca.pem".to_string()));
        // Should fail because the file doesn't exist
        let config = build_tls_config(&info);
        assert!(config.is_err());
    }

    #[test]
    fn test_build_tls_config_require_ignores_sslrootcert() {
        let _ = rustls::crypto::aws_lc_rs::default_provider().install_default();

        let info = test_conninfo(SslMode::Require, Some("/nonexistent/ca.pem".to_string()));
        // sslrootcert is ignored for require mode — should succeed
        let config = build_tls_config(&info);
        assert!(config.is_ok());
    }

    // === Direct SSL negotiation ===

    #[test]
    fn test_build_tls_config_has_no_alpn_by_default() {
        let _ = rustls::crypto::aws_lc_rs::default_provider().install_default();

        let info = test_conninfo(SslMode::Require, None);
        let config = build_tls_config(&info).unwrap();
        assert!(
            config.alpn_protocols.is_empty(),
            "Standard TLS config should have no ALPN protocols set"
        );
    }

    #[test]
    fn test_direct_ssl_sets_alpn_postgresql() {
        let _ = rustls::crypto::aws_lc_rs::default_provider().install_default();

        let info = test_conninfo(SslMode::Require, None);
        let mut config = build_tls_config(&info).unwrap();
        // Simulate what negotiate_tls_direct does
        config.alpn_protocols = vec![b"postgresql".to_vec()];
        assert_eq!(config.alpn_protocols, vec![b"postgresql".to_vec()]);
    }

    #[test]
    fn test_sslnegotiation_default_is_postgres() {
        let info = test_conninfo(SslMode::Require, None);
        assert_eq!(
            info.sslnegotiation,
            super::super::conninfo::SslNegotiation::Postgres
        );
    }

    // === find_subsequence ===

    #[test]
    fn test_find_subsequence_found() {
        let haystack = &[0x01, 0x02, 0x03, 0x04, 0x05];
        assert_eq!(find_subsequence(haystack, &[0x02, 0x03]), Some(1));
    }

    #[test]
    fn test_find_subsequence_at_start() {
        let haystack = &[0x01, 0x02, 0x03];
        assert_eq!(find_subsequence(haystack, &[0x01, 0x02]), Some(0));
    }

    #[test]
    fn test_find_subsequence_at_end() {
        let haystack = &[0x01, 0x02, 0x03];
        assert_eq!(find_subsequence(haystack, &[0x02, 0x03]), Some(1));
    }

    #[test]
    fn test_find_subsequence_not_found() {
        let haystack = &[0x01, 0x02, 0x03];
        assert_eq!(find_subsequence(haystack, &[0x04, 0x05]), None);
    }

    #[test]
    fn test_find_subsequence_single_byte_needle() {
        let haystack = &[0x01, 0x02, 0x03];
        assert_eq!(find_subsequence(haystack, &[0x02]), Some(1));
    }

    #[test]
    fn test_find_subsequence_needle_longer_than_haystack() {
        let haystack = &[0x01];
        assert_eq!(find_subsequence(haystack, &[0x01, 0x02]), None);
    }

    // === compute_tls_server_end_point_hash ===

    /// Build a minimal DER certificate stub containing a known RSA signature algorithm OID.
    /// This is NOT a valid X.509 cert, but contains the OID bytes that
    /// `compute_tls_server_end_point_hash` scans for.
    fn cert_with_rsa_oid(suffix: u8) -> Vec<u8> {
        let mut data = vec![0x30, 0x82, 0x00, 0x10]; // SEQUENCE header (fake)
        data.extend_from_slice(&[0x06, 0x09]); // OID tag + length
                                               // RSA OID prefix: 2a 86 48 86 f7 0d 01 01
        data.extend_from_slice(&[0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, suffix]);
        data.extend_from_slice(&[0x00; 20]); // padding
        data
    }

    /// Build a minimal DER certificate stub containing a known ECDSA signature algorithm OID.
    fn cert_with_ecdsa_oid(suffix: u8) -> Vec<u8> {
        let mut data = vec![0x30, 0x82, 0x00, 0x10]; // SEQUENCE header (fake)
        data.extend_from_slice(&[0x06, 0x08]); // OID tag + length
                                               // ECDSA OID prefix: 2a 86 48 ce 3d 04 03
        data.extend_from_slice(&[0x2a, 0x86, 0x48, 0xce, 0x3d, 0x04, 0x03, suffix]);
        data.extend_from_slice(&[0x00; 20]); // padding
        data
    }

    #[test]
    fn test_channel_binding_hash_sha256_with_rsa() {
        use aws_lc_rs::digest;
        let cert = cert_with_rsa_oid(0x0b); // sha256WithRSAEncryption
        let hash = compute_tls_server_end_point_hash(&cert).unwrap();
        let expected = digest::digest(&digest::SHA256, &cert);
        assert_eq!(hash, expected.as_ref());
    }

    #[test]
    fn test_channel_binding_hash_sha384_with_rsa() {
        use aws_lc_rs::digest;
        let cert = cert_with_rsa_oid(0x0c); // sha384WithRSAEncryption
        let hash = compute_tls_server_end_point_hash(&cert).unwrap();
        let expected = digest::digest(&digest::SHA384, &cert);
        assert_eq!(hash, expected.as_ref());
    }

    #[test]
    fn test_channel_binding_hash_sha512_with_rsa() {
        use aws_lc_rs::digest;
        let cert = cert_with_rsa_oid(0x0d); // sha512WithRSAEncryption
        let hash = compute_tls_server_end_point_hash(&cert).unwrap();
        let expected = digest::digest(&digest::SHA512, &cert);
        assert_eq!(hash, expected.as_ref());
    }

    #[test]
    fn test_channel_binding_hash_md5_falls_back_to_sha256() {
        use aws_lc_rs::digest;
        let cert = cert_with_rsa_oid(0x04); // md5WithRSAEncryption
        let hash = compute_tls_server_end_point_hash(&cert).unwrap();
        // RFC 5929: MD5 → use SHA-256
        let expected = digest::digest(&digest::SHA256, &cert);
        assert_eq!(hash, expected.as_ref());
    }

    #[test]
    fn test_channel_binding_hash_sha1_falls_back_to_sha256() {
        use aws_lc_rs::digest;
        let cert = cert_with_rsa_oid(0x05); // sha1WithRSAEncryption
        let hash = compute_tls_server_end_point_hash(&cert).unwrap();
        // RFC 5929: SHA-1 → use SHA-256
        let expected = digest::digest(&digest::SHA256, &cert);
        assert_eq!(hash, expected.as_ref());
    }

    #[test]
    fn test_channel_binding_hash_ecdsa_sha256() {
        use aws_lc_rs::digest;
        let cert = cert_with_ecdsa_oid(0x02); // ecdsa-with-SHA256
        let hash = compute_tls_server_end_point_hash(&cert).unwrap();
        let expected = digest::digest(&digest::SHA256, &cert);
        assert_eq!(hash, expected.as_ref());
    }

    #[test]
    fn test_channel_binding_hash_ecdsa_sha384() {
        use aws_lc_rs::digest;
        let cert = cert_with_ecdsa_oid(0x03); // ecdsa-with-SHA384
        let hash = compute_tls_server_end_point_hash(&cert).unwrap();
        let expected = digest::digest(&digest::SHA384, &cert);
        assert_eq!(hash, expected.as_ref());
    }

    #[test]
    fn test_channel_binding_hash_ecdsa_sha512() {
        use aws_lc_rs::digest;
        let cert = cert_with_ecdsa_oid(0x04); // ecdsa-with-SHA512
        let hash = compute_tls_server_end_point_hash(&cert).unwrap();
        let expected = digest::digest(&digest::SHA512, &cert);
        assert_eq!(hash, expected.as_ref());
    }

    #[test]
    fn test_channel_binding_hash_unknown_oid_defaults_sha256() {
        use aws_lc_rs::digest;
        // No known OID present → should default to SHA-256
        let cert = vec![0x30, 0x82, 0x00, 0x10, 0xAA, 0xBB, 0xCC, 0xDD];
        let hash = compute_tls_server_end_point_hash(&cert).unwrap();
        let expected = digest::digest(&digest::SHA256, &cert);
        assert_eq!(hash, expected.as_ref());
    }

    #[test]
    fn test_channel_binding_hash_unknown_rsa_suffix_defaults_sha256() {
        use aws_lc_rs::digest;
        let cert = cert_with_rsa_oid(0xFF); // unknown RSA suffix
        let hash = compute_tls_server_end_point_hash(&cert).unwrap();
        let expected = digest::digest(&digest::SHA256, &cert);
        assert_eq!(hash, expected.as_ref());
    }

    // === Transport::tls_server_end_point on plain connection ===

    #[test]
    fn test_transport_plain_returns_none_for_tls_endpoint() {
        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
        let addr = listener.local_addr().unwrap();
        let std_tcp = std::net::TcpStream::connect(addr).unwrap();
        std_tcp.set_nonblocking(true).unwrap();
        let _peer = listener.accept().unwrap();

        let tcp = match tokio::runtime::Handle::try_current() {
            Ok(_) => tokio::net::TcpStream::from_std(std_tcp).unwrap(),
            Err(_) => {
                let rt = tokio::runtime::Builder::new_current_thread()
                    .enable_io()
                    .build()
                    .unwrap();
                let _guard = rt.enter();
                tokio::net::TcpStream::from_std(std_tcp).unwrap()
            }
        };

        let transport = Transport::Plain(tcp);
        assert!(transport.tls_server_end_point().is_none());
    }
}