Skip to main content

mz_deploy/client/
connection.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
10//! Database client for mz-deploy.
11//!
12//! This module provides the main `Client` struct for interacting with Materialize.
13//! The client handles connection management and delegates specialized operations
14//! to domain-specific sub-clients.
15//!
16//! ## Sub-Client Architecture
17//!
18//! Operations are grouped into domain sub-clients accessed via accessor methods
19//! on `Client`. Each sub-client borrows the `Client` and provides a focused API:
20//!
21//! | Sub-client | Accessor | Responsibility |
22//! |------------|----------|---------------|
23//! | `DeploymentsClient` | `.deployments()` | Deployment lifecycle (stage, promote, abort) |
24//! | `DeploymentsClientMut` | `.deployments_mut()` | Mutable deployment ops (SUBSCRIBE cursors) |
25//! | `IntrospectionClient` | `.introspection()` | Read-only catalog metadata queries |
26//! | `ValidationClient` | `.validation()` | Pre-deployment environment checks |
27//! | `TypeInfoClient` | `.types()` | Column/type introspection for type checking |
28//! | `ProvisioningClient` | `.provisioning()` | Idempotent DDL for databases, schemas, clusters |
29//!
30//! ## TLS Policy
31//!
32//! Per-profile `sslmode` with libpq semantics (`disable`, `prefer`, `require`,
33//! `verify-ca`, `verify-full`). When unset, loopback hosts default to
34//! `prefer` and everything else defaults to `require`. See the design at
35//! `docs/superpowers/specs/2026-04-22-profile-tls-design.md` for the behavior
36//! table and migration notes.
37
38use 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
46/// Database client for interacting with Materialize.
47///
48/// The `Client` struct provides methods for:
49/// - Connecting to the database
50/// - Schema and cluster management
51/// - Deployment tracking
52/// - Database introspection
53/// - Project validation
54pub struct Client {
55    client: PgClient,
56    profile: Profile,
57    default_replication_factor: std::sync::OnceLock<u32>,
58}
59
60/// Domain sub-client for deployment lifecycle operations.
61pub struct DeploymentsClient<'a> {
62    pub(crate) client: &'a Client,
63}
64
65/// Domain sub-client for deployment operations that require mutable client access.
66pub struct DeploymentsClientMut<'a> {
67    pub(crate) client: &'a mut Client,
68}
69
70/// Domain sub-client for metadata and object introspection operations.
71pub struct IntrospectionClient<'a> {
72    pub(crate) client: &'a Client,
73}
74
75/// Domain sub-client for project and privilege validation operations.
76pub struct ValidationClient<'a> {
77    pub(crate) client: &'a Client,
78}
79
80/// Domain sub-client for column/type introspection used by type checking and tests.
81pub struct TypeInfoClient<'a> {
82    pub(crate) client: &'a Client,
83}
84
85/// Domain sub-client for provisioning databases, schemas, and clusters.
86pub struct ProvisioningClient<'a> {
87    pub(crate) client: &'a Client,
88}
89
90/// Domain sub-client for developer overlay manifest operations.
91pub struct DevOverlaysClient<'a> {
92    pub(crate) client: &'a Client,
93}
94
95const APPLICATION_NAME: &str = "mz-deploy";
96
97impl Client {
98    /// Connect to the database using a Profile directly.
99    ///
100    /// TLS behavior is driven by `profile.sslmode`; when unset, loopback hosts
101    /// default to `prefer` and everything else defaults to `require`. Verification
102    /// (`verify-ca` / `verify-full`) trusts only `profile.sslrootcert` when it
103    /// is set. Without it, `verify-full` trusts the platform roots and
104    /// `verify-ca` is an error.
105    ///
106    /// Every connection is pinned to `_mz_deploy_server` via libpq options;
107    /// any user-supplied `cluster` in profile.options is silently overridden.
108    /// The unit-test runtime uses `connect_with_profile_no_pin` instead —
109    /// its ephemeral Docker container has no `_mz_deploy_server` cluster.
110    pub async fn connect_with_profile(profile: Profile) -> Result<Self, ConnectionError> {
111        Self::connect_with_profile_inner(profile, /* pin_server_cluster */ true).await
112    }
113
114    /// Connect without pinning the session cluster to `_mz_deploy_server`.
115    ///
116    /// Used in two places where `_mz_deploy_server` is not yet (or never)
117    /// present:
118    /// - The ephemeral Docker container used by unit-test execution.
119    /// - `setup::run`, which is the command that creates the cluster.
120    ///
121    /// Uses whatever cluster the profile or server default selects.
122    /// Deliberately `pub(crate)` so nothing outside the crate can bypass
123    /// the production session-cluster pin.
124    pub(crate) async fn connect_with_profile_no_pin(
125        profile: Profile,
126    ) -> Result<Self, ConnectionError> {
127        Self::connect_with_profile_inner(profile, /* pin_server_cluster */ 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        // `config.connect(NoTls)` and `config.connect(tls)` return `Connection`s
163        // parameterized over different TLS stream types that can't unify. We box
164        // both to a common `dyn Future` so there's a single spawn site below.
165        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    /// The replication factor the server gives a managed cluster whose
198    /// definition omits `REPLICATION FACTOR`.
199    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    /// Get the profile used for this connection.
218    pub fn profile(&self) -> &Profile {
219        &self.profile
220    }
221
222    /// Start a transaction on the underlying connection.
223    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    /// Access deployment lifecycle operations.
231    pub fn deployments(&self) -> DeploymentsClient<'_> {
232        DeploymentsClient { client: self }
233    }
234
235    /// Access mutable deployment lifecycle operations.
236    pub fn deployments_mut(&mut self) -> DeploymentsClientMut<'_> {
237        DeploymentsClientMut { client: self }
238    }
239
240    /// Access metadata and object introspection operations.
241    pub fn introspection(&self) -> IntrospectionClient<'_> {
242        IntrospectionClient { client: self }
243    }
244
245    /// Access database validation operations.
246    pub fn validation(&self) -> ValidationClient<'_> {
247        ValidationClient { client: self }
248    }
249
250    /// Access type/column introspection operations.
251    pub fn types(&self) -> TypeInfoClient<'_> {
252        TypeInfoClient { client: self }
253    }
254
255    /// Access provisioning operations for databases, schemas, and clusters.
256    pub fn provisioning(&self) -> ProvisioningClient<'_> {
257        ProvisioningClient { client: self }
258    }
259
260    /// Access developer overlay manifest operations.
261    pub fn dev_overlays(&self) -> DevOverlaysClient<'_> {
262        DevOverlaysClient { client: self }
263    }
264
265    /// Execute a SQL statement that doesn't return rows.
266    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    /// Execute a SQL query and return the resulting rows.
281    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    /// Execute a SQL query and return the resulting rows.
296    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    /// Execute a SQL statement using the simple query protocol (text-only, no binary encoding).
311    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    /// Execute one or more SQL statements that don't return rows, using the simple query protocol.
321    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
328/// The default `SslMode` applied when a profile does not set `sslmode`.
329///
330/// Loopback hosts get `Prefer` so local Mz (which does not offer TLS) works
331/// without explicit config. Everything else gets `Require` — TLS is required
332/// but certificate verification is not. Users who want verification set
333/// `sslmode = "verify-ca"` or `sslmode = "verify-full"` explicitly.
334pub(crate) fn default_sslmode(host: &str) -> SslMode {
335    if is_loopback_host(host) {
336        SslMode::Prefer
337    } else {
338        SslMode::Require
339    }
340}
341
342/// Returns `true` if `host` names the loopback interface.
343///
344/// Recognizes `localhost`, any address in `127.0.0.0/8`, and `::1` (with or
345/// without URL-style brackets). Used by the SQL TLS defaults and by
346/// `mz-deploy mcp` to pick `http://` vs `https://`.
347pub(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/// Pure-data representation of the TLS setup for a connection, derived from
371/// a profile's effective `SslMode` and `sslrootcert`.
372#[derive(Debug)]
373enum ConnectorSpec {
374    NoTls,
375    Tls {
376        /// Selects peer and hostname verification in
377        /// [`mz_tls_util::make_tls_rustls`]. `verify-full` checks the name
378        /// the connection was made to, whether a DNS name or an IP literal.
379        mode: tokio_postgres::config::SslMode,
380        ca_source: CaSource,
381    },
382}
383
384/// Where the CA bundle comes from for verifying the server cert, or the
385/// absence thereof for non-verifying modes.
386#[derive(Debug)]
387enum CaSource {
388    /// `disable` / `prefer` / `require` — no CA is loaded.
389    None,
390    /// Explicit path from the profile's `sslrootcert` field.
391    Explicit(std::path::PathBuf),
392    /// The platform's root store, for `verify-full` without `sslrootcert`.
393    PlatformRoots,
394}
395
396/// Runtime-ready connector variant handed to `tokio_postgres::Config::connect`.
397enum 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
411/// Plan the TLS setup for a connection from the resolved (mode, CA) inputs.
412///
413/// Pure: does no network I/O and — aside from the injected `ca_exists`
414/// predicate — does no filesystem I/O. Returns a [`ConnectorSpec`] that
415/// [`build_connector`] then materializes into a rustls connector.
416fn 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                // verify-ca skips the host name, so any certificate a platform
435                // root issued for any domain would pass.
436                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
449/// Convert a [`ConnectorSpec`] into a runtime [`Connector`]. All filesystem
450/// I/O for CAs happens here.
451fn 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
471/// Classify a `tokio_postgres::Error` surfaced from `Config::connect(...)`
472/// into the most specific `ConnectionError` variant.
473///
474/// Rules:
475/// - rustls error found in the source chain + `mode` is `verify-*` →
476///   [`ConnectionError::TlsVerification`] (with `hostname_suffix` if the
477///   certificate does not match the host name or IP).
478/// - `mode` is `require` / `verify-*` and the error message indicates the
479///   server refused TLS → [`ConnectionError::TlsRequiredNotSupported`].
480/// - Otherwise → [`ConnectionError::Connect`].
481fn classify_connect_error(
482    source: tokio_postgres::Error,
483    profile: &Profile,
484    mode: SslMode,
485) -> ConnectionError {
486    // Caller has already gone through `require_host()` to attempt the
487    // connection that produced this error, so `host` must be `Some` here.
488    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
530/// Walk the source chain of a `tokio_postgres::Error` and return the first
531/// `rustls::Error` found.
532fn 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        // NOTE: `io::Error::source` skips the error it wraps, which is where
539        // tokio-rustls puts the handshake failure.
540        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
551/// Heuristic: does the error look like "server said no to our TLS request"?
552///
553/// `tokio_postgres` surfaces this as an io error or a "server does not
554/// support TLS" message depending on version. We string-match the Display
555/// form because the typed variants are not all public.
556fn message_indicates_tls_refused(err: &tokio_postgres::Error) -> bool {
557    matches_tls_refused_message(&err.to_string())
558}
559
560/// Pure string check for the substrings `tokio_postgres` produces when the
561/// server refuses the TLS startup request (responds `'N'` to the SSL byte).
562///
563/// Extracted from `message_indicates_tls_refused` so we can unit-test the
564/// substring list — the caller takes `&tokio_postgres::Error`, which has no
565/// public constructor.
566fn 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
572/// Escape a value for embedding inside the libpq `options` connection
573/// parameter.
574///
575/// Within the `options` string, spaces separate `-c key=value` tokens unless
576/// escaped, and backslash is the escape character. Only spaces and backslashes
577/// are special; all other characters are literal.
578fn 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
590/// Build the inner value of the libpq `options` connection parameter from a
591/// profile's options map.
592///
593/// Produces a space-separated string of `-c key=value` tokens in sorted-key
594/// order, with each value inner-escaped per [`escape_options_value`].
595/// Returns `None` when the map is empty so the caller can omit the fragment.
596pub(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        // Space then backslash
630        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        // Insert in reverse order to verify BTreeMap iteration sorts keys.
653        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)] // unsupported operation: can't call foreign function `rust_psm_stack_pointer` on OS `linux`
750    #[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)] // unsupported operation: can't call foreign function `rust_psm_stack_pointer` on OS `linux`
761    #[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}