1use 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#[derive(Debug, PartialEq, Clone)]
39pub enum TunnelConfig {
40 Direct {
44 resolved_ips: Option<BTreeSet<IpAddr>>,
45 },
46 Ssh { config: SshTunnelConfig },
52 AwsPrivatelink {
55 connection_id: CatalogItemId,
57 },
58}
59
60pub const DEFAULT_SNAPSHOT_STATEMENT_TIMEOUT: Duration = Duration::ZERO;
61
62pub struct Client {
64 inner: tokio_postgres::Client,
65 _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#[derive(Clone, Debug)]
90pub struct Config {
91 inner: tokio_postgres::Config,
92 tunnel: TunnelConfig,
93 in_task: InTask,
94 ssh_timeout_config: SshTimeoutConfig,
95 iam_auth: Option<RdsIamAuth>,
98}
99
100impl Config {
101 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 config.address()?;
124
125 Ok(config)
126 }
127
128 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 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 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 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 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; 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 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 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 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
380fn 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 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)] 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 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)] async fn unreachable_server_does_not_report_the_token() {
467 let mut inner = tokio_postgres::Config::new();
468 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}