Skip to main content

mz_mysql_util/
tunnel.rs

1// Copyright Materialize, Inc. and contributors. All rights reserved.
2//
3// Use of this software is governed by the Business Source License
4// included in the LICENSE file.
5//
6// As of the Change Date specified in that file, in accordance with
7// the Business Source License, use of this software will be governed
8// by the Apache License, Version 2.0.
9
10use mysql_async::{Conn, Opts, OptsBuilder};
11use std::collections::BTreeSet;
12use std::future::Future;
13use std::net::IpAddr;
14use std::ops::{Deref, DerefMut};
15use std::panic::AssertUnwindSafe;
16use std::pin::Pin;
17use std::time::Duration;
18
19use mz_aws_util::rds::RdsIamAuth;
20use mz_ore::future::{InTask, OreFutureExt, TimeoutError};
21use mz_ore::option::OptionExt;
22use mz_ore::task::spawn;
23use mz_repr::CatalogItemId;
24use mz_ssh_util::tunnel::{SshTimeoutConfig, SshTunnelConfig};
25use mz_ssh_util::tunnel_manager::{ManagedSshTunnelHandle, SshTunnelManager};
26use serde::{Deserialize, Serialize};
27use tracing::{error, info, warn};
28
29use crate::MySqlError;
30
31/// Configures an optional tunnel for use when connecting to a MySQL
32/// database.
33#[derive(Debug, PartialEq, Clone)]
34pub enum TunnelConfig {
35    /// Establish a direct TCP connection to the database host.
36    /// If `resolved_ips` is not None, the provided IPs will be used
37    /// rather than resolving the hostname.
38    Direct {
39        resolved_ips: Option<BTreeSet<IpAddr>>,
40    },
41    /// Establish a TCP connection to the database via an SSH tunnel.
42    /// This means first establishing an SSH connection to a bastion host,
43    /// and then opening a separate connection from that host to the database.
44    /// This is commonly referred by vendors as a "direct SSH tunnel", in
45    /// opposition to "reverse SSH tunnel", which is currently unsupported.
46    Ssh { config: SshTunnelConfig },
47    /// Establish a TCP connection to the database via an AWS PrivateLink
48    /// service.
49    AwsPrivatelink {
50        /// The ID of the AWS PrivateLink service.
51        connection_id: CatalogItemId,
52    },
53}
54
55pub const DEFAULT_TCP_KEEPALIVE: Duration = Duration::from_secs(60);
56pub const DEFAULT_SNAPSHOT_MAX_EXECUTION_TIME: Duration = Duration::ZERO;
57pub const DEFAULT_SNAPSHOT_LOCK_WAIT_TIMEOUT: Duration = Duration::from_secs(3600);
58/// The `wait_timeout` to set on connections used during snapshotting, chosen
59/// to comfortably outlast even very long-running snapshots.
60pub const DEFAULT_SNAPSHOT_WAIT_TIMEOUT: Duration = Duration::from_secs(48 * 60 * 60);
61/// The minimum value MySQL accepts for `wait_timeout`.
62pub const MIN_SNAPSHOT_WAIT_TIMEOUT: Duration = Duration::from_secs(1);
63/// The maximum value MySQL accepts for `wait_timeout` on Windows, which is
64/// lower than the Unix maximum and so the portable upper bound.
65pub const MAX_SNAPSHOT_WAIT_TIMEOUT: Duration = Duration::from_secs(2147483);
66pub const DEFAULT_CONNECT_TIMEOUT: Duration = Duration::from_secs(60);
67
68#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
69pub struct TimeoutConfig {
70    // Snapshot-related configs
71    pub snapshot_max_execution_time: Option<Duration>,
72    pub snapshot_lock_wait_timeout: Option<Duration>,
73    pub snapshot_wait_timeout: Option<Duration>,
74
75    // Socket-related configs
76    pub tcp_keepalive: Option<Duration>,
77
78    // Connection timeout.  This timeout covers creating an authenticated connection
79    // (e.g. includes network connection, TLS handshake, authentication, etc.).
80    // If the connection has not been established in that time, it is considered an error.
81    pub connect_timeout: Option<Duration>,
82    // There are other timeout options on `mysql_async::OptsBuilder`
83    // (e.g. `conn_ttl` and `wait_timeout`) that could be exposed
84    // but they only apply to connection pools, which we are not currently using.
85}
86
87impl Default for TimeoutConfig {
88    fn default() -> Self {
89        Self {
90            snapshot_max_execution_time: Some(DEFAULT_SNAPSHOT_MAX_EXECUTION_TIME),
91            snapshot_lock_wait_timeout: Some(DEFAULT_SNAPSHOT_LOCK_WAIT_TIMEOUT),
92            snapshot_wait_timeout: Some(DEFAULT_SNAPSHOT_WAIT_TIMEOUT),
93            tcp_keepalive: Some(DEFAULT_TCP_KEEPALIVE),
94            connect_timeout: Some(DEFAULT_CONNECT_TIMEOUT),
95        }
96    }
97}
98
99impl TimeoutConfig {
100    pub fn build(
101        snapshot_max_execution_time: Duration,
102        snapshot_lock_wait_timeout: Duration,
103        snapshot_wait_timeout: Duration,
104        tcp_keepalive: Duration,
105        connect_timeout: Duration,
106    ) -> Self {
107        // Verify values are within valid ranges
108        // Note we error log but do not fail as this is called in a non-fallible
109        // LD-sync in the adapter.
110
111        // https://dev.mysql.com/doc/refman/8.0/en/server-system-variables.html#sysvar_lock_wait_timeout
112        let snapshot_lock_wait_timeout = if snapshot_lock_wait_timeout.as_secs() > 31536000 {
113            error!(
114                "snapshot_lock_wait_timeout is too large: {}. Maximum is 31536000.",
115                snapshot_lock_wait_timeout.as_secs()
116            );
117            Some(DEFAULT_SNAPSHOT_LOCK_WAIT_TIMEOUT)
118        } else {
119            Some(snapshot_lock_wait_timeout)
120        };
121
122        // https://dev.mysql.com/doc/refman/8.0/en/server-system-variables.html#sysvar_wait_timeout
123        let snapshot_wait_timeout = if snapshot_wait_timeout > MAX_SNAPSHOT_WAIT_TIMEOUT
124            || snapshot_wait_timeout < MIN_SNAPSHOT_WAIT_TIMEOUT
125        {
126            error!(
127                "snapshot_wait_timeout is out of range: {}. Must be within [{}, {}].",
128                snapshot_wait_timeout.as_secs(),
129                MIN_SNAPSHOT_WAIT_TIMEOUT.as_secs(),
130                MAX_SNAPSHOT_WAIT_TIMEOUT.as_secs(),
131            );
132            Some(DEFAULT_SNAPSHOT_WAIT_TIMEOUT)
133        } else {
134            Some(snapshot_wait_timeout)
135        };
136
137        // https://dev.mysql.com/doc/refman/8.0/en/server-system-variables.html#sysvar_max_execution_time
138        let snapshot_max_execution_time = if snapshot_max_execution_time.as_millis() > 4294967295 {
139            error!(
140                "snapshot_max_execution_time is too large: {}. Maximum is 4294967295.",
141                snapshot_max_execution_time.as_secs()
142            );
143            Some(DEFAULT_SNAPSHOT_MAX_EXECUTION_TIME)
144        } else {
145            Some(snapshot_max_execution_time)
146        };
147
148        let tcp_keepalive = match u32::try_from(tcp_keepalive.as_millis()) {
149            Err(_) => {
150                error!(
151                    "tcp_keepalive is too large: {}. Maximum is {}.",
152                    tcp_keepalive.as_millis(),
153                    u32::MAX,
154                );
155                Some(DEFAULT_TCP_KEEPALIVE)
156            }
157            Ok(_) => Some(tcp_keepalive),
158        };
159
160        let connect_timeout = match u32::try_from(connect_timeout.as_millis()) {
161            Err(_) => {
162                error!(
163                    "connect_timeout is too large: {}. Maximum is {}.",
164                    connect_timeout.as_millis(),
165                    u32::MAX,
166                );
167                Some(DEFAULT_CONNECT_TIMEOUT)
168            }
169            Ok(_) => Some(connect_timeout),
170        };
171
172        Self {
173            snapshot_max_execution_time,
174            snapshot_lock_wait_timeout,
175            snapshot_wait_timeout,
176            tcp_keepalive,
177            connect_timeout,
178        }
179    }
180
181    /// Apply relevant timeout configurations to a `mysql_async::OptsBuilder`.
182    pub fn apply_to_opts(&self, mut opts_builder: OptsBuilder) -> Result<OptsBuilder, MySqlError> {
183        if let Some(tcp_keepalive) = self.tcp_keepalive {
184            opts_builder = opts_builder.tcp_keepalive(Some(tcp_keepalive));
185        }
186        Ok(opts_builder)
187    }
188}
189
190/// A MySQL connection with an optional SSH tunnel handle.
191///
192/// This wrapper is intended to be used in place of `mysql_async::Conn` to
193/// keep the SSH tunnel alive for the lifecycle of the connection by holding
194/// a reference to the tunnel handle.
195#[derive(Debug)]
196pub struct MySqlConn {
197    conn: Conn,
198    _ssh_tunnel_handle: Option<ManagedSshTunnelHandle>,
199}
200
201impl Deref for MySqlConn {
202    type Target = Conn;
203
204    fn deref(&self) -> &Self::Target {
205        &self.conn
206    }
207}
208
209impl DerefMut for MySqlConn {
210    fn deref_mut(&mut self) -> &mut Self::Target {
211        &mut self.conn
212    }
213}
214
215impl MySqlConn {
216    pub async fn disconnect(mut self) -> Result<(), MySqlError> {
217        self.conn.disconnect().await?;
218        self._ssh_tunnel_handle.take();
219        Ok(())
220    }
221
222    pub fn take(self) -> (Conn, Option<ManagedSshTunnelHandle>) {
223        (self.conn, self._ssh_tunnel_handle)
224    }
225}
226
227/// Configuration for MySQL connections.
228///
229/// This wraps [`mysql_async::Opts`] to allow the configuration of a
230/// tunnel via a [`TunnelConfig`].
231#[derive(Clone, Debug)]
232pub struct Config {
233    inner: Opts,
234    tunnel: TunnelConfig,
235    // Whether to poll I/O for this connection in a tokio task
236    // TODO(roshan): Make this apply to queries on the returned connection, not just the initial
237    // connection.
238    in_task: InTask,
239    ssh_timeout_config: SshTimeoutConfig,
240    mysql_timeout_config: TimeoutConfig,
241    iam_auth: Option<RdsIamAuth>,
242}
243
244impl Config {
245    pub fn new(
246        builder: OptsBuilder,
247        tunnel: TunnelConfig,
248        ssh_timeout_config: SshTimeoutConfig,
249        in_task: InTask,
250        mysql_timeout_config: TimeoutConfig,
251        iam_auth: Option<RdsIamAuth>,
252    ) -> Result<Self, MySqlError> {
253        let opts = mysql_timeout_config.apply_to_opts(builder)?;
254        Ok(Self {
255            inner: opts.into(),
256            tunnel,
257            in_task,
258            ssh_timeout_config,
259            mysql_timeout_config,
260            iam_auth,
261        })
262    }
263
264    pub async fn connect(
265        &self,
266        task_name: &str,
267        ssh_tunnel_manager: &SshTunnelManager,
268    ) -> Result<MySqlConn, MySqlError> {
269        let address = format!(
270            "mysql:://{}@{}:{}/{}",
271            self.inner.user().display_or("<unknown-user>"),
272            self.inner.ip_or_hostname(),
273            self.inner.tcp_port(),
274            self.inner.db_name().display_or("<unknown-dbname>"),
275        );
276        info!(%task_name, %address, "connecting");
277        match self.connect_internal(ssh_tunnel_manager).await {
278            Ok(t) => {
279                info!(%task_name, %address, "connected");
280                Ok(t)
281            }
282            Err(e) => {
283                warn!(%task_name, %address, "connection failed: {e:#}");
284                Err(e)
285            }
286        }
287    }
288
289    fn address(&self) -> (&str, u16) {
290        (self.inner.ip_or_hostname(), self.inner.tcp_port())
291    }
292
293    async fn connect_internal(
294        &self,
295        ssh_tunnel_manager: &SshTunnelManager,
296    ) -> Result<MySqlConn, MySqlError> {
297        let mut opts_builder = OptsBuilder::from_opts(self.inner.clone());
298
299        let iam_token = match &self.iam_auth {
300            None => None,
301            Some(iam_auth) => {
302                let (host, port) = self.address();
303                let username = self.inner.user().expect("MySQL: username required");
304
305                let token = iam_auth.token(host, port, username).await?;
306                // Cleartext plugin must be enabled for IAM authentication, for security,
307                // the network traffic is SSL/TLS encrypted.  The cleartext plugin is built
308                // into the MySQL client library.
309                opts_builder = opts_builder
310                    .pass(Some(token.token.unsecure()))
311                    .enable_cleartext_plugin(true);
312                Some(token)
313            }
314        };
315
316        let result = self
317            .connect_with_opts(opts_builder, ssh_tunnel_manager)
318            .await;
319        if let Err(error) = &result
320            && let Some(iam_auth) = &self.iam_auth
321            && let Some(token) = &iam_token
322            && is_authentication_failure(error)
323        {
324            iam_auth.token_rejected(token);
325        }
326        result
327    }
328
329    async fn connect_with_opts(
330        &self,
331        mut opts_builder: OptsBuilder,
332        ssh_tunnel_manager: &SshTunnelManager,
333    ) -> Result<MySqlConn, MySqlError> {
334        match &self.tunnel {
335            TunnelConfig::Direct { resolved_ips } => {
336                opts_builder = opts_builder.resolved_ips(
337                    resolved_ips
338                        .clone()
339                        .map(|ips| ips.into_iter().collect::<Vec<_>>()),
340                );
341
342                Ok(MySqlConn {
343                    conn: self.connect_with_timeout(opts_builder).await?,
344                    _ssh_tunnel_handle: None,
345                })
346            }
347            TunnelConfig::Ssh { config } => {
348                let (host, port) = self.address();
349                let tunnel = ssh_tunnel_manager
350                    .connect(
351                        config.clone(),
352                        host,
353                        port,
354                        self.ssh_timeout_config,
355                        self.in_task,
356                    )
357                    .await
358                    .map_err(MySqlError::Ssh)?;
359
360                let tunnel_addr = tunnel.local_addr();
361                // Override the connection host and port for the actual TCP connection to point to
362                // the local tunnel instead.
363                opts_builder = opts_builder
364                    .ip_or_hostname(tunnel_addr.ip().to_string())
365                    .tcp_port(tunnel_addr.port());
366
367                if let Some(ssl_opts) = self.inner.ssl_opts() {
368                    if !ssl_opts.skip_domain_validation() {
369                        // If the TLS configuration will validate the hostname, we need to set
370                        // the TLS hostname back to the actual upstream host and not the hostname
371                        // of the local SSH tunnel
372                        opts_builder = opts_builder.ssl_opts(Some(
373                            ssl_opts.clone().with_danger_tls_hostname_override(Some(
374                                self.inner.ip_or_hostname().to_string(),
375                            )),
376                        ));
377                    }
378                }
379
380                Ok(MySqlConn {
381                    conn: self.connect_with_timeout(opts_builder).await?,
382                    _ssh_tunnel_handle: Some(tunnel),
383                })
384            }
385            TunnelConfig::AwsPrivatelink { connection_id } => {
386                let privatelink_host = mz_cloud_resources::vpc_endpoint_name(*connection_id);
387
388                // Override the connection host for the actual TCP connection to point to
389                // the privatelink hostname instead.
390                let mut opts_builder = opts_builder.ip_or_hostname(privatelink_host);
391
392                if let Some(ssl_opts) = self.inner.ssl_opts() {
393                    if !ssl_opts.skip_domain_validation() {
394                        // If the TLS configuration will validate the hostname, we need to set
395                        // the TLS hostname back to the actual upstream host and not the
396                        // privatelink hostname.
397                        opts_builder = opts_builder.ssl_opts(Some(
398                            ssl_opts.clone().with_danger_tls_hostname_override(Some(
399                                self.inner.ip_or_hostname().to_string(),
400                            )),
401                        ));
402                    }
403                }
404
405                Ok(MySqlConn {
406                    conn: self.connect_with_timeout(opts_builder).await?,
407                    _ssh_tunnel_handle: None,
408                })
409            }
410        }
411    }
412
413    async fn connect_with_timeout(
414        &self,
415        opts_builder: OptsBuilder,
416    ) -> Result<mysql_async::Conn, MySqlError> {
417        // NOTE: mysql_async panics on some server-controlled handshake input, for example an
418        // auth switch to `parsec`, which is a bare `panic!` without mysql_common's
419        // `client_parsec` feature. Outside a catch scope the panic hook aborts the process, so a
420        // server we connect to could take down environmentd or clusterd. The catch scope is
421        // task-local, so it has to wrap `Conn::new` inside the spawned task.
422        let connect = async move {
423            match AssertUnwindSafe(Conn::new(opts_builder))
424                .ore_catch_unwind()
425                .await
426            {
427                Ok(result) => result.map_err(MySqlError::from),
428                Err(payload) => {
429                    let message = payload
430                        .downcast_ref::<&str>()
431                        .map(|s| s.to_string())
432                        .or_else(|| payload.downcast_ref::<String>().cloned())
433                        .unwrap_or_else(|| "unknown panic".to_string());
434                    error!("mysql connection attempt panicked: {message}");
435                    Err(MySqlError::ConnectionPanicked(message))
436                }
437            }
438        };
439        let connection_future: Pin<Box<dyn Future<Output = Result<Conn, MySqlError>> + Send>> =
440            if let InTask::Yes = self.in_task {
441                Box::pin(spawn(|| "mysql_connect".to_string(), connect).abort_on_drop())
442            } else {
443                Box::pin(connect)
444            };
445
446        if let Some(connect_timeout) = self.mysql_timeout_config.connect_timeout {
447            mz_ore::future::timeout(connect_timeout, connection_future)
448                .await
449                .map_err(|err| match err {
450                    // match instead of impl From<> for MySqlError so we can capture the timeout value
451                    TimeoutError::DeadlineElapsed => MySqlError::ConnectionTimeout(connect_timeout),
452                    TimeoutError::Inner(e) => e,
453                })
454        } else {
455            connection_future.await
456        }
457    }
458}
459
460/// The MySQL error code for `ER_ACCESS_DENIED_ERROR`.
461const ER_ACCESS_DENIED_ERROR: u16 = 1045;
462
463/// Reports whether the server refused the connection's credentials.
464///
465/// Amazon RDS for MySQL was observed to answer a token signed by a revoked
466/// role session with `ER_ACCESS_DENIED_ERROR`.
467fn is_authentication_failure(error: &MySqlError) -> bool {
468    match error {
469        MySqlError::MySql(mysql_async::Error::Server(e)) => e.code == ER_ACCESS_DENIED_ERROR,
470        _ => false,
471    }
472}