1use crate::client::errors::ConnectionError;
39use crate::config::{Profile, SslMode};
40use crate::info;
41use mz_postgres_util::Sql;
42use std::collections::BTreeMap;
43use tokio_postgres::types::ToSql;
44use tokio_postgres::{Client as PgClient, NoTls, Row, SimpleQueryMessage, Transaction};
45
46pub struct Client {
55 client: PgClient,
56 profile: Profile,
57 default_replication_factor: std::sync::OnceLock<u32>,
58}
59
60pub struct DeploymentsClient<'a> {
62 pub(crate) client: &'a Client,
63}
64
65pub struct DeploymentsClientMut<'a> {
67 pub(crate) client: &'a mut Client,
68}
69
70pub struct IntrospectionClient<'a> {
72 pub(crate) client: &'a Client,
73}
74
75pub struct ValidationClient<'a> {
77 pub(crate) client: &'a Client,
78}
79
80pub struct TypeInfoClient<'a> {
82 pub(crate) client: &'a Client,
83}
84
85pub struct ProvisioningClient<'a> {
87 pub(crate) client: &'a Client,
88}
89
90pub struct DevOverlaysClient<'a> {
92 pub(crate) client: &'a Client,
93}
94
95const APPLICATION_NAME: &str = "mz-deploy";
96
97impl Client {
98 pub async fn connect_with_profile(profile: Profile) -> Result<Self, ConnectionError> {
111 Self::connect_with_profile_inner(profile, true).await
112 }
113
114 pub(crate) async fn connect_with_profile_no_pin(
125 profile: Profile,
126 ) -> Result<Self, ConnectionError> {
127 Self::connect_with_profile_inner(profile, false).await
128 }
129
130 async fn connect_with_profile_inner(
131 profile: Profile,
132 pin_server_cluster: bool,
133 ) -> Result<Self, ConnectionError> {
134 let host = profile.require_host()?;
135 let mut config = tokio_postgres::Config::new();
136 config.host(host);
137 config.port(profile.port);
138 config.user(&profile.username);
139 config.dbname("materialize");
140 if let Some(password) = &profile.password {
141 config.password(password.as_str());
142 }
143 config.application_name(APPLICATION_NAME);
144
145 let mut effective_options = profile.options.clone();
146 if pin_server_cluster {
147 effective_options.insert(
148 "cluster".to_string(),
149 crate::client::SERVER_CLUSTER_NAME.to_string(),
150 );
151 }
152 if let Some(inner) = build_options_string(&effective_options) {
153 config.options(&inner);
154 }
155
156 let mode = profile.sslmode.unwrap_or_else(|| default_sslmode(host));
157 let spec = plan_connector(mode, profile.sslrootcert.as_deref(), |p| p.exists())?;
158 let connector = build_connector(spec)?;
159
160 config.ssl_mode(tokio_ssl_mode(mode));
161
162 type BoxConnection =
166 Box<dyn Future<Output = Result<(), tokio_postgres::Error>> + Send + Unpin>;
167 let (client, connection): (PgClient, BoxConnection) = match connector {
168 Connector::NoTls => {
169 let (client, connection) = config
170 .connect(NoTls)
171 .await
172 .map_err(|source| classify_connect_error(source, &profile, mode))?;
173 (client, Box::new(connection))
174 }
175 Connector::Tls(tls) => {
176 let (client, connection) = config
177 .connect(tls)
178 .await
179 .map_err(|source| classify_connect_error(source, &profile, mode))?;
180 (client, Box::new(connection))
181 }
182 };
183
184 mz_ore::task::spawn(|| "mz-deploy-connection", async move {
185 if let Err(e) = connection.await {
186 info!("connection error: {}", e);
187 }
188 });
189
190 Ok(Client {
191 client,
192 profile,
193 default_replication_factor: std::sync::OnceLock::new(),
194 })
195 }
196
197 pub(crate) async fn default_cluster_replication_factor(&self) -> Result<u32, ConnectionError> {
200 if let Some(factor) = self.default_replication_factor.get() {
201 return Ok(*factor);
202 }
203 let row = self
204 .query_one("SHOW default_cluster_replication_factor", &[])
205 .await?;
206 let raw: String = row.get(0);
207 let factor = raw.parse().map_err(|_| {
208 ConnectionError::Message(format!(
209 "invalid default_cluster_replication_factor '{}'",
210 raw
211 ))
212 })?;
213 let _ = self.default_replication_factor.set(factor);
214 Ok(factor)
215 }
216
217 pub fn profile(&self) -> &Profile {
219 &self.profile
220 }
221
222 pub(crate) async fn begin_transaction(&mut self) -> Result<Transaction<'_>, ConnectionError> {
224 self.client
225 .transaction()
226 .await
227 .map_err(ConnectionError::Query)
228 }
229
230 pub fn deployments(&self) -> DeploymentsClient<'_> {
232 DeploymentsClient { client: self }
233 }
234
235 pub fn deployments_mut(&mut self) -> DeploymentsClientMut<'_> {
237 DeploymentsClientMut { client: self }
238 }
239
240 pub fn introspection(&self) -> IntrospectionClient<'_> {
242 IntrospectionClient { client: self }
243 }
244
245 pub fn validation(&self) -> ValidationClient<'_> {
247 ValidationClient { client: self }
248 }
249
250 pub fn types(&self) -> TypeInfoClient<'_> {
252 TypeInfoClient { client: self }
253 }
254
255 pub fn provisioning(&self) -> ProvisioningClient<'_> {
257 ProvisioningClient { client: self }
258 }
259
260 pub fn dev_overlays(&self) -> DevOverlaysClient<'_> {
262 DevOverlaysClient { client: self }
263 }
264
265 pub async fn execute(
267 &self,
268 statement: &str,
269 params: &[&(dyn ToSql + Sync)],
270 ) -> Result<u64, ConnectionError> {
271 mz_postgres_util::execute(
272 &self.client,
273 Sql::raw_unchecked(statement.to_string()),
274 params,
275 )
276 .await
277 .map_err(ConnectionError::from)
278 }
279
280 pub async fn query_one(
282 &self,
283 statement: &str,
284 params: &[&(dyn ToSql + Sync)],
285 ) -> Result<Row, ConnectionError> {
286 mz_postgres_util::query_one(
287 &self.client,
288 Sql::raw_unchecked(statement.to_string()),
289 params,
290 )
291 .await
292 .map_err(ConnectionError::from)
293 }
294
295 pub async fn query(
297 &self,
298 statement: &str,
299 params: &[&(dyn ToSql + Sync)],
300 ) -> Result<Vec<Row>, ConnectionError> {
301 mz_postgres_util::query(
302 &self.client,
303 Sql::raw_unchecked(statement.to_string()),
304 params,
305 )
306 .await
307 .map_err(ConnectionError::from)
308 }
309
310 pub async fn simple_query(
312 &self,
313 query: &str,
314 ) -> Result<Vec<SimpleQueryMessage>, ConnectionError> {
315 mz_postgres_util::simple_query(&self.client, Sql::raw_unchecked(query.to_string()))
316 .await
317 .map_err(ConnectionError::from)
318 }
319
320 pub async fn batch_execute(&self, query: &str) -> Result<(), ConnectionError> {
322 mz_postgres_util::batch_execute(&self.client, Sql::raw_unchecked(query.to_string()))
323 .await
324 .map_err(ConnectionError::from)
325 }
326}
327
328pub(crate) fn default_sslmode(host: &str) -> SslMode {
335 if is_loopback_host(host) {
336 SslMode::Prefer
337 } else {
338 SslMode::Require
339 }
340}
341
342pub(crate) fn is_loopback_host(host: &str) -> bool {
348 if host == "localhost" {
349 return true;
350 }
351 let unbracketed = host
352 .strip_prefix('[')
353 .and_then(|s| s.strip_suffix(']'))
354 .unwrap_or(host);
355 if let Ok(ip) = unbracketed.parse::<std::net::IpAddr>() {
356 return ip.is_loopback();
357 }
358 false
359}
360
361fn tokio_ssl_mode(mode: SslMode) -> tokio_postgres::config::SslMode {
362 use tokio_postgres::config::SslMode as TokioMode;
363 match mode {
364 SslMode::Disable => TokioMode::Disable,
365 SslMode::Prefer => TokioMode::Prefer,
366 SslMode::Require | SslMode::VerifyCa | SslMode::VerifyFull => TokioMode::Require,
367 }
368}
369
370#[derive(Debug)]
373enum ConnectorSpec {
374 NoTls,
375 Tls {
376 mode: tokio_postgres::config::SslMode,
380 ca_source: CaSource,
381 },
382}
383
384#[derive(Debug)]
387enum CaSource {
388 None,
390 Explicit(std::path::PathBuf),
392 PlatformRoots,
394}
395
396enum Connector {
398 NoTls,
399 Tls(mz_tls_util::MakeRustlsConnect),
400}
401
402impl std::fmt::Debug for Connector {
403 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
404 match self {
405 Connector::NoTls => write!(f, "Connector::NoTls"),
406 Connector::Tls(_) => write!(f, "Connector::Tls(...)"),
407 }
408 }
409}
410
411fn plan_connector(
417 mode: SslMode,
418 sslrootcert: Option<&std::path::Path>,
419 ca_exists: impl Fn(&std::path::Path) -> bool,
420) -> Result<ConnectorSpec, ConnectionError> {
421 use tokio_postgres::config::SslMode as TokioMode;
422
423 match mode {
424 SslMode::Disable => Ok(ConnectorSpec::NoTls),
425 SslMode::Prefer | SslMode::Require => Ok(ConnectorSpec::Tls {
426 mode: TokioMode::Require,
427 ca_source: CaSource::None,
428 }),
429 SslMode::VerifyCa | SslMode::VerifyFull => {
430 let verify_full = matches!(mode, SslMode::VerifyFull);
431 let ca_source = match sslrootcert {
432 Some(path) if ca_exists(path) => CaSource::Explicit(path.to_path_buf()),
433 Some(_) => return Err(ConnectionError::TlsCaNotFound),
434 None if !verify_full => return Err(ConnectionError::TlsCaNotFound),
437 None => CaSource::PlatformRoots,
438 };
439 let mode = if verify_full {
440 TokioMode::VerifyFull
441 } else {
442 TokioMode::VerifyCa
443 };
444 Ok(ConnectorSpec::Tls { mode, ca_source })
445 }
446 }
447}
448
449fn build_connector(spec: ConnectorSpec) -> Result<Connector, ConnectionError> {
452 match spec {
453 ConnectorSpec::NoTls => Ok(Connector::NoTls),
454 ConnectorSpec::Tls { mode, ca_source } => {
455 let mut tls_config = tokio_postgres::Config::new();
456 tls_config.ssl_mode(mode);
457 match ca_source {
458 CaSource::None | CaSource::PlatformRoots => {}
459 CaSource::Explicit(path) => {
460 let ca = std::fs::read(&path).map_err(|_| ConnectionError::TlsCaNotFound)?;
461 tls_config.ssl_root_cert(&ca);
462 }
463 }
464 let tls = mz_tls_util::make_tls_rustls(&tls_config)
465 .map_err(|e| ConnectionError::Message(format!("{e:#}")))?;
466 Ok(Connector::Tls(tls))
467 }
468 }
469}
470
471fn classify_connect_error(
482 source: tokio_postgres::Error,
483 profile: &Profile,
484 mode: SslMode,
485) -> ConnectionError {
486 let host = profile.host.clone().unwrap_or_default();
489 if matches!(mode, SslMode::VerifyCa | SslMode::VerifyFull) {
490 if let Some(tls_err) = tls_error_in_chain(&source) {
491 let hostname_suffix = if matches!(
492 tls_err,
493 rustls::Error::InvalidCertificate(
494 rustls::CertificateError::NotValidForName
495 | rustls::CertificateError::NotValidForNameContext { .. }
496 )
497 ) {
498 " (hostname mismatch)"
499 } else {
500 ""
501 };
502 return ConnectionError::TlsVerification {
503 host,
504 port: profile.port,
505 hostname_suffix,
506 source,
507 };
508 }
509 }
510
511 if matches!(
512 mode,
513 SslMode::Require | SslMode::VerifyCa | SslMode::VerifyFull
514 ) && message_indicates_tls_refused(&source)
515 {
516 return ConnectionError::TlsRequiredNotSupported {
517 host,
518 port: profile.port,
519 source,
520 };
521 }
522
523 ConnectionError::Connect {
524 host,
525 port: profile.port,
526 source,
527 }
528}
529
530fn tls_error_in_chain(err: &tokio_postgres::Error) -> Option<&rustls::Error> {
533 let mut cur: &(dyn std::error::Error + 'static) = err;
534 loop {
535 if let Some(tls_err) = cur.downcast_ref::<rustls::Error>() {
536 return Some(tls_err);
537 }
538 if let Some(inner) = cur
541 .downcast_ref::<std::io::Error>()
542 .and_then(|io| io.get_ref())
543 .and_then(|inner| inner.downcast_ref::<rustls::Error>())
544 {
545 return Some(inner);
546 }
547 cur = cur.source()?;
548 }
549}
550
551fn message_indicates_tls_refused(err: &tokio_postgres::Error) -> bool {
557 matches_tls_refused_message(&err.to_string())
558}
559
560fn matches_tls_refused_message(msg: &str) -> bool {
567 msg.contains("TLS was required")
568 || msg.contains("server does not support TLS")
569 || msg.contains("server does not support SSL")
570}
571
572fn escape_options_value(value: &str) -> String {
579 let mut out = String::with_capacity(value.len());
580 for c in value.chars() {
581 match c {
582 '\\' => out.push_str(r"\\"),
583 ' ' => out.push_str(r"\ "),
584 other => out.push(other),
585 }
586 }
587 out
588}
589
590pub(crate) fn build_options_string(options: &BTreeMap<String, String>) -> Option<String> {
597 if options.is_empty() {
598 return None;
599 }
600 let joined = options
601 .iter()
602 .map(|(k, v)| format!("-c {k}={}", escape_options_value(v)))
603 .collect::<Vec<_>>()
604 .join(" ");
605 Some(joined)
606}
607
608#[cfg(test)]
609mod tests {
610 use super::*;
611
612 #[mz_ore::test]
613 fn test_escape_options_value_plain() {
614 assert_eq!(escape_options_value("prod"), "prod");
615 }
616
617 #[mz_ore::test]
618 fn test_escape_options_value_space() {
619 assert_eq!(escape_options_value("prod cluster"), r"prod\ cluster");
620 }
621
622 #[mz_ore::test]
623 fn test_escape_options_value_backslash() {
624 assert_eq!(escape_options_value(r"a\b"), r"a\\b");
625 }
626
627 #[mz_ore::test]
628 fn test_escape_options_value_mixed() {
629 assert_eq!(escape_options_value(r"a \b"), r"a\ \\b");
631 }
632
633 #[mz_ore::test]
634 fn test_build_options_string_empty() {
635 let options: BTreeMap<String, String> = BTreeMap::new();
636 assert_eq!(build_options_string(&options), None);
637 }
638
639 #[mz_ore::test]
640 fn test_build_options_string_single() {
641 let mut options = BTreeMap::new();
642 options.insert("cluster".to_string(), "prod".to_string());
643 assert_eq!(
644 build_options_string(&options),
645 Some("-c cluster=prod".to_string())
646 );
647 }
648
649 #[mz_ore::test]
650 fn test_build_options_string_multiple_sorted() {
651 let mut options = BTreeMap::new();
652 options.insert("search_path".to_string(), "public".to_string());
654 options.insert("cluster".to_string(), "prod".to_string());
655 assert_eq!(
656 build_options_string(&options),
657 Some("-c cluster=prod -c search_path=public".to_string())
658 );
659 }
660
661 #[mz_ore::test]
662 fn test_build_options_string_escapes_value_space() {
663 let mut options = BTreeMap::new();
664 options.insert("cluster".to_string(), "prod cluster".to_string());
665 assert_eq!(
666 build_options_string(&options),
667 Some(r"-c cluster=prod\ cluster".to_string())
668 );
669 }
670
671 #[mz_ore::test]
672 fn test_build_options_string_escapes_value_backslash() {
673 let mut options = BTreeMap::new();
674 options.insert("cluster".to_string(), r"a\b".to_string());
675 assert_eq!(
676 build_options_string(&options),
677 Some(r"-c cluster=a\\b".to_string())
678 );
679 }
680
681 use tokio_postgres::config::SslMode as TokioMode;
682
683 #[mz_ore::test]
684 fn plan_disable_produces_notls() {
685 let spec = plan_connector(SslMode::Disable, None, |_| false).unwrap();
686 assert!(matches!(spec, ConnectorSpec::NoTls));
687 }
688
689 #[mz_ore::test]
690 fn plan_prefer_and_require_do_not_verify_and_load_no_ca() {
691 for mode in [SslMode::Prefer, SslMode::Require] {
692 let spec = plan_connector(mode, None, |_| true).unwrap();
693 match spec {
694 ConnectorSpec::Tls { mode, ca_source } => {
695 assert_eq!(mode, TokioMode::Require);
696 assert!(matches!(ca_source, CaSource::None));
697 }
698 ConnectorSpec::NoTls => panic!("expected Tls for {:?}, got NoTls", mode),
699 }
700 }
701 }
702
703 #[mz_ore::test]
704 fn plan_verify_ca_without_sslrootcert_is_ca_not_found() {
705 let err = plan_connector(SslMode::VerifyCa, None, |_| true).unwrap_err();
706 assert!(matches!(err, ConnectionError::TlsCaNotFound));
707 }
708
709 #[mz_ore::test]
710 fn plan_verify_full_without_sslrootcert_uses_platform_roots() {
711 let spec = plan_connector(SslMode::VerifyFull, None, |_| true).unwrap();
712 match spec {
713 ConnectorSpec::Tls {
714 mode,
715 ca_source: CaSource::PlatformRoots,
716 } => assert_eq!(mode, TokioMode::VerifyFull),
717 other => panic!("expected Tls/PlatformRoots, got {:?}", other),
718 }
719 }
720
721 #[mz_ore::test]
722 fn plan_explicit_sslrootcert_is_used() {
723 let explicit = std::path::PathBuf::from("/my/ca.pem");
724 for mode in [SslMode::VerifyCa, SslMode::VerifyFull] {
725 let spec = plan_connector(mode, Some(&explicit), |p| p == explicit.as_path()).unwrap();
726 match spec {
727 ConnectorSpec::Tls {
728 ca_source: CaSource::Explicit(p),
729 ..
730 } => assert_eq!(p, explicit),
731 other => panic!("expected Tls/Explicit, got {:?}", other),
732 }
733 }
734 }
735
736 #[mz_ore::test]
737 fn plan_explicit_sslrootcert_missing_is_ca_not_found() {
738 let explicit = std::path::PathBuf::from("/no/such/file.pem");
739 let err = plan_connector(SslMode::VerifyCa, Some(&explicit), |_| false).unwrap_err();
740 assert!(matches!(err, ConnectionError::TlsCaNotFound));
741 }
742
743 #[mz_ore::test]
744 fn build_disable_returns_notls() {
745 let connector = build_connector(ConnectorSpec::NoTls).unwrap();
746 assert!(matches!(connector, Connector::NoTls));
747 }
748
749 #[cfg_attr(miri, ignore)] #[mz_ore::test]
751 fn build_prefer_returns_tls_no_ca_work() {
752 let connector = build_connector(ConnectorSpec::Tls {
753 mode: TokioMode::Require,
754 ca_source: CaSource::None,
755 })
756 .unwrap();
757 assert!(matches!(connector, Connector::Tls(_)));
758 }
759
760 #[cfg_attr(miri, ignore)] #[mz_ore::test]
762 fn build_explicit_missing_ca_returns_ca_not_found() {
763 let err = build_connector(ConnectorSpec::Tls {
764 mode: TokioMode::VerifyCa,
765 ca_source: CaSource::Explicit(std::path::PathBuf::from("/absolutely/not/a/real/file")),
766 })
767 .unwrap_err();
768 assert!(matches!(err, ConnectionError::TlsCaNotFound));
769 }
770
771 #[mz_ore::test]
772 fn matches_tls_refused_tls_was_required() {
773 assert!(matches_tls_refused_message(
774 "some prefix: TLS was required but not provided"
775 ));
776 }
777
778 #[mz_ore::test]
779 fn matches_tls_refused_does_not_support_tls() {
780 assert!(matches_tls_refused_message(
781 "error: server does not support TLS"
782 ));
783 }
784
785 #[mz_ore::test]
786 fn matches_tls_refused_does_not_support_ssl() {
787 assert!(matches_tls_refused_message(
788 "error: server does not support SSL"
789 ));
790 }
791
792 #[mz_ore::test]
793 fn matches_tls_refused_unrelated_message() {
794 assert!(!matches_tls_refused_message("connection refused"));
795 assert!(!matches_tls_refused_message("database does not exist"));
796 assert!(!matches_tls_refused_message(""));
797 }
798}