Skip to main content

mz_postgres_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 std::collections::BTreeSet;
11use std::net::IpAddr;
12use std::ops::{Deref, DerefMut};
13use std::time::Duration;
14
15use mz_aws_util::rds::RdsIamAuth;
16use mz_ore::future::{InTask, OreFutureExt};
17use mz_ore::option::OptionExt;
18use mz_ore::task::{self, AbortOnDropHandle};
19use mz_repr::CatalogItemId;
20use mz_ssh_util::tunnel::{SshTimeoutConfig, SshTunnelConfig};
21use mz_ssh_util::tunnel_manager::SshTunnelManager;
22use tokio::net::TcpStream as TokioTcpStream;
23use tokio_postgres::config::{Host, ReplicationMode};
24use tokio_postgres::error::SqlState;
25use tokio_postgres::tls::MakeTlsConnect;
26use tracing::{info, warn};
27
28use crate::PostgresError;
29
30macro_rules! bail_generic {
31    ($err:expr $(,)?) => {
32        return Err(PostgresError::Generic(anyhow::anyhow!($err)))
33    };
34}
35
36/// Configures an optional tunnel for use when connecting to a PostgreSQL
37/// database.
38#[derive(Debug, PartialEq, Clone)]
39pub enum TunnelConfig {
40    /// Establish a direct TCP connection to the database host.
41    /// If `resolved_ips` is not None, the provided IPs will be used
42    /// rather than resolving the hostname.
43    Direct {
44        resolved_ips: Option<BTreeSet<IpAddr>>,
45    },
46    /// Establish a TCP connection to the database via an SSH tunnel.
47    /// This means first establishing an SSH connection to a bastion host,
48    /// and then opening a separate connection from that host to the database.
49    /// This is commonly referred by vendors as a "direct SSH tunnel", in
50    /// opposition to "reverse SSH tunnel", which is currently unsupported.
51    Ssh { config: SshTunnelConfig },
52    /// Establish a TCP connection to the database via an AWS PrivateLink
53    /// service.
54    AwsPrivatelink {
55        /// The ID of the AWS PrivateLink service.
56        connection_id: CatalogItemId,
57    },
58}
59
60pub const DEFAULT_SNAPSHOT_STATEMENT_TIMEOUT: Duration = Duration::ZERO;
61
62/// A wrapper for [`tokio_postgres::Client`] that can report the server version.
63pub struct Client {
64    inner: tokio_postgres::Client,
65    // Holds a handle to the task with the connection to ensure that when
66    // the client is dropped, the task can be aborted to close the connection.
67    // This is also useful for maintaining the lifetimes of dependent object (e.g. ssh tunnel).
68    _connection_handle: AbortOnDropHandle<()>,
69}
70
71impl Deref for Client {
72    type Target = tokio_postgres::Client;
73
74    fn deref(&self) -> &Self::Target {
75        &self.inner
76    }
77}
78
79impl DerefMut for Client {
80    fn deref_mut(&mut self) -> &mut Self::Target {
81        &mut self.inner
82    }
83}
84
85/// Configuration for PostgreSQL connections.
86///
87/// This wraps [`tokio_postgres::Config`] to allow the configuration of a
88/// tunnel via a [`TunnelConfig`].
89#[derive(Clone, Debug)]
90pub struct Config {
91    inner: tokio_postgres::Config,
92    tunnel: TunnelConfig,
93    in_task: InTask,
94    ssh_timeout_config: SshTimeoutConfig,
95    /// If set, authenticate with an AWS IAM authentication token in place of
96    /// a password.
97    iam_auth: Option<RdsIamAuth>,
98}
99
100impl Config {
101    /// Creates a new configuration.
102    ///
103    /// If `iam_auth` is `Some`, each connection authenticates to Amazon RDS
104    /// or Aurora with a freshly generated AWS IAM authentication token, and
105    /// any password set on `inner` is ignored.
106    pub fn new(
107        inner: tokio_postgres::Config,
108        tunnel: TunnelConfig,
109        ssh_timeout_config: SshTimeoutConfig,
110        in_task: InTask,
111        iam_auth: Option<RdsIamAuth>,
112    ) -> Result<Self, PostgresError> {
113        let config = Self {
114            inner,
115            tunnel,
116            in_task,
117            ssh_timeout_config,
118            iam_auth,
119        };
120
121        // Early validate that the configuration contains only a single TCP
122        // server.
123        config.address()?;
124
125        Ok(config)
126    }
127
128    /// Connects to the configured PostgreSQL database.
129    pub async fn connect(
130        &self,
131        task_name: &str,
132        ssh_tunnel_manager: &SshTunnelManager,
133    ) -> Result<Client, PostgresError> {
134        self.connect_traced(task_name, |_| (), ssh_tunnel_manager)
135            .await
136    }
137
138    /// Starts a replication connection to the configured PostgreSQL database.
139    pub async fn connect_replication(
140        &self,
141        ssh_tunnel_manager: &SshTunnelManager,
142    ) -> Result<Client, PostgresError> {
143        self.connect_traced(
144            "postgres_connect_replication",
145            |config| {
146                config.replication_mode(ReplicationMode::Logical);
147            },
148            ssh_tunnel_manager,
149        )
150        .await
151    }
152
153    fn address(&self) -> Result<(&str, u16), PostgresError> {
154        match (self.inner.get_hosts(), self.inner.get_ports()) {
155            ([Host::Tcp(host)], [port]) => Ok((host, *port)),
156            _ => bail_generic!("only TCP connections to a single PostgreSQL server are supported"),
157        }
158    }
159
160    async fn connect_traced<F>(
161        &self,
162        task_name: &str,
163        configure: F,
164        ssh_tunnel_manager: &SshTunnelManager,
165    ) -> Result<Client, PostgresError>
166    where
167        F: FnOnce(&mut tokio_postgres::Config),
168    {
169        let (host, port) = self.address()?;
170        let address = format!(
171            "{}@{}:{}/{}",
172            self.get_user().display_or("<unknown-user>"),
173            host,
174            port,
175            self.get_dbname().display_or("<unknown-dbname>")
176        );
177        info!(%task_name, %address, "connecting");
178        match self
179            .connect_internal(task_name, configure, ssh_tunnel_manager)
180            .await
181        {
182            Ok(t) => {
183                let backend_pid = t.backend_pid();
184                info!(%task_name, %address, %backend_pid, "connected");
185                Ok(t)
186            }
187            Err(e) => {
188                warn!(%task_name, %address, "connection failed: {e:#}");
189                Err(e)
190            }
191        }
192    }
193
194    async fn connect_internal<F>(
195        &self,
196        task_name: &str,
197        configure: F,
198        ssh_tunnel_manager: &SshTunnelManager,
199    ) -> Result<Client, PostgresError>
200    where
201        F: FnOnce(&mut tokio_postgres::Config),
202    {
203        let mut postgres_config = self.inner.clone();
204        configure(&mut postgres_config);
205
206        let iam_token = match &self.iam_auth {
207            None => None,
208            Some(iam_auth) => {
209                // Sign the token for the address of the database itself, not
210                // for any tunnel in front of it. A token is valid for 15
211                // minutes and is only checked when a connection opens, so
212                // generate a new one for every connection.
213                let (host, port) = self.address()?;
214                let Some(user) = self.inner.get_user() else {
215                    bail_generic!("AWS IAM authentication requires a user");
216                };
217                let token = iam_auth.token(host, port, user).await?;
218                postgres_config.password(token.token.unsecure());
219                Some(token)
220            }
221        };
222
223        let result = self
224            .connect_with_config(task_name, postgres_config, ssh_tunnel_manager)
225            .await;
226        if let Err(error) = &result
227            && let Some(iam_auth) = &self.iam_auth
228            && let Some(token) = &iam_token
229            && is_authentication_failure(error)
230        {
231            iam_auth.token_rejected(token);
232        }
233        result
234    }
235
236    async fn connect_with_config(
237        &self,
238        task_name: &str,
239        mut postgres_config: tokio_postgres::Config,
240        ssh_tunnel_manager: &SshTunnelManager,
241    ) -> Result<Client, PostgresError> {
242        let mut tls = mz_tls_util::make_tls(&postgres_config).map_err(|tls_err| match tls_err {
243            mz_tls_util::TlsError::Generic(e) => PostgresError::Generic(e),
244            mz_tls_util::TlsError::OpenSsl(e) => PostgresError::PostgresSsl(e),
245        })?;
246
247        match &self.tunnel {
248            TunnelConfig::Direct { resolved_ips } => {
249                if let Some(ips) = resolved_ips {
250                    let host = match postgres_config.get_hosts() {
251                        [Host::Tcp(host)] => host,
252                        _ => bail_generic!(
253                            "only TCP connections to a single PostgreSQL server are supported"
254                        ),
255                    }
256                    .to_owned();
257                    // Associate each resolved ip with the exact same, singular host, for tls
258                    // verification. We are required to do this dance because `tokio-postgres`
259                    // enforces that the number of 'host' and 'hostaddr' values must be the same.
260                    for (idx, ip) in ips.iter().enumerate() {
261                        if idx != 0 {
262                            postgres_config.host(&host);
263                        }
264                        postgres_config.hostaddr(ip.clone());
265                    }
266                };
267
268                let (client, connection) = async move { postgres_config.connect(tls).await }
269                    .run_in_task_if(self.in_task, || "pg_connect".to_string())
270                    .await?;
271
272                let client = Client {
273                    inner: client,
274                    _connection_handle: task::spawn(|| task_name, async {
275                        if let Err(e) = connection.await {
276                            warn!("postgres direct connection failed: {e}");
277                        }
278                    })
279                    .abort_on_drop(),
280                };
281                Ok(client)
282            }
283            TunnelConfig::Ssh { config } => {
284                let (host, port) = self.address()?;
285                let tunnel = ssh_tunnel_manager
286                    .connect(
287                        config.clone(),
288                        host,
289                        port,
290                        self.ssh_timeout_config,
291                        self.in_task,
292                    )
293                    .await
294                    .map_err(PostgresError::Ssh)?;
295
296                let tls = MakeTlsConnect::<TokioTcpStream>::make_tls_connect(&mut tls, host)?;
297                let tcp_stream = TokioTcpStream::connect(tunnel.local_addr())
298                    .await
299                    .map_err(PostgresError::SshIo)?;
300                // Because we are connecting to a local host/port, we don't configure any TCP
301                // keepalive settings. The connection is entirely local to the machine running the
302                // process and we trust the kernel to keep a local connection alive without keepalives.
303                //
304                // Ideally we'd be able to configure SSH to enable TCP keepalives on the other
305                // end of the tunnel, between the SSH bastion host and the PostgreSQL server,
306                // but SSH does not expose an option for this.
307                let (client, connection) =
308                    async move { postgres_config.connect_raw(tcp_stream, tls).await }
309                        .run_in_task_if(self.in_task, || "pg_connect".to_string())
310                        .await?;
311
312                let client = Client {
313                    inner: client,
314                    _connection_handle: task::spawn(|| task_name, async {
315                        let _tunnel = tunnel; // Keep SSH tunnel alive for duration of connection.
316                        if let Err(e) = connection.await {
317                            warn!("postgres via SSH tunnel connection failed: {e}");
318                        }
319                    })
320                    .abort_on_drop(),
321                };
322                Ok(client)
323            }
324            TunnelConfig::AwsPrivatelink { connection_id } => {
325                // This section of code is somewhat subtle. We are overriding the host
326                // for the actual TCP connection to be the PrivateLink host, but leaving the host
327                // for TLS verification as the original host. Managing the
328                // `tokio_postgres::Config` to do this is somewhat confusing, and requires we edit
329                // the singular host in place.
330
331                let privatelink_host = mz_cloud_resources::vpc_endpoint_name(*connection_id);
332                let privatelink_addrs = tokio::net::lookup_host((privatelink_host, 0)).await?;
333
334                // Override the actual IPs to connect to for the TCP connection, leaving the original host in-place
335                // for TLS verification
336                let host = match postgres_config.get_hosts() {
337                    [Host::Tcp(host)] => host,
338                    _ => bail_generic!(
339                        "only TCP connections to a single PostgreSQL server are supported"
340                    ),
341                }
342                .to_owned();
343                // Associate each resolved ip with the exact same, singular host, for tls
344                // verification. We are required to do this dance because `tokio-postgres`
345                // enforces that the number of 'host' and 'hostaddr' values must be the same.
346                for (idx, addr) in privatelink_addrs.enumerate() {
347                    if idx != 0 {
348                        postgres_config.host(&host);
349                    }
350                    postgres_config.hostaddr(addr.ip());
351                }
352
353                let (client, connection) = async move { postgres_config.connect(tls).await }
354                    .run_in_task_if(self.in_task, || "pg_connect".to_string())
355                    .await?;
356
357                let client = Client {
358                    inner: client,
359                    _connection_handle: task::spawn(|| task_name, async {
360                        if let Err(e) = connection.await {
361                            warn!("postgres AWS link connection failed: {e}");
362                        }
363                    })
364                    .abort_on_drop(),
365                };
366                Ok(client)
367            }
368        }
369    }
370
371    pub fn get_user(&self) -> Option<&str> {
372        self.inner.get_user()
373    }
374
375    pub fn get_dbname(&self) -> Option<&str> {
376        self.inner.get_dbname()
377    }
378}
379
380/// Reports whether the server refused the connection's credentials, which is
381/// SQLSTATE class 28.
382///
383/// Amazon RDS was observed to answer two kinds of refused IAM connection
384/// with an error in this class. With IAM authentication disabled for
385/// replication, it reports `password authentication failed`. With a token
386/// signed by a revoked role session, it reports `PAM authentication failed`.
387fn is_authentication_failure(error: &PostgresError) -> bool {
388    match error {
389        PostgresError::Postgres(e) => {
390            let code = e.code();
391            code == Some(&SqlState::INVALID_PASSWORD)
392                || code == Some(&SqlState::INVALID_AUTHORIZATION_SPECIFICATION)
393        }
394        _ => false,
395    }
396}
397
398#[cfg(test)]
399mod tests {
400    use std::sync::{Arc, Mutex};
401
402    use aws_credential_types::Credentials;
403    use aws_credential_types::provider::SharedCredentialsProvider;
404    use aws_types::SdkConfig;
405
406    use super::*;
407
408    /// Returns a config that authenticates `inner` with an IAM token, and the
409    /// access key IDs of the tokens that were reported as rejected.
410    fn iam_config(inner: tokio_postgres::Config) -> (Config, Arc<Mutex<Vec<String>>>) {
411        let rejected = Arc::new(Mutex::new(Vec::new()));
412        let credentials = Credentials::new("akid-test", "secret", None, None, "test");
413        let aws_config = SdkConfig::builder()
414            .credentials_provider(SharedCredentialsProvider::new(credentials))
415            .build();
416        let iam_auth = RdsIamAuth::new(aws_config).on_token_rejected({
417            let rejected = Arc::clone(&rejected);
418            move |access_key_id: &str| {
419                let mut rejected = rejected.lock().expect("lock poisoned");
420                rejected.push(access_key_id.to_owned());
421            }
422        });
423        let config = Config::new(
424            inner,
425            TunnelConfig::Direct { resolved_ips: None },
426            SshTimeoutConfig::default(),
427            InTask::No,
428            Some(iam_auth),
429        )
430        .expect("valid config");
431        (config, rejected)
432    }
433
434    #[mz_ore::test(tokio::test)]
435    #[cfg_attr(miri, ignore)] // unsupported operation: can't call foreign function `getauxval` on OS `linux`
436    async fn refused_login_reports_the_token() {
437        let Ok(url) = std::env::var("POSTGRES_URL") else {
438            println!("skipped: POSTGRES_URL is not set, so there is no server to connect to");
439            return;
440        };
441        let mut inner: tokio_postgres::Config = url.parse().expect("valid POSTGRES_URL");
442        // No such role exists, so the server refuses the login whichever
443        // authentication method it uses for the connection.
444        inner
445            .user("mz_iam_auth_test_no_such_role")
446            .dbname("postgres");
447        let (config, rejected) = iam_config(inner);
448
449        let error = config
450            .connect("test", &SshTunnelManager::default())
451            .await
452            .err()
453            .expect("the server must refuse the login");
454        assert!(
455            is_authentication_failure(&error),
456            "expected an authentication failure, got: {error}"
457        );
458        assert_eq!(
459            *rejected.lock().expect("lock poisoned"),
460            vec!["akid-test".to_owned()]
461        );
462    }
463
464    #[mz_ore::test(tokio::test)]
465    #[cfg_attr(miri, ignore)] // unsupported operation: can't call foreign function `getauxval` on OS `linux`
466    async fn unreachable_server_does_not_report_the_token() {
467        let mut inner = tokio_postgres::Config::new();
468        // Nothing listens on this port, so the connection fails before the
469        // server sees the token.
470        inner
471            .host("localhost")
472            .port(1)
473            .user("postgres")
474            .dbname("postgres")
475            .connect_timeout(Duration::from_secs(10));
476        let (config, rejected) = iam_config(inner);
477
478        let error = config
479            .connect("test", &SshTunnelManager::default())
480            .await
481            .err()
482            .expect("nothing listens on the port");
483        assert!(
484            !is_authentication_failure(&error),
485            "expected a connection failure, got: {error}"
486        );
487        assert!(rejected.lock().expect("lock poisoned").is_empty());
488    }
489}