postgres_rustls 0.1.6

TLS support for tokio-postgres via tokio-rustls.
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
//! [![git]](https://git.philomathiclife.com/postgres_rustls/log.html) [![crates-io]](https://crates.io/crates/postgres_rustls) [![docs-rs]](crate)
//!
//! [git]: https://git.philomathiclife.com/git_badge.svg
//! [crates-io]: https://img.shields.io/badge/crates.io-fc8d62?style=for-the-badge&labelColor=555555&logo=rust
//! [docs-rs]: https://img.shields.io/badge/docs.rs-66c2a5?style=for-the-badge&labelColor=555555&logo=docs.rs
//!
//! `postgres_rustls` is a library that adds TLS support to [`tokio_postgres`] using [`tokio_rustls`].
#![cfg_attr(docsrs, feature(doc_cfg))]
#![expect(
    clippy::multiple_crate_versions,
    reason = "dependencies haven't updated to newest crates"
)]
#![expect(
    clippy::doc_paragraphs_missing_punctuation,
    reason = "false positive for crate documentation having image links"
)]
#![cfg_attr(test, expect(dead_code_pub_in_binary, reason = "ignore for tests"))]
use core::{
    pin::Pin,
    task::{Context, Poll},
};
use sha2::{
    Sha224, Sha256, Sha384, Sha512,
    digest::{Digest as _, OutputSizeUser, array::Array},
};
use std::io::{self, IoSlice};
pub use tokio;
use tokio::io::{AsyncRead, AsyncWrite, ReadBuf};
pub use tokio_postgres;
#[cfg(feature = "runtime")]
use tokio_postgres::tls::MakeTlsConnect;
use tokio_postgres::tls::{ChannelBinding, TlsConnect as PgTlsConnect, TlsStream as PgTlsStream};
pub use tokio_rustls;
use tokio_rustls::{
    Connect,
    client::TlsStream as RustlsStream,
    rustls::{
        ClientConfig,
        pki_types::{InvalidDnsNameError, ServerName},
    },
};
/// Unit tests.
#[cfg(test)]
mod tests;
/// Hash for the leaf certificate provided by the PostgreSQL server.
#[expect(clippy::doc_markdown, reason = "PostgreSQL is correct")]
enum Hash {
    /// SHA-256 hash.
    Sha256(Array<u8, <Sha256 as OutputSizeUser>::OutputSize>),
    /// SHA-384 hash.
    Sha384(Array<u8, <Sha384 as OutputSizeUser>::OutputSize>),
    /// SHA-512 hash.
    Sha512(Array<u8, <Sha512 as OutputSizeUser>::OutputSize>),
    /// SHA-224 hash.
    Sha224(Array<u8, <Sha224 as OutputSizeUser>::OutputSize>),
}
impl From<Hash> for Vec<u8> {
    #[inline]
    fn from(value: Hash) -> Self {
        match value {
            Hash::Sha256(hash) => hash.to_vec(),
            Hash::Sha384(hash) => hash.to_vec(),
            Hash::Sha512(hash) => hash.to_vec(),
            Hash::Sha224(hash) => hash.to_vec(),
        }
    }
}
impl Hash {
    /// Parses `cert` as a DER-encoded X.509 v3 certifcate extracting the signature algorithm and using it to hash
    /// `cert` (based on the underlying hash algorithm of the signature algorithm).
    ///
    /// Note this will return `Some` for certain invalid payloads; however when the payload is a valid
    /// DER-encoded X.509 v3 certificate, then it is guaranteed to produce the correct hash. The idea is that
    /// in the event the leaf certificate is invalid, then it will be rejected by `rustls` anyway thus what
    /// this returns won't matter. We do this for simplicity and performance reasons since it allows us to
    /// avoid parsing the entire certificate and instead _only_ care about the signature algorithm.
    ///
    /// The only signature algorithms supported are the following:
    ///
    /// * id-Ed25519
    /// * ecdsa-with-SHA256
    /// * sha256WithRSAEncryption
    /// * ecdsa-with-SHA384
    /// * sha384WithRSAEncryption
    /// * ecdsa-with-SHA512
    /// * sha512WithRSAEncryption
    /// * ecdsa-with-SHA224
    /// * sha224WithRSAEncryption
    /// * dsa-with-SHA256
    /// * dsa-with-SHA224
    /// * dsa-with-SHA1
    /// * sha1WithRSAEncryption
    ///
    /// More may be added; but for ones that require additional dependencies, they will be hidden behind a feature.
    /// Additionally new ones must be supported by PostgreSQL, `tokio-postgres`, and `rustls`.
    //
    // [RFC 5280 § 4.1](https://www.rfc-editor.org/rfc/rfc5280#section-4.1) describes the ASN.1 format
    // of an X.509 v3 Certificate:
    //
    // ```asn
    // Certificate  ::=  SEQUENCE  {
    //   tbsCertificate       TBSCertificate,
    //   signatureAlgorithm   AlgorithmIdentifier,
    //   signatureValue       BIT STRING  }
    //
    // TBSCertificate  ::=  SEQUENCE  { … }
    //
    // AlgorithmIdentifier  ::=  SEQUENCE  {
    //   algorithm               OBJECT IDENTIFIER,
    //   parameters              ANY DEFINED BY algorithm OPTIONAL  }
    // ```
    //
    // [ITU-T X.690](https://www.itu.int/rec/T-REC-X.690-202102-I/en)
    // describes how DER-encoding works.
    #[expect(
        clippy::arithmetic_side_effects,
        clippy::big_endian_bytes,
        clippy::indexing_slicing,
        reason = "comments justify their correctness"
    )]
    #[expect(clippy::too_many_lines, reason = "inflated by the const slices")]
    #[expect(clippy::doc_markdown, reason = "PostgreSQL is correct")]
    fn from_der_cert(cert: &[u8]) -> Option<Self> {
        /// [RFC 8410 § 9](https://www.rfc-editor.org/rfc/rfc8410#section-9)
        /// defines id-Ed25519 as 1.3.101.112. This is encoded as below per X.690 § 8.19.
        const ED25519: &[u8] = [43, 101, 112].as_slice();
        /// [RFC 5912 § 6](https://www.rfc-editor.org/rfc/rfc5912.html#section-6)
        /// defines ecdsa-with-SHA256 as 1.2.840.10045.4.3.2. This is encoded as
        /// below per X.690 § 8.19.
        const ECDSA_SHA256: &[u8] = [42, 134, 72, 206, 61, 4, 3, 2].as_slice();
        /// [RFC 8017 § Appendix C](https://www.rfc-editor.org/rfc/rfc8017#appendix-C)
        /// defines sha256WithRSAEncryption as 1.2.840.113549.1.1.11. This is encoded as
        /// below per X.690 § 8.19.
        const RSA_SHA256: &[u8] = [42, 134, 72, 134, 247, 13, 1, 1, 11].as_slice();
        /// [RFC 5912 § 6](https://www.rfc-editor.org/rfc/rfc5912.html#section-6)
        /// defines dsa-with-SHA256 as 2.16.840.1.101.3.4.3.2. This is encoded as
        /// below per X.690 § 8.19.
        const DSA_SHA256: &[u8] = [96, 134, 72, 1, 101, 3, 4, 3, 2].as_slice();
        /// [RFC 5912 § 6](https://www.rfc-editor.org/rfc/rfc5912.html#section-6)
        /// defines dsa-with-SHA1 as 1.2.840.10040.4.3. This is encoded as
        /// below per X.690 § 8.19.
        const DSA_SHA1: &[u8] = [42, 134, 72, 206, 56, 4, 3].as_slice();
        /// [RFC 8017 § Appendix C](https://www.rfc-editor.org/rfc/rfc8017#appendix-C)
        /// defines sha1WithRSAEncryption as 1.2.840.113549.1.1.5. This is encoded as
        /// below per X.690 § 8.19.
        const RSA_SHA1: &[u8] = [42, 134, 72, 134, 247, 13, 1, 1, 5].as_slice();
        /// [RFC 5912 § 6](https://www.rfc-editor.org/rfc/rfc5912.html#section-6)
        /// defines ecdsa-with-SHA384 as 1.2.840.10045.4.3.3. This is encoded as
        /// below per X.690 § 8.19.
        const ECDSA_SHA384: &[u8] = [42, 134, 72, 206, 61, 4, 3, 3].as_slice();
        /// [RFC 8017 § Appendix C](https://www.rfc-editor.org/rfc/rfc8017#appendix-C)
        /// defines sha384WithRSAEncryption as 1.2.840.113549.1.1.12. This is encoded as
        /// below per X.690 § 8.19.
        const RSA_SHA384: &[u8] = [42, 134, 72, 134, 247, 13, 1, 1, 12].as_slice();
        /// [RFC 5912 § 6](https://www.rfc-editor.org/rfc/rfc5912.html#section-6)
        /// defines ecdsa-with-SHA512 as 1.2.840.10045.4.3.4. This is encoded as
        /// below per X.690 § 8.19.
        const ECDSA_SHA512: &[u8] = [42, 134, 72, 206, 61, 4, 3, 4].as_slice();
        /// [RFC 8017 § Appendix C](https://www.rfc-editor.org/rfc/rfc8017#appendix-C)
        /// defines sha512WithRSAEncryption as 1.2.840.113549.1.1.13. This is encoded as
        /// below per X.690 § 8.19.
        const RSA_SHA512: &[u8] = [42, 134, 72, 134, 247, 13, 1, 1, 13].as_slice();
        /// [RFC 5912 § 6](https://www.rfc-editor.org/rfc/rfc5912.html#section-6)
        /// defines ecdsa-with-SHA224 as 1.2.840.10045.4.3.1. This is encoded as
        /// below per X.690 § 8.19.
        const ECDSA_SHA224: &[u8] = [42, 134, 72, 206, 61, 4, 3, 1].as_slice();
        /// [RFC 8017 § Appendix C](https://www.rfc-editor.org/rfc/rfc8017#appendix-C)
        /// defines sha224WithRSAEncryption as 1.2.840.113549.1.1.14. This is encoded as
        /// below per X.690 § 8.19.
        const RSA_SHA224: &[u8] = [42, 134, 72, 134, 247, 13, 1, 1, 14].as_slice();
        /// [RFC 5912 § 6](https://www.rfc-editor.org/rfc/rfc5912.html#section-6)
        /// defines dsa-with-SHA224 as 2.16.840.1.101.3.4.3.1. This is encoded as
        /// below per X.690 § 8.19.
        const DSA_SHA224: &[u8] = [96, 134, 72, 1, 101, 3, 4, 3, 1].as_slice();
        // The first octet represents a constructed sequence (i.e., 0x30) and the second octet represents
        // the (possibly encoded) length of the remaining payload.
        cert.split_at_checked(2).and_then(|(cert_seq, cert_rem)| {
            // This won't `panic` since `cert_seq.len() == 2`.
            // This represents the (possibly encoded) length.
            //
            // We don't care about the actual length of the payload. We only care about the number of bytes
            // we need to skip until the (possibly encoded) length of the constructed sequence of
            // tbsCertificate.
            match cert_seq[1] {
                // The length of the payload is represented with this byte; thus we only need to skip
                // the constructed sequence byte (i.e., 0x30) of tbsCertificate.
                ..=127 => Some(1),
                // The length of the payload is invalid since DER-encoded lengths must use the minimum
                // number of bytes possible. The high bit is set iff one or more octets are needed to encode
                // the actual length. The number of octets is represented by the remaining bits; thus this
                // means there are 0 bytes to encode the length, but then it should have been encoded as
                // `0` and not `128`.
                //
                // 255 is not allowed to be used per § 8.1.3.5.
                128 | 255 => None,
                // The remaining bits represent the number of bytes that it takes to encode the length;
                // thus we subtract 128 and add 1 to account for the constructed sequence byte (i.e., 0x30)
                // of tbsCertificate. This is the same as just subtracting 127.
                //
                // Underflow clearly cannot occur since `len` is at least 129.
                len @ 129.. => Some(usize::from(len) - 127),
            }
            .and_then(|skip| {
                cert_rem.get(skip..).and_then(|tbs_rem_with_len| {
                    // Remaining payload starting from the (possibly encoded) length of tbsCertificate.
                    tbs_rem_with_len
                        // Extract the (possibly encoded) length of tbsCertificate.
                        .split_first()
                        .and_then(|(tbs_enc_len, tbs_rem)| {
                            // We need to extract how many bytes make up tbsCertificate that way
                            // we can skip it and get to the (possibly encoded) length of
                            // signatureAlgorithm.
                            match *tbs_enc_len {
                                // tbsCertificate is encoded in `len` bytes. We need to skip that many
                                // bytes taking into account the constructed sequence byte (i.e., 0x30)
                                // of signatureAlgorithm.
                                //
                                // This won't overflow since `len` is at most 127; thus this maxes at 128
                                // which is <= `usize::MAX`.
                                len @ ..=127 => Some(usize::from(len) + 1),
                                // The number of bytes tbsCertificate is encoded in takes 1 byte to encode
                                // We get that one byte since that is how many bytes we need to skip taking
                                // into account the byte and the constructed sequence byte (i.e., 0x30) of
                                // signatureAlgorithm.
                                //
                                // This won't overflow since this maxes at 255 + 2 = 257 <= usize::MAX.
                                129 => tbs_rem.first().map(|len| usize::from(*len) + 2),
                                // The number of bytes tbsCertificate is encoded in takes 2 bytes to encode.
                                // We get the two bytes since that is how many bytes we need to skip.
                                130 => tbs_rem.get(..2).and_then(|enc_len| {
                                    let mut big_endian_len = [0; 2];
                                    // This won't `panic` since `enc_len.len() == 2`.
                                    big_endian_len.copy_from_slice(enc_len);
                                    // Multi-byte lengths are encoded in big-endian.
                                    u16::from_be_bytes(big_endian_len)
                                        // We need to account for the two bytes and the constructed sequence byte
                                        // (i.e., 0x30) of signatureAlgorithm.
                                        .checked_add(3)
                                        // We don't support payloads larger than 65,535 since that is more than
                                        // enough for a single certificate.
                                        .map(usize::from)
                                }),
                                // We arbitrarily cap the size of payloads we accept to simplify decoding.
                                // If this is more than 130, then the payload is at least 16,777,216 bytes
                                // which is obscenely large for a single certificate. 128 is invalid.
                                _ => None,
                            }
                            .and_then(|tbs_len| {
                                tbs_rem.get(tbs_len..).and_then(|alg_rem_with_len| {
                                    // Remaining payload starting from the (possibly encoded) length of
                                    // signatureAlgorithm.
                                    alg_rem_with_len
                                        // Extract the (possibly encoded) length of signatureAlgorithm.
                                        .split_first()
                                        .and_then(|(alg_enc_len, alg_rem)| {
                                            // We need to extract how many bytes make up signatureAlgorithm that way
                                            // we can skip it and get to the (possibly encoded) length of algorithm.
                                            match *alg_enc_len {
                                                // The length of the payload is represented with this byte; thus we
                                                // only need to skip the object identifier byte (i.e., 0x06) of
                                                // algorithm.
                                                ..=127 => Some(1),
                                                // The length of the payload is invalid.
                                                128 | 255 => None,
                                                // The remaining bits represents the number of bytes that it takes to
                                                // encode the length; thus we subtract 128 and add 1 to account for
                                                // the object identifier byte (i.e., 0x06) of algorithm.
                                                // This is the same as just subtracting 127.
                                                //
                                                // Underflow clearly cannot occur since `len` is at least 129.
                                                len @ 129.. => Some(usize::from(len) - 127),
                                            }
                                            .and_then(
                                                |alg_skip| {
                                                    alg_rem.get(alg_skip..).and_then(|oid_rem| {
                                                        // Remaining payload starting from the (possibly encoded)
                                                        // length of algorithm, and we extract the
                                                        // (possibly encoded) length of algorithm.
                                                        oid_rem.split_first().and_then(
                                                            |(oid_enc_len, rem)| {
                                                                // Extract the algorithm.
                                                                // Recall we don't care if the certificate is
                                                                // invalid, and we only support algorithms of
                                                                // length at most 127. As a result, we treat
                                                                // `oid_enc_len` as is.
                                                                rem.get(..usize::from(*oid_enc_len))
                                                                    .and_then(|oid| match oid {
                                                                        ED25519 | ECDSA_SHA256
                                                                        | RSA_SHA256 | DSA_SHA256
                                                                        // [RFC 5929 § 4.1](https://www.rfc-editor.org/rfc/rfc5929#section-4.1)
                                                                        // mandates that SHA-1 based signatures
                                                                        // use SHA-256.
                                                                        | DSA_SHA1 | RSA_SHA1 => {
                                                                            Some(Self::Sha256(
                                                                                Sha256::digest(
                                                                                    cert,
                                                                                ),
                                                                            ))
                                                                        }
                                                                        ECDSA_SHA384
                                                                        | RSA_SHA384 => {
                                                                            Some(Self::Sha384(
                                                                                Sha384::digest(
                                                                                    cert,
                                                                                ),
                                                                            ))
                                                                        }
                                                                        ECDSA_SHA512
                                                                        | RSA_SHA512 => {
                                                                            Some(Self::Sha512(
                                                                                Sha512::digest(
                                                                                    cert,
                                                                                ),
                                                                            ))
                                                                        }
                                                                        ECDSA_SHA224
                                                                        | RSA_SHA224
                                                                        | DSA_SHA224 => {
                                                                            Some(Self::Sha224(
                                                                                Sha224::digest(
                                                                                    cert,
                                                                                ),
                                                                            ))
                                                                        }
                                                                        _ => None,
                                                                    })
                                                            },
                                                        )
                                                    })
                                                },
                                            )
                                        })
                                })
                            })
                        })
                })
            })
        })
    }
}
/// The [`TlsConnector::Stream`] returned from [`TlsConnectorFuture::poll`].
#[derive(Debug)]
pub struct TlsStream<S>(RustlsStream<S>);
impl<S: AsyncRead + AsyncWrite + Unpin> AsyncRead for TlsStream<S> {
    #[inline]
    fn poll_read(
        mut self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buf: &mut ReadBuf<'_>,
    ) -> Poll<io::Result<()>> {
        Pin::new(&mut self.0).poll_read(cx, buf)
    }
}
impl<S: AsyncRead + AsyncWrite + Unpin> AsyncWrite for TlsStream<S> {
    #[inline]
    fn poll_write(
        mut self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buf: &[u8],
    ) -> Poll<Result<usize, io::Error>> {
        Pin::new(&mut self.0).poll_write(cx, buf)
    }
    #[inline]
    fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), io::Error>> {
        Pin::new(&mut self.0).poll_flush(cx)
    }
    #[inline]
    fn poll_shutdown(
        mut self: Pin<&mut Self>,
        cx: &mut Context<'_>,
    ) -> Poll<Result<(), io::Error>> {
        Pin::new(&mut self.0).poll_shutdown(cx)
    }
    #[inline]
    fn poll_write_vectored(
        mut self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        bufs: &[IoSlice<'_>],
    ) -> Poll<Result<usize, io::Error>> {
        Pin::new(&mut self.0).poll_write_vectored(cx, bufs)
    }
    #[inline]
    fn is_write_vectored(&self) -> bool {
        self.0.is_write_vectored()
    }
}
impl<S: AsyncRead + AsyncWrite + Unpin> PgTlsStream for TlsStream<S> {
    /// Returns the [`ChannelBinding`] based on the X.509 v3 certificate sent from the PostgreSQL server.
    ///
    /// Note when this returns [`ChannelBinding::tls_server_end_point`], it _does not_ mean the certificate
    /// is valid. In certain circumstances, this will return that even for an invalid certificate. This should
    /// not matter since the certificate being invalid will cause the certificate to be rejected anyway. When
    /// the certificate is valid and uses a supported signature algorithm, then this will always return the
    /// correct value.
    ///
    /// The only supported signature algorithms are the following:
    ///
    /// * id-Ed25519
    /// * ecdsa-with-SHA256
    /// * sha256WithRSAEncryption
    /// * ecdsa-with-SHA384
    /// * sha384WithRSAEncryption
    /// * ecdsa-with-SHA512
    /// * sha512WithRSAEncryption
    /// * ecdsa-with-SHA224
    /// * sha224WithRSAEncryption
    /// * dsa-with-SHA256
    /// * dsa-with-SHA224
    /// * dsa-with-SHA1
    /// * sha1WithRSAEncryption
    ///
    /// Note it is strongly recommended that TLS 1.3 be used; thus while signature algorithms that are not
    /// part of TLS 1.3 are supported, you should avoid them.
    /// See [RFC 9266 § 4.2](https://www.rfc-editor.org/rfc/rfc9266#section-4.2).
    /// Additionally some of the supported signature algorithms may not be supported by PostgreSQL
    /// (e.g., id-Ed25519).
    #[expect(clippy::doc_markdown, reason = "PostgreSQL is correct")]
    #[inline]
    fn channel_binding(&self) -> ChannelBinding {
        self.0
            .get_ref()
            .1
            .peer_certificates()
            .and_then(|certs| {
                certs.first().and_then(|fst| {
                    Hash::from_der_cert(fst)
                        .map(|hash| ChannelBinding::tls_server_end_point(hash.into()))
                })
            })
            .unwrap_or_else(ChannelBinding::none)
    }
}
/// [`TlsConnector::Future`] returned from [`TlsConnector::connect`].
#[expect(
    missing_debug_implementations,
    reason = "Connect does not implement Debug, so we don't"
)]
pub struct TlsConnectorFuture<S>(Connect<S>);
impl<S: AsyncRead + AsyncWrite + Unpin> Future for TlsConnectorFuture<S> {
    type Output = io::Result<TlsStream<S>>;
    #[inline]
    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        Pin::new(&mut self.0).poll(cx).map_ok(TlsStream)
    }
}
/// Connects to the PostgreSQL server.
#[expect(
    missing_debug_implementations,
    reason = "TlsConnector does not implement Debug, so we don't"
)]
#[expect(clippy::doc_markdown, reason = "PostgreSQL is correct")]
pub struct TlsConnector<'domain> {
    /// Used to connect to the PostgreSQL server.
    #[expect(clippy::doc_markdown, reason = "PostgreSQL is correct")]
    connector: tokio_rustls::TlsConnector,
    /// The domain or IP of the PostgreSQL server.
    #[expect(clippy::doc_markdown, reason = "PostgreSQL is correct")]
    dom: ServerName<'domain>,
}
impl<'domain> TlsConnector<'domain> {
    /// Returns `Self` based on `connector` and `domain`.
    ///
    /// # Errors
    ///
    /// Errors iff [`ServerName::try_from`] does when passed `domain`.
    #[expect(single_use_lifetimes, reason = "false positive")]
    #[inline]
    pub fn new<'dom: 'domain>(
        connector: tokio_rustls::TlsConnector,
        domain: &'dom str,
    ) -> Result<Self, InvalidDnsNameError> {
        ServerName::try_from(domain).map(|dom| Self { connector, dom })
    }
}
impl<S: AsyncRead + AsyncWrite + Unpin> PgTlsConnect<S> for TlsConnector<'static> {
    type Stream = TlsStream<S>;
    type Error = io::Error;
    type Future = TlsConnectorFuture<S>;
    #[inline]
    fn connect(self, stream: S) -> Self::Future {
        TlsConnectorFuture(self.connector.connect(self.dom, stream))
    }
}
/// [`MakeTlsConnect`] based on [`tokio_rustls::TlsConnector`].
#[expect(
    missing_debug_implementations,
    reason = "TlsConnector does not implement Debug, so we don't"
)]
#[cfg(feature = "runtime")]
#[derive(Clone)]
pub struct MakeTlsConnector(tokio_rustls::TlsConnector);
#[cfg(feature = "runtime")]
impl MakeTlsConnector {
    /// Constructs `Self` based on `connector`.
    #[inline]
    #[must_use]
    pub const fn new(connector: tokio_rustls::TlsConnector) -> Self {
        Self(connector)
    }
}
#[cfg(feature = "runtime")]
impl<S: AsyncRead + AsyncWrite + Unpin> MakeTlsConnect<S> for MakeTlsConnector {
    type Stream = TlsStream<S>;
    type TlsConnect = TlsConnector<'static>;
    type Error = InvalidDnsNameError;
    #[inline]
    fn make_tls_connect(&mut self, domain: &str) -> Result<Self::TlsConnect, Self::Error> {
        ServerName::try_from(domain).map(|dom| TlsConnector {
            connector: self.0.clone(),
            dom: dom.to_owned(),
        })
    }
}
/// Removes any ALPN values and adds the `b"postgresql"` ALPN.
#[inline]
pub fn set_postgresql_alpn(config: &mut ClientConfig) {
    config.alpn_protocols.clear();
    config.alpn_protocols.push(vec![
        b'p', b'o', b's', b't', b'g', b'r', b'e', b's', b'q', b'l',
    ]);
}