Skip to main content

sqlx_core/net/tls/
mod.rs

1#![allow(dead_code)]
2
3use std::path::PathBuf;
4
5use crate::error::Error;
6use crate::net::socket::WithSocket;
7use crate::net::Socket;
8
9#[cfg(feature = "_tls-rustls")]
10mod tls_rustls;
11
12#[cfg(feature = "_tls-native-tls")]
13mod tls_native_tls;
14
15mod util;
16
17/// X.509 Certificate input, either a file path or a PEM encoded inline certificate(s).
18#[derive(Clone, Debug)]
19pub enum CertificateInput {
20    /// PEM encoded certificate(s)
21    Inline(Vec<u8>),
22    /// Path to a file containing PEM encoded certificate(s)
23    File(PathBuf),
24}
25
26impl From<String> for CertificateInput {
27    fn from(value: String) -> Self {
28        // Leading and trailing whitespace/newlines
29        let trimmed = value.trim();
30
31        // Heuristic for PEM encoded inputs:
32        // https://tools.ietf.org/html/rfc7468
33        if trimmed.starts_with("-----BEGIN") && trimmed.ends_with("-----") {
34            CertificateInput::Inline(value.as_bytes().to_vec())
35        } else {
36            CertificateInput::File(PathBuf::from(value))
37        }
38    }
39}
40
41impl CertificateInput {
42    async fn data(&self) -> Result<Vec<u8>, std::io::Error> {
43        use crate::fs;
44        match self {
45            CertificateInput::Inline(v) => Ok(v.clone()),
46            CertificateInput::File(path) => fs::read(path).await,
47        }
48    }
49}
50
51impl std::fmt::Display for CertificateInput {
52    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
53        match self {
54            CertificateInput::Inline(v) => write!(f, "{}", String::from_utf8_lossy(v.as_slice())),
55            CertificateInput::File(path) => write!(f, "file: {}", path.display()),
56        }
57    }
58}
59
60pub struct TlsConfig<'a> {
61    pub accept_invalid_certs: bool,
62    pub accept_invalid_hostnames: bool,
63    pub root_cert_path: Option<&'a CertificateInput>,
64    pub client_cert_path: Option<&'a CertificateInput>,
65    pub client_key_path: Option<&'a CertificateInput>,
66}
67
68#[cfg(feature = "_tls-native-tls")]
69pub use self::tls_native_tls::NativeTlsConnector as TlsConnector;
70#[cfg(all(feature = "_tls-rustls", not(feature = "_tls-native-tls")))]
71pub use self::tls_rustls::RustlsConnector as TlsConnector;
72#[cfg(not(any(feature = "_tls-native-tls", feature = "_tls-rustls")))]
73#[derive(Debug, Clone)]
74pub struct TlsConnector(std::convert::Infallible);
75
76pub async fn connector(config: TlsConfig<'_>) -> crate::Result<TlsConnector> {
77    #[cfg(feature = "_tls-native-tls")]
78    return tls_native_tls::connector(config).await;
79
80    #[cfg(all(feature = "_tls-rustls", not(feature = "_tls-native-tls")))]
81    return tls_rustls::connector(config).await;
82
83    #[cfg(not(any(feature = "_tls-native-tls", feature = "_tls-rustls")))]
84    {
85        _ = config;
86        panic!("one of the `runtime-*-native-tls` or `runtime-*-rustls` features must be enabled")
87    }
88}
89
90pub async fn handshake<S, Ws>(
91    socket: S,
92    hostname: &str,
93    connector: &TlsConnector,
94    with_socket: Ws,
95) -> crate::Result<Ws::Output>
96where
97    S: Socket,
98    Ws: WithSocket,
99{
100    #[cfg(feature = "_tls-native-tls")]
101    return Ok(with_socket
102        .with_socket(tls_native_tls::handshake(socket, hostname, connector).await?)
103        .await);
104
105    #[cfg(all(feature = "_tls-rustls", not(feature = "_tls-native-tls")))]
106    return Ok(with_socket
107        .with_socket(tls_rustls::handshake(socket, hostname, connector).await?)
108        .await);
109
110    #[cfg(not(any(feature = "_tls-native-tls", feature = "_tls-rustls")))]
111    {
112        drop((socket, hostname, with_socket));
113        match connector.0 {}
114    }
115}
116
117pub fn available() -> bool {
118    cfg!(any(feature = "_tls-native-tls", feature = "_tls-rustls"))
119}
120
121pub fn error_if_unavailable() -> crate::Result<()> {
122    if !available() {
123        return Err(Error::tls(
124            "TLS upgrade required by connect options \
125                    but SQLx was built without TLS support enabled",
126        ));
127    }
128
129    Ok(())
130}