mz_environmentd/
test_util.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::BTreeMap;
11use std::error::Error;
12use std::future::IntoFuture;
13use std::net::{IpAddr, Ipv4Addr, SocketAddr, TcpStream};
14use std::path::{Path, PathBuf};
15use std::pin::Pin;
16use std::str::FromStr;
17use std::sync::Arc;
18use std::sync::LazyLock;
19use std::time::Duration;
20use std::{env, fs, iter};
21
22use anyhow::anyhow;
23use futures::Future;
24use futures::future::{BoxFuture, LocalBoxFuture};
25use headers::{Header, HeaderMapExt};
26use http::Uri;
27use hyper::http::header::HeaderMap;
28use maplit::btreemap;
29use mz_adapter::TimestampExplanation;
30use mz_adapter_types::bootstrap_builtin_cluster_config::{
31    ANALYTICS_CLUSTER_DEFAULT_REPLICATION_FACTOR, BootstrapBuiltinClusterConfig,
32    CATALOG_SERVER_CLUSTER_DEFAULT_REPLICATION_FACTOR, PROBE_CLUSTER_DEFAULT_REPLICATION_FACTOR,
33    SUPPORT_CLUSTER_DEFAULT_REPLICATION_FACTOR, SYSTEM_CLUSTER_DEFAULT_REPLICATION_FACTOR,
34};
35
36use mz_auth::password::Password;
37use mz_catalog::config::ClusterReplicaSizeMap;
38use mz_controller::ControllerConfig;
39use mz_dyncfg::ConfigUpdates;
40use mz_license_keys::ValidatedLicenseKey;
41use mz_orchestrator_process::{ProcessOrchestrator, ProcessOrchestratorConfig};
42use mz_orchestrator_tracing::{TracingCliArgs, TracingOrchestrator};
43use mz_ore::metrics::MetricsRegistry;
44use mz_ore::now::{EpochMillis, NowFn, SYSTEM_TIME};
45use mz_ore::retry::Retry;
46use mz_ore::task;
47use mz_ore::tracing::{
48    OpenTelemetryConfig, StderrLogConfig, StderrLogFormat, TracingConfig, TracingHandle,
49};
50use mz_persist_client::PersistLocation;
51use mz_persist_client::cache::PersistClientCache;
52use mz_persist_client::cfg::{CONSENSUS_CONNECTION_POOL_MAX_SIZE, PersistConfig};
53use mz_persist_client::rpc::PersistGrpcPubSubServer;
54use mz_secrets::SecretsController;
55use mz_server_core::listeners::{
56    AllowedRoles, AuthenticatorKind, BaseListenerConfig, HttpRoutesEnabled,
57};
58use mz_server_core::{ReloadTrigger, TlsCertConfig};
59use mz_sql::catalog::EnvironmentId;
60use mz_storage_types::connections::ConnectionContext;
61use mz_tracing::CloneableEnvFilter;
62use openssl::asn1::Asn1Time;
63use openssl::error::ErrorStack;
64use openssl::hash::MessageDigest;
65use openssl::nid::Nid;
66use openssl::pkey::{PKey, Private};
67use openssl::rsa::Rsa;
68use openssl::ssl::{SslConnector, SslConnectorBuilder, SslMethod, SslOptions};
69use openssl::x509::extension::{BasicConstraints, SubjectAlternativeName};
70use openssl::x509::{X509, X509Name, X509NameBuilder};
71use postgres::error::DbError;
72use postgres::tls::{MakeTlsConnect, TlsConnect};
73use postgres::types::{FromSql, Type};
74use postgres::{NoTls, Socket};
75use postgres_openssl::MakeTlsConnector;
76use tempfile::TempDir;
77use tokio::net::TcpListener;
78use tokio::runtime::Runtime;
79use tokio_postgres::config::{Host, SslMode};
80use tokio_postgres::{AsyncMessage, Client};
81use tokio_stream::wrappers::TcpListenerStream;
82use tower_http::cors::AllowOrigin;
83use tracing::Level;
84use tracing_capture::SharedStorage;
85use tracing_subscriber::EnvFilter;
86use tungstenite::stream::MaybeTlsStream;
87use tungstenite::{Message, WebSocket};
88
89use crate::{
90    CatalogConfig, FronteggAuthenticator, HttpListenerConfig, ListenersConfig, SqlListenerConfig,
91    WebSocketAuth, WebSocketResponse,
92};
93
94pub static KAFKA_ADDRS: LazyLock<String> =
95    LazyLock::new(|| env::var("KAFKA_ADDRS").unwrap_or_else(|_| "localhost:9092".into()));
96
97/// Entry point for creating and configuring an `environmentd` test harness.
98#[derive(Clone)]
99pub struct TestHarness {
100    data_directory: Option<PathBuf>,
101    tls: Option<TlsCertConfig>,
102    frontegg: Option<FronteggAuthenticator>,
103    external_login_password_mz_system: Option<Password>,
104    listeners_config: ListenersConfig,
105    unsafe_mode: bool,
106    workers: usize,
107    now: NowFn,
108    seed: u32,
109    storage_usage_collection_interval: Duration,
110    storage_usage_retention_period: Option<Duration>,
111    default_cluster_replica_size: String,
112    default_cluster_replication_factor: u32,
113    builtin_system_cluster_config: BootstrapBuiltinClusterConfig,
114    builtin_catalog_server_cluster_config: BootstrapBuiltinClusterConfig,
115    builtin_probe_cluster_config: BootstrapBuiltinClusterConfig,
116    builtin_support_cluster_config: BootstrapBuiltinClusterConfig,
117    builtin_analytics_cluster_config: BootstrapBuiltinClusterConfig,
118
119    propagate_crashes: bool,
120    enable_tracing: bool,
121    // This is currently unrelated to enable_tracing, and is used only to disable orchestrator
122    // tracing.
123    orchestrator_tracing_cli_args: TracingCliArgs,
124    bootstrap_role: Option<String>,
125    deploy_generation: u64,
126    system_parameter_defaults: BTreeMap<String, String>,
127    internal_console_redirect_url: Option<String>,
128    metrics_registry: Option<MetricsRegistry>,
129    code_version: semver::Version,
130    capture: Option<SharedStorage>,
131    pub environment_id: EnvironmentId,
132}
133
134impl Default for TestHarness {
135    fn default() -> TestHarness {
136        TestHarness {
137            data_directory: None,
138            tls: None,
139            frontegg: None,
140            external_login_password_mz_system: None,
141            listeners_config: ListenersConfig {
142                sql: btreemap![
143                    "external".to_owned() => SqlListenerConfig {
144                        addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 0),
145                        authenticator_kind: AuthenticatorKind::None,
146                        allowed_roles: AllowedRoles::Normal,
147                        enable_tls: false,
148                    },
149                    "internal".to_owned() => SqlListenerConfig {
150                        addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 0),
151                        authenticator_kind: AuthenticatorKind::None,
152                        allowed_roles: AllowedRoles::NormalAndInternal,
153                        enable_tls: false,
154                    },
155                ],
156                http: btreemap![
157                    "external".to_owned() => HttpListenerConfig {
158                        base: BaseListenerConfig {
159                            addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 0),
160                            authenticator_kind: AuthenticatorKind::None,
161                            allowed_roles: AllowedRoles::Normal,
162                            enable_tls: false,
163                        },
164                        routes: HttpRoutesEnabled{
165                            base: true,
166                            webhook: true,
167                            internal: false,
168                            metrics: false,
169                            profiling: false,
170                        },
171                    },
172                    "internal".to_owned() => HttpListenerConfig {
173                        base: BaseListenerConfig {
174                            addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 0),
175                            authenticator_kind: AuthenticatorKind::None,
176                            allowed_roles: AllowedRoles::NormalAndInternal,
177                            enable_tls: false,
178                        },
179                        routes: HttpRoutesEnabled{
180                            base: true,
181                            webhook: true,
182                            internal: true,
183                            metrics: true,
184                            profiling: true,
185                        },
186                    },
187                ],
188            },
189            unsafe_mode: false,
190            workers: 1,
191            now: SYSTEM_TIME.clone(),
192            seed: rand::random(),
193            storage_usage_collection_interval: Duration::from_secs(3600),
194            storage_usage_retention_period: None,
195            default_cluster_replica_size: "scale=1,workers=1".to_string(),
196            default_cluster_replication_factor: 1,
197            builtin_system_cluster_config: BootstrapBuiltinClusterConfig {
198                size: "scale=1,workers=1".to_string(),
199                replication_factor: SYSTEM_CLUSTER_DEFAULT_REPLICATION_FACTOR,
200            },
201            builtin_catalog_server_cluster_config: BootstrapBuiltinClusterConfig {
202                size: "scale=1,workers=1".to_string(),
203                replication_factor: CATALOG_SERVER_CLUSTER_DEFAULT_REPLICATION_FACTOR,
204            },
205            builtin_probe_cluster_config: BootstrapBuiltinClusterConfig {
206                size: "scale=1,workers=1".to_string(),
207                replication_factor: PROBE_CLUSTER_DEFAULT_REPLICATION_FACTOR,
208            },
209            builtin_support_cluster_config: BootstrapBuiltinClusterConfig {
210                size: "scale=1,workers=1".to_string(),
211                replication_factor: SUPPORT_CLUSTER_DEFAULT_REPLICATION_FACTOR,
212            },
213            builtin_analytics_cluster_config: BootstrapBuiltinClusterConfig {
214                size: "scale=1,workers=1".to_string(),
215                replication_factor: ANALYTICS_CLUSTER_DEFAULT_REPLICATION_FACTOR,
216            },
217            propagate_crashes: false,
218            enable_tracing: false,
219            bootstrap_role: Some("materialize".into()),
220            deploy_generation: 0,
221            // This and startup_log_filter below are both (?) needed to suppress clusterd messages.
222            // If we need those in the future, we might need to change both.
223            system_parameter_defaults: BTreeMap::from([(
224                "log_filter".to_string(),
225                "error".to_string(),
226            )]),
227            internal_console_redirect_url: None,
228            metrics_registry: None,
229            orchestrator_tracing_cli_args: TracingCliArgs {
230                startup_log_filter: CloneableEnvFilter::from_str("error").expect("must parse"),
231                ..Default::default()
232            },
233            code_version: crate::BUILD_INFO.semver_version(),
234            environment_id: EnvironmentId::for_tests(),
235            capture: None,
236        }
237    }
238}
239
240impl TestHarness {
241    /// Starts a test [`TestServer`], panicking if the server could not be started.
242    ///
243    /// For cases when startup might fail, see [`TestHarness::try_start`].
244    pub async fn start(self) -> TestServer {
245        self.try_start().await.expect("Failed to start test Server")
246    }
247
248    /// Like [`TestHarness::start`] but can specify a cert reload trigger.
249    pub async fn start_with_trigger(self, tls_reload_certs: ReloadTrigger) -> TestServer {
250        self.try_start_with_trigger(tls_reload_certs)
251            .await
252            .expect("Failed to start test Server")
253    }
254
255    /// Starts a test [`TestServer`], returning an error if the server could not be started.
256    pub async fn try_start(self) -> Result<TestServer, anyhow::Error> {
257        self.try_start_with_trigger(mz_server_core::cert_reload_never_reload())
258            .await
259    }
260
261    /// Like [`TestHarness::try_start`] but can specify a cert reload trigger.
262    pub async fn try_start_with_trigger(
263        self,
264        tls_reload_certs: ReloadTrigger,
265    ) -> Result<TestServer, anyhow::Error> {
266        let listeners = Listeners::new(&self).await?;
267        listeners.serve_with_trigger(self, tls_reload_certs).await
268    }
269
270    /// Starts a runtime and returns a [`TestServerWithRuntime`].
271    pub fn start_blocking(self) -> TestServerWithRuntime {
272        let runtime = tokio::runtime::Builder::new_multi_thread()
273            .enable_all()
274            .thread_stack_size(mz_ore::stack::STACK_SIZE)
275            .build()
276            .expect("failed to spawn runtime for test");
277        let runtime = Arc::new(runtime);
278        let server = runtime.block_on(self.start());
279        TestServerWithRuntime { runtime, server }
280    }
281
282    pub fn data_directory(mut self, data_directory: impl Into<PathBuf>) -> Self {
283        self.data_directory = Some(data_directory.into());
284        self
285    }
286
287    pub fn with_tls(mut self, cert_path: impl Into<PathBuf>, key_path: impl Into<PathBuf>) -> Self {
288        self.tls = Some(TlsCertConfig {
289            cert: cert_path.into(),
290            key: key_path.into(),
291        });
292        for (_, listener) in &mut self.listeners_config.sql {
293            listener.enable_tls = true;
294        }
295        for (_, listener) in &mut self.listeners_config.http {
296            listener.base.enable_tls = true;
297        }
298        self
299    }
300
301    pub fn unsafe_mode(mut self) -> Self {
302        self.unsafe_mode = true;
303        self
304    }
305
306    pub fn workers(mut self, workers: usize) -> Self {
307        self.workers = workers;
308        self
309    }
310
311    pub fn with_frontegg_auth(mut self, frontegg: &FronteggAuthenticator) -> Self {
312        self.frontegg = Some(frontegg.clone());
313        let enable_tls = self.tls.is_some();
314        self.listeners_config = ListenersConfig {
315            sql: btreemap! {
316                "external".to_owned() => SqlListenerConfig {
317                    addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 0),
318                    authenticator_kind: AuthenticatorKind::Frontegg,
319                    allowed_roles: AllowedRoles::Normal,
320                    enable_tls,
321                },
322                "internal".to_owned() => SqlListenerConfig {
323                    addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 0),
324                    authenticator_kind: AuthenticatorKind::None,
325                    allowed_roles: AllowedRoles::NormalAndInternal,
326                    enable_tls: false,
327                },
328            },
329            http: btreemap! {
330                "external".to_owned() => HttpListenerConfig {
331                    base: BaseListenerConfig {
332                        addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 0),
333                        authenticator_kind: AuthenticatorKind::Frontegg,
334                        allowed_roles: AllowedRoles::Normal,
335                        enable_tls,
336                    },
337                    routes: HttpRoutesEnabled{
338                        base: true,
339                        webhook: true,
340                        internal: false,
341                        metrics: false,
342                        profiling: false,
343                    },
344                },
345                "internal".to_owned() => HttpListenerConfig {
346                    base: BaseListenerConfig {
347                        addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 0),
348                        authenticator_kind: AuthenticatorKind::None,
349                        allowed_roles: AllowedRoles::NormalAndInternal,
350                        enable_tls: false,
351                    },
352                    routes: HttpRoutesEnabled{
353                        base: true,
354                        webhook: true,
355                        internal: true,
356                        metrics: true,
357                        profiling: true,
358                    },
359                },
360            },
361        };
362        self
363    }
364
365    pub fn with_password_auth(mut self, mz_system_password: Password) -> Self {
366        self.external_login_password_mz_system = Some(mz_system_password);
367        let enable_tls = self.tls.is_some();
368        self.listeners_config = ListenersConfig {
369            sql: btreemap! {
370                "external".to_owned() => SqlListenerConfig {
371                    addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 0),
372                    authenticator_kind: AuthenticatorKind::Password,
373                    allowed_roles: AllowedRoles::NormalAndInternal,
374                    enable_tls,
375                },
376            },
377            http: btreemap! {
378                "external".to_owned() => HttpListenerConfig {
379                    base: BaseListenerConfig {
380                        addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 0),
381                        authenticator_kind: AuthenticatorKind::Password,
382                        allowed_roles: AllowedRoles::NormalAndInternal,
383                        enable_tls,
384                    },
385                    routes: HttpRoutesEnabled{
386                        base: true,
387                        webhook: true,
388                        internal: true,
389                        metrics: false,
390                        profiling: true,
391                    },
392                },
393                "metrics".to_owned() => HttpListenerConfig {
394                    base: BaseListenerConfig {
395                        addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 0),
396                        authenticator_kind: AuthenticatorKind::None,
397                        allowed_roles: AllowedRoles::NormalAndInternal,
398                        enable_tls: false,
399                    },
400                    routes: HttpRoutesEnabled{
401                        base: false,
402                        webhook: false,
403                        internal: false,
404                        metrics: true,
405                        profiling: false,
406                    },
407                },
408            },
409        };
410        self
411    }
412
413    pub fn with_sasl_scram_auth(mut self, mz_system_password: Password) -> Self {
414        self.external_login_password_mz_system = Some(mz_system_password);
415        let enable_tls = self.tls.is_some();
416        self.listeners_config = ListenersConfig {
417            sql: btreemap! {
418                "external".to_owned() => SqlListenerConfig {
419                    addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 0),
420                    authenticator_kind: AuthenticatorKind::Sasl,
421                    allowed_roles: AllowedRoles::NormalAndInternal,
422                    enable_tls,
423                },
424            },
425            http: btreemap! {
426                "external".to_owned() => HttpListenerConfig {
427                    base: BaseListenerConfig {
428                        addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 0),
429                        authenticator_kind: AuthenticatorKind::Password,
430                        allowed_roles: AllowedRoles::NormalAndInternal,
431                        enable_tls,
432                    },
433                    routes: HttpRoutesEnabled{
434                        base: true,
435                        webhook: true,
436                        internal: true,
437                        metrics: false,
438                        profiling: true,
439                    },
440                },
441                "metrics".to_owned() => HttpListenerConfig {
442                    base: BaseListenerConfig {
443                        addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 0),
444                        authenticator_kind: AuthenticatorKind::None,
445                        allowed_roles: AllowedRoles::NormalAndInternal,
446                        enable_tls: false,
447                    },
448                    routes: HttpRoutesEnabled{
449                        base: false,
450                        webhook: false,
451                        internal: false,
452                        metrics: true,
453                        profiling: false,
454                    },
455                },
456            },
457        };
458        self
459    }
460
461    pub fn with_now(mut self, now: NowFn) -> Self {
462        self.now = now;
463        self
464    }
465
466    pub fn with_storage_usage_collection_interval(
467        mut self,
468        storage_usage_collection_interval: Duration,
469    ) -> Self {
470        self.storage_usage_collection_interval = storage_usage_collection_interval;
471        self
472    }
473
474    pub fn with_storage_usage_retention_period(
475        mut self,
476        storage_usage_retention_period: Duration,
477    ) -> Self {
478        self.storage_usage_retention_period = Some(storage_usage_retention_period);
479        self
480    }
481
482    pub fn with_default_cluster_replica_size(
483        mut self,
484        default_cluster_replica_size: String,
485    ) -> Self {
486        self.default_cluster_replica_size = default_cluster_replica_size;
487        self
488    }
489
490    pub fn with_builtin_system_cluster_replica_size(
491        mut self,
492        builtin_system_cluster_replica_size: String,
493    ) -> Self {
494        self.builtin_system_cluster_config.size = builtin_system_cluster_replica_size;
495        self
496    }
497
498    pub fn with_builtin_system_cluster_replication_factor(
499        mut self,
500        builtin_system_cluster_replication_factor: u32,
501    ) -> Self {
502        self.builtin_system_cluster_config.replication_factor =
503            builtin_system_cluster_replication_factor;
504        self
505    }
506
507    pub fn with_builtin_catalog_server_cluster_replica_size(
508        mut self,
509        builtin_catalog_server_cluster_replica_size: String,
510    ) -> Self {
511        self.builtin_catalog_server_cluster_config.size =
512            builtin_catalog_server_cluster_replica_size;
513        self
514    }
515
516    pub fn with_propagate_crashes(mut self, propagate_crashes: bool) -> Self {
517        self.propagate_crashes = propagate_crashes;
518        self
519    }
520
521    pub fn with_enable_tracing(mut self, enable_tracing: bool) -> Self {
522        self.enable_tracing = enable_tracing;
523        self
524    }
525
526    pub fn with_bootstrap_role(mut self, bootstrap_role: Option<String>) -> Self {
527        self.bootstrap_role = bootstrap_role;
528        self
529    }
530
531    pub fn with_deploy_generation(mut self, deploy_generation: u64) -> Self {
532        self.deploy_generation = deploy_generation;
533        self
534    }
535
536    pub fn with_system_parameter_default(mut self, param: String, value: String) -> Self {
537        self.system_parameter_defaults.insert(param, value);
538        self
539    }
540
541    pub fn with_internal_console_redirect_url(
542        mut self,
543        internal_console_redirect_url: Option<String>,
544    ) -> Self {
545        self.internal_console_redirect_url = internal_console_redirect_url;
546        self
547    }
548
549    pub fn with_metrics_registry(mut self, registry: MetricsRegistry) -> Self {
550        self.metrics_registry = Some(registry);
551        self
552    }
553
554    pub fn with_code_version(mut self, version: semver::Version) -> Self {
555        self.code_version = version;
556        self
557    }
558
559    pub fn with_capture(mut self, storage: SharedStorage) -> Self {
560        self.capture = Some(storage);
561        self
562    }
563}
564
565pub struct Listeners {
566    pub inner: crate::Listeners,
567}
568
569impl Listeners {
570    pub async fn new(config: &TestHarness) -> Result<Listeners, anyhow::Error> {
571        let inner = crate::Listeners::bind(config.listeners_config.clone()).await?;
572        Ok(Listeners { inner })
573    }
574
575    pub async fn serve(self, config: TestHarness) -> Result<TestServer, anyhow::Error> {
576        self.serve_with_trigger(config, mz_server_core::cert_reload_never_reload())
577            .await
578    }
579
580    pub async fn serve_with_trigger(
581        self,
582        config: TestHarness,
583        tls_reload_certs: ReloadTrigger,
584    ) -> Result<TestServer, anyhow::Error> {
585        let (data_directory, temp_dir) = match config.data_directory {
586            None => {
587                // If no data directory is provided, we create a temporary
588                // directory. The temporary directory is cleaned up when the
589                // `TempDir` is dropped, so we keep it alive until the `Server` is
590                // dropped.
591                let temp_dir = tempfile::tempdir()?;
592                (temp_dir.path().to_path_buf(), Some(temp_dir))
593            }
594            Some(data_directory) => (data_directory, None),
595        };
596        let scratch_dir = tempfile::tempdir()?;
597        let (consensus_uri, timestamp_oracle_url) = {
598            let seed = config.seed;
599            let cockroach_url = env::var("METADATA_BACKEND_URL")
600                .map_err(|_| anyhow!("METADATA_BACKEND_URL environment variable is not set"))?;
601            let (client, conn) = tokio_postgres::connect(&cockroach_url, NoTls).await?;
602            mz_ore::task::spawn(|| "startup-postgres-conn", async move {
603                if let Err(err) = conn.await {
604                    panic!("connection error: {}", err);
605                };
606            });
607            client
608                .batch_execute(&format!(
609                    "CREATE SCHEMA IF NOT EXISTS consensus_{seed};
610                    CREATE SCHEMA IF NOT EXISTS tsoracle_{seed};"
611                ))
612                .await?;
613            (
614                format!("{cockroach_url}?options=--search_path=consensus_{seed}")
615                    .parse()
616                    .expect("invalid consensus URI"),
617                format!("{cockroach_url}?options=--search_path=tsoracle_{seed}")
618                    .parse()
619                    .expect("invalid timestamp oracle URI"),
620            )
621        };
622        let metrics_registry = config.metrics_registry.unwrap_or_else(MetricsRegistry::new);
623        let orchestrator = ProcessOrchestrator::new(ProcessOrchestratorConfig {
624            image_dir: env::current_exe()?
625                .parent()
626                .unwrap()
627                .parent()
628                .unwrap()
629                .to_path_buf(),
630            suppress_output: false,
631            environment_id: config.environment_id.to_string(),
632            secrets_dir: data_directory.join("secrets"),
633            command_wrapper: vec![],
634            propagate_crashes: config.propagate_crashes,
635            tcp_proxy: None,
636            scratch_directory: scratch_dir.path().to_path_buf(),
637        })
638        .await?;
639        let orchestrator = Arc::new(orchestrator);
640        // Messing with the clock causes persist to expire leases, causing hangs and
641        // panics. Is it possible/desirable to put this back somehow?
642        let persist_now = SYSTEM_TIME.clone();
643        let dyncfgs = mz_dyncfgs::all_dyncfgs();
644
645        let mut updates = ConfigUpdates::default();
646        // Tune down the number of connections to make this all work a little easier
647        // with local postgres.
648        updates.add(&CONSENSUS_CONNECTION_POOL_MAX_SIZE, 1);
649        updates.apply(&dyncfgs);
650
651        let mut persist_cfg = PersistConfig::new(&crate::BUILD_INFO, persist_now.clone(), dyncfgs);
652        persist_cfg.build_version = config.code_version;
653        // Stress persist more by writing rollups frequently
654        persist_cfg.set_rollup_threshold(5);
655
656        let persist_pubsub_server = PersistGrpcPubSubServer::new(&persist_cfg, &metrics_registry);
657        let persist_pubsub_client = persist_pubsub_server.new_same_process_connection();
658        let persist_pubsub_tcp_listener =
659            TcpListener::bind(SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 0))
660                .await
661                .expect("pubsub addr binding");
662        let persist_pubsub_server_port = persist_pubsub_tcp_listener
663            .local_addr()
664            .expect("pubsub addr has local addr")
665            .port();
666
667        // Spawn the persist pub-sub server.
668        mz_ore::task::spawn(|| "persist_pubsub_server", async move {
669            persist_pubsub_server
670                .serve_with_stream(TcpListenerStream::new(persist_pubsub_tcp_listener))
671                .await
672                .expect("success")
673        });
674        let persist_clients =
675            PersistClientCache::new(persist_cfg, &metrics_registry, |_, _| persist_pubsub_client);
676        let persist_clients = Arc::new(persist_clients);
677
678        let secrets_controller = Arc::clone(&orchestrator);
679        let connection_context = ConnectionContext::for_tests(orchestrator.reader());
680        let orchestrator = Arc::new(TracingOrchestrator::new(
681            orchestrator,
682            config.orchestrator_tracing_cli_args,
683        ));
684        let tracing_handle = if config.enable_tracing {
685            let config = TracingConfig::<fn(&tracing::Metadata) -> sentry_tracing::EventFilter> {
686                service_name: "environmentd",
687                stderr_log: StderrLogConfig {
688                    format: StderrLogFormat::Json,
689                    filter: EnvFilter::default(),
690                },
691                opentelemetry: Some(OpenTelemetryConfig {
692                    endpoint: "http://fake_address_for_testing:8080".to_string(),
693                    headers: http::HeaderMap::new(),
694                    filter: EnvFilter::default().add_directive(Level::DEBUG.into()),
695                    resource: opentelemetry_sdk::resource::Resource::default(),
696                    max_batch_queue_size: 2048,
697                    max_export_batch_size: 512,
698                    max_concurrent_exports: 1,
699                    batch_scheduled_delay: Duration::from_millis(5000),
700                    max_export_timeout: Duration::from_secs(30),
701                }),
702                tokio_console: None,
703                sentry: None,
704                build_version: crate::BUILD_INFO.version,
705                build_sha: crate::BUILD_INFO.sha,
706                registry: metrics_registry.clone(),
707                capture: config.capture,
708            };
709            mz_ore::tracing::configure(config).await?
710        } else {
711            TracingHandle::disabled()
712        };
713        let host_name = format!(
714            "localhost:{}",
715            self.inner.http["external"].handle.local_addr.port()
716        );
717        let catalog_config = CatalogConfig {
718            persist_clients: Arc::clone(&persist_clients),
719            metrics: Arc::new(mz_catalog::durable::Metrics::new(&MetricsRegistry::new())),
720        };
721
722        let inner = self
723            .inner
724            .serve(crate::Config {
725                catalog_config,
726                timestamp_oracle_url: Some(timestamp_oracle_url),
727                controller: ControllerConfig {
728                    build_info: &crate::BUILD_INFO,
729                    orchestrator,
730                    clusterd_image: "clusterd".into(),
731                    init_container_image: None,
732                    deploy_generation: config.deploy_generation,
733                    persist_location: PersistLocation {
734                        blob_uri: format!("file://{}/persist/blob", data_directory.display())
735                            .parse()
736                            .expect("invalid blob URI"),
737                        consensus_uri,
738                    },
739                    persist_clients,
740                    now: config.now.clone(),
741                    metrics_registry: metrics_registry.clone(),
742                    persist_pubsub_url: format!("http://localhost:{}", persist_pubsub_server_port),
743                    secrets_args: mz_service::secrets::SecretsReaderCliArgs {
744                        secrets_reader: mz_service::secrets::SecretsControllerKind::LocalFile,
745                        secrets_reader_local_file_dir: Some(data_directory.join("secrets")),
746                        secrets_reader_kubernetes_context: None,
747                        secrets_reader_aws_prefix: None,
748                        secrets_reader_name_prefix: None,
749                    },
750                    connection_context,
751                },
752                secrets_controller,
753                cloud_resource_controller: None,
754                tls: config.tls,
755                frontegg: config.frontegg,
756                unsafe_mode: config.unsafe_mode,
757                all_features: false,
758                metrics_registry: metrics_registry.clone(),
759                now: config.now,
760                environment_id: config.environment_id,
761                cors_allowed_origin: AllowOrigin::list([]),
762                cluster_replica_sizes: ClusterReplicaSizeMap::for_tests(),
763                bootstrap_default_cluster_replica_size: config.default_cluster_replica_size,
764                bootstrap_default_cluster_replication_factor: config
765                    .default_cluster_replication_factor,
766                bootstrap_builtin_system_cluster_config: config.builtin_system_cluster_config,
767                bootstrap_builtin_catalog_server_cluster_config: config
768                    .builtin_catalog_server_cluster_config,
769                bootstrap_builtin_probe_cluster_config: config.builtin_probe_cluster_config,
770                bootstrap_builtin_support_cluster_config: config.builtin_support_cluster_config,
771                bootstrap_builtin_analytics_cluster_config: config.builtin_analytics_cluster_config,
772                system_parameter_defaults: config.system_parameter_defaults,
773                availability_zones: Default::default(),
774                tracing_handle,
775                storage_usage_collection_interval: config.storage_usage_collection_interval,
776                storage_usage_retention_period: config.storage_usage_retention_period,
777                segment_api_key: None,
778                segment_client_side: false,
779                test_only_dummy_segment_client: false,
780                egress_addresses: vec![],
781                aws_account_id: None,
782                aws_privatelink_availability_zones: None,
783                launchdarkly_sdk_key: None,
784                launchdarkly_key_map: Default::default(),
785                config_sync_file_path: None,
786                config_sync_timeout: Duration::from_secs(30),
787                config_sync_loop_interval: None,
788                bootstrap_role: config.bootstrap_role,
789                http_host_name: Some(host_name),
790                internal_console_redirect_url: config.internal_console_redirect_url,
791                tls_reload_certs,
792                helm_chart_version: None,
793                license_key: ValidatedLicenseKey::for_tests(),
794                external_login_password_mz_system: config.external_login_password_mz_system,
795                force_builtin_schema_migration: None,
796            })
797            .await?;
798
799        Ok(TestServer {
800            inner,
801            metrics_registry,
802            _temp_dir: temp_dir,
803            _scratch_dir: scratch_dir,
804        })
805    }
806}
807
808/// A running instance of `environmentd`.
809pub struct TestServer {
810    pub inner: crate::Server,
811    pub metrics_registry: MetricsRegistry,
812    /// The `TempDir`s are saved to prevent them from being dropped, and thus cleaned up too early.
813    _temp_dir: Option<TempDir>,
814    _scratch_dir: TempDir,
815}
816
817impl TestServer {
818    pub fn connect(&self) -> ConnectBuilder<'_, postgres::NoTls, NoHandle> {
819        ConnectBuilder::new(self).no_tls()
820    }
821
822    pub async fn enable_feature_flags(&self, flags: &[&'static str]) {
823        let internal_client = self.connect().internal().await.unwrap();
824
825        for flag in flags {
826            internal_client
827                .batch_execute(&format!("ALTER SYSTEM SET {} = true;", flag))
828                .await
829                .unwrap();
830        }
831    }
832
833    pub async fn disable_feature_flags(&self, flags: &[&'static str]) {
834        let internal_client = self.connect().internal().await.unwrap();
835
836        for flag in flags {
837            internal_client
838                .batch_execute(&format!("ALTER SYSTEM SET {} = false;", flag))
839                .await
840                .unwrap();
841        }
842    }
843
844    pub fn ws_addr(&self) -> Uri {
845        format!(
846            "ws://{}/api/experimental/sql",
847            self.inner.http_listener_handles["external"].local_addr
848        )
849        .parse()
850        .unwrap()
851    }
852
853    pub fn internal_ws_addr(&self) -> Uri {
854        format!(
855            "ws://{}/api/experimental/sql",
856            self.inner.http_listener_handles["internal"].local_addr
857        )
858        .parse()
859        .unwrap()
860    }
861
862    pub fn http_local_addr(&self) -> SocketAddr {
863        self.inner.http_listener_handles["external"].local_addr
864    }
865
866    pub fn internal_http_local_addr(&self) -> SocketAddr {
867        self.inner.http_listener_handles["internal"].local_addr
868    }
869
870    pub fn sql_local_addr(&self) -> SocketAddr {
871        self.inner.sql_listener_handles["external"].local_addr
872    }
873
874    pub fn internal_sql_local_addr(&self) -> SocketAddr {
875        self.inner.sql_listener_handles["internal"].local_addr
876    }
877}
878
879/// A builder struct to configure a pgwire connection to a running [`TestServer`].
880///
881/// You can create this struct, and thus open a pgwire connection, using [`TestServer::connect`].
882pub struct ConnectBuilder<'s, T, H> {
883    /// A running `environmentd` test server.
884    server: &'s TestServer,
885
886    /// Postgres configuration for connecting to the test server.
887    pg_config: tokio_postgres::Config,
888    /// Port to use when connecting to the test server.
889    port: u16,
890    /// Tls settings to use.
891    tls: T,
892
893    /// Callback that gets invoked for every notice we receive.
894    notice_callback: Option<Box<dyn FnMut(tokio_postgres::error::DbError) + Send + 'static>>,
895
896    /// Type variable for whether or not we include the handle for the spawned [`tokio::task`].
897    _with_handle: H,
898}
899
900impl<'s> ConnectBuilder<'s, (), NoHandle> {
901    fn new(server: &'s TestServer) -> Self {
902        let mut pg_config = tokio_postgres::Config::new();
903        pg_config
904            .host(&Ipv4Addr::LOCALHOST.to_string())
905            .user("materialize")
906            .options("--welcome_message=off")
907            .application_name("environmentd_test_framework");
908
909        ConnectBuilder {
910            server,
911            pg_config,
912            port: server.sql_local_addr().port(),
913            tls: (),
914            notice_callback: None,
915            _with_handle: NoHandle,
916        }
917    }
918}
919
920impl<'s, T, H> ConnectBuilder<'s, T, H> {
921    /// Create a pgwire connection without using TLS.
922    ///
923    /// Note: this is the default for all connections.
924    pub fn no_tls(self) -> ConnectBuilder<'s, postgres::NoTls, H> {
925        ConnectBuilder {
926            server: self.server,
927            pg_config: self.pg_config,
928            port: self.port,
929            tls: postgres::NoTls,
930            notice_callback: self.notice_callback,
931            _with_handle: self._with_handle,
932        }
933    }
934
935    /// Create a pgwire connection with TLS.
936    pub fn with_tls<Tls>(self, tls: Tls) -> ConnectBuilder<'s, Tls, H>
937    where
938        Tls: MakeTlsConnect<Socket> + Send + 'static,
939        Tls::TlsConnect: Send,
940        Tls::Stream: Send,
941        <Tls::TlsConnect as TlsConnect<Socket>>::Future: Send,
942    {
943        ConnectBuilder {
944            server: self.server,
945            pg_config: self.pg_config,
946            port: self.port,
947            tls,
948            notice_callback: self.notice_callback,
949            _with_handle: self._with_handle,
950        }
951    }
952
953    /// Create a [`ConnectBuilder`] using the provided [`tokio_postgres::Config`].
954    pub fn with_config(mut self, pg_config: tokio_postgres::Config) -> Self {
955        self.pg_config = pg_config;
956        self
957    }
958
959    /// Set the [`SslMode`] to be used with the resulting connection.
960    pub fn ssl_mode(mut self, mode: SslMode) -> Self {
961        self.pg_config.ssl_mode(mode);
962        self
963    }
964
965    /// Set the user for the pgwire connection.
966    pub fn user(mut self, user: &str) -> Self {
967        self.pg_config.user(user);
968        self
969    }
970
971    /// Set the password for the pgwire connection.
972    pub fn password(mut self, password: &str) -> Self {
973        self.pg_config.password(password);
974        self
975    }
976
977    /// Set the application name for the pgwire connection.
978    pub fn application_name(mut self, application_name: &str) -> Self {
979        self.pg_config.application_name(application_name);
980        self
981    }
982
983    /// Set the database name for the pgwire connection.
984    pub fn dbname(mut self, dbname: &str) -> Self {
985        self.pg_config.dbname(dbname);
986        self
987    }
988
989    /// Set the options for the pgwire connection.
990    pub fn options(mut self, options: &str) -> Self {
991        self.pg_config.options(options);
992        self
993    }
994
995    /// Configures this [`ConnectBuilder`] to connect to the __internal__ SQL port of the running
996    /// [`TestServer`].
997    ///
998    /// For example, this will change the port we connect to, and the user we connect as.
999    pub fn internal(mut self) -> Self {
1000        self.port = self.server.internal_sql_local_addr().port();
1001        self.pg_config.user(mz_sql::session::user::SYSTEM_USER_NAME);
1002        self
1003    }
1004
1005    /// Sets a callback for any database notices that are received from the [`TestServer`].
1006    pub fn notice_callback(self, callback: impl FnMut(DbError) + Send + 'static) -> Self {
1007        ConnectBuilder {
1008            notice_callback: Some(Box::new(callback)),
1009            ..self
1010        }
1011    }
1012
1013    /// Configures this [`ConnectBuilder`] to return the [`mz_ore::task::JoinHandle`] that is
1014    /// polling the underlying postgres connection, associated with the returned client.
1015    pub fn with_handle(self) -> ConnectBuilder<'s, T, WithHandle> {
1016        ConnectBuilder {
1017            server: self.server,
1018            pg_config: self.pg_config,
1019            port: self.port,
1020            tls: self.tls,
1021            notice_callback: self.notice_callback,
1022            _with_handle: WithHandle,
1023        }
1024    }
1025
1026    /// Returns the [`tokio_postgres::Config`] that will be used to connect.
1027    pub fn as_pg_config(&self) -> &tokio_postgres::Config {
1028        &self.pg_config
1029    }
1030}
1031
1032/// This trait enables us to either include or omit the [`mz_ore::task::JoinHandle`] in the result
1033/// of a client connection.
1034pub trait IncludeHandle: Send {
1035    type Output;
1036    fn transform_result(
1037        client: tokio_postgres::Client,
1038        handle: mz_ore::task::JoinHandle<()>,
1039    ) -> Self::Output;
1040}
1041
1042/// Type parameter that denotes we __will not__ return the [`mz_ore::task::JoinHandle`] in the
1043/// result of a [`ConnectBuilder`].
1044pub struct NoHandle;
1045impl IncludeHandle for NoHandle {
1046    type Output = tokio_postgres::Client;
1047    fn transform_result(
1048        client: tokio_postgres::Client,
1049        _handle: mz_ore::task::JoinHandle<()>,
1050    ) -> Self::Output {
1051        client
1052    }
1053}
1054
1055/// Type parameter that denotes we __will__ return the [`mz_ore::task::JoinHandle`] in the result of
1056/// a [`ConnectBuilder`].
1057pub struct WithHandle;
1058impl IncludeHandle for WithHandle {
1059    type Output = (tokio_postgres::Client, mz_ore::task::JoinHandle<()>);
1060    fn transform_result(
1061        client: tokio_postgres::Client,
1062        handle: mz_ore::task::JoinHandle<()>,
1063    ) -> Self::Output {
1064        (client, handle)
1065    }
1066}
1067
1068impl<'s, T, H> IntoFuture for ConnectBuilder<'s, T, H>
1069where
1070    T: MakeTlsConnect<Socket> + Send + 'static,
1071    T::TlsConnect: Send,
1072    T::Stream: Send,
1073    <T::TlsConnect as TlsConnect<Socket>>::Future: Send,
1074    H: IncludeHandle,
1075{
1076    type Output = Result<H::Output, postgres::Error>;
1077    type IntoFuture = BoxFuture<'static, Self::Output>;
1078
1079    fn into_future(mut self) -> Self::IntoFuture {
1080        Box::pin(async move {
1081            assert!(
1082                self.pg_config.get_ports().is_empty(),
1083                "specifying multiple ports is not supported"
1084            );
1085            self.pg_config.port(self.port);
1086
1087            let (client, mut conn) = self.pg_config.connect(self.tls).await?;
1088            let mut notice_callback = self.notice_callback.take();
1089
1090            let handle = task::spawn(|| "connect", async move {
1091                while let Some(msg) = std::future::poll_fn(|cx| conn.poll_message(cx)).await {
1092                    match msg {
1093                        Ok(AsyncMessage::Notice(notice)) => {
1094                            if let Some(callback) = notice_callback.as_mut() {
1095                                callback(notice);
1096                            }
1097                        }
1098                        Ok(msg) => {
1099                            tracing::debug!(?msg, "Dropping message from database");
1100                        }
1101                        Err(e) => {
1102                            // tokio_postgres::Connection docs say:
1103                            // > Return values of None or Some(Err(_)) are “terminal”; callers
1104                            // > should not invoke this method again after receiving one of those
1105                            // > values.
1106                            tracing::info!("connection error: {e}");
1107                            break;
1108                        }
1109                    }
1110                }
1111                tracing::info!("connection closed");
1112            });
1113
1114            let output = H::transform_result(client, handle);
1115            Ok(output)
1116        })
1117    }
1118}
1119
1120/// A running instance of `environmentd`, that exposes blocking/synchronous test helpers.
1121///
1122/// Note: Ideally you should use a [`TestServer`] which relies on an external runtime, e.g. the
1123/// [`tokio::test`] macro. This struct exists so we can incrementally migrate our existing tests.
1124pub struct TestServerWithRuntime {
1125    server: TestServer,
1126    runtime: Arc<Runtime>,
1127}
1128
1129impl TestServerWithRuntime {
1130    /// Returns the [`Runtime`] owned by this [`TestServerWithRuntime`].
1131    ///
1132    /// Can be used to spawn async tasks.
1133    pub fn runtime(&self) -> &Arc<Runtime> {
1134        &self.runtime
1135    }
1136
1137    /// Returns a referece to the inner running `environmentd` [`crate::Server`]`.
1138    pub fn inner(&self) -> &crate::Server {
1139        &self.server.inner
1140    }
1141
1142    /// Connect to the __public__ SQL port of the running `environmentd` server.
1143    pub fn connect<T>(&self, tls: T) -> Result<postgres::Client, postgres::Error>
1144    where
1145        T: MakeTlsConnect<Socket> + Send + 'static,
1146        T::TlsConnect: Send,
1147        T::Stream: Send,
1148        <T::TlsConnect as TlsConnect<Socket>>::Future: Send,
1149    {
1150        self.pg_config().connect(tls)
1151    }
1152
1153    /// Connect to the __internal__ SQL port of the running `environmentd` server.
1154    pub fn connect_internal<T>(&self, tls: T) -> Result<postgres::Client, anyhow::Error>
1155    where
1156        T: MakeTlsConnect<Socket> + Send + 'static,
1157        T::TlsConnect: Send,
1158        T::Stream: Send,
1159        <T::TlsConnect as TlsConnect<Socket>>::Future: Send,
1160    {
1161        Ok(self.pg_config_internal().connect(tls)?)
1162    }
1163
1164    /// Enable LaunchDarkly feature flags.
1165    pub fn enable_feature_flags(&self, flags: &[&'static str]) {
1166        let mut internal_client = self.connect_internal(postgres::NoTls).unwrap();
1167
1168        for flag in flags {
1169            internal_client
1170                .batch_execute(&format!("ALTER SYSTEM SET {} = true;", flag))
1171                .unwrap();
1172        }
1173    }
1174
1175    /// Disable LaunchDarkly feature flags.
1176    pub fn disable_feature_flags(&self, flags: &[&'static str]) {
1177        let mut internal_client = self.connect_internal(postgres::NoTls).unwrap();
1178
1179        for flag in flags {
1180            internal_client
1181                .batch_execute(&format!("ALTER SYSTEM SET {} = false;", flag))
1182                .unwrap();
1183        }
1184    }
1185
1186    /// Return a [`postgres::Config`] for connecting to the __public__ SQL port of the running
1187    /// `environmentd` server.
1188    pub fn pg_config(&self) -> postgres::Config {
1189        let local_addr = self.server.sql_local_addr();
1190        let mut config = postgres::Config::new();
1191        config
1192            .host(&Ipv4Addr::LOCALHOST.to_string())
1193            .port(local_addr.port())
1194            .user("materialize")
1195            .options("--welcome_message=off");
1196        config
1197    }
1198
1199    /// Return a [`postgres::Config`] for connecting to the __internal__ SQL port of the running
1200    /// `environmentd` server.
1201    pub fn pg_config_internal(&self) -> postgres::Config {
1202        let local_addr = self.server.internal_sql_local_addr();
1203        let mut config = postgres::Config::new();
1204        config
1205            .host(&Ipv4Addr::LOCALHOST.to_string())
1206            .port(local_addr.port())
1207            .user("mz_system")
1208            .options("--welcome_message=off");
1209        config
1210    }
1211
1212    pub fn ws_addr(&self) -> Uri {
1213        self.server.ws_addr()
1214    }
1215
1216    pub fn internal_ws_addr(&self) -> Uri {
1217        self.server.internal_ws_addr()
1218    }
1219
1220    pub fn http_local_addr(&self) -> SocketAddr {
1221        self.server.http_local_addr()
1222    }
1223
1224    pub fn internal_http_local_addr(&self) -> SocketAddr {
1225        self.server.internal_http_local_addr()
1226    }
1227
1228    pub fn sql_local_addr(&self) -> SocketAddr {
1229        self.server.sql_local_addr()
1230    }
1231
1232    pub fn internal_sql_local_addr(&self) -> SocketAddr {
1233        self.server.internal_sql_local_addr()
1234    }
1235
1236    /// Returns the metrics registry for the test server.
1237    pub fn metrics_registry(&self) -> &MetricsRegistry {
1238        &self.server.metrics_registry
1239    }
1240}
1241
1242#[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd)]
1243pub struct MzTimestamp(pub u64);
1244
1245impl<'a> FromSql<'a> for MzTimestamp {
1246    fn from_sql(ty: &Type, raw: &'a [u8]) -> Result<MzTimestamp, Box<dyn Error + Sync + Send>> {
1247        let n = mz_pgrepr::Numeric::from_sql(ty, raw)?;
1248        Ok(MzTimestamp(u64::try_from(n.0.0)?))
1249    }
1250
1251    fn accepts(ty: &Type) -> bool {
1252        mz_pgrepr::Numeric::accepts(ty)
1253    }
1254}
1255
1256pub trait PostgresErrorExt {
1257    fn unwrap_db_error(self) -> DbError;
1258}
1259
1260impl PostgresErrorExt for postgres::Error {
1261    fn unwrap_db_error(self) -> DbError {
1262        match self.source().and_then(|e| e.downcast_ref::<DbError>()) {
1263            Some(e) => e.clone(),
1264            None => panic!("expected DbError, but got: {:?}", self),
1265        }
1266    }
1267}
1268
1269impl<T, E> PostgresErrorExt for Result<T, E>
1270where
1271    E: PostgresErrorExt,
1272{
1273    fn unwrap_db_error(self) -> DbError {
1274        match self {
1275            Ok(_) => panic!("expected Err(DbError), but got Ok(_)"),
1276            Err(e) => e.unwrap_db_error(),
1277        }
1278    }
1279}
1280
1281/// Group commit will block writes until the current time has advanced. This can make
1282/// performing inserts while using deterministic time difficult. This is a helper
1283/// method to perform writes and advance the current time.
1284pub async fn insert_with_deterministic_timestamps(
1285    table: &'static str,
1286    values: &'static str,
1287    server: &TestServer,
1288    now: Arc<std::sync::Mutex<EpochMillis>>,
1289) -> Result<(), Box<dyn Error>> {
1290    let client_write = server.connect().await?;
1291    let client_read = server.connect().await?;
1292
1293    let mut current_ts = get_explain_timestamp(table, &client_read).await;
1294
1295    let insert_query = format!("INSERT INTO {table} VALUES {values}");
1296
1297    let write_future = client_write.execute(&insert_query, &[]);
1298    let timestamp_interval = tokio::time::interval(Duration::from_millis(1));
1299
1300    let mut write_future = std::pin::pin!(write_future);
1301    let mut timestamp_interval = std::pin::pin!(timestamp_interval);
1302
1303    // Keep increasing `now` until the write has executed succeed. Table advancements may
1304    // have increased the global timestamp by an unknown amount.
1305    loop {
1306        tokio::select! {
1307            _ = (&mut write_future) => return Ok(()),
1308            _ = timestamp_interval.tick() => {
1309                current_ts += 1;
1310                *now.lock().expect("lock poisoned") = current_ts;
1311            }
1312        };
1313    }
1314}
1315
1316pub async fn get_explain_timestamp(from_suffix: &str, client: &Client) -> EpochMillis {
1317    try_get_explain_timestamp(from_suffix, client)
1318        .await
1319        .unwrap()
1320}
1321
1322pub async fn try_get_explain_timestamp(
1323    from_suffix: &str,
1324    client: &Client,
1325) -> Result<EpochMillis, anyhow::Error> {
1326    let det = get_explain_timestamp_determination(from_suffix, client).await?;
1327    let ts = det.determination.timestamp_context.timestamp_or_default();
1328    Ok(ts.into())
1329}
1330
1331pub async fn get_explain_timestamp_determination(
1332    from_suffix: &str,
1333    client: &Client,
1334) -> Result<TimestampExplanation<mz_repr::Timestamp>, anyhow::Error> {
1335    let row = client
1336        .query_one(
1337            &format!("EXPLAIN TIMESTAMP AS JSON FOR SELECT * FROM {from_suffix}"),
1338            &[],
1339        )
1340        .await?;
1341    let explain: String = row.get(0);
1342    Ok(serde_json::from_str(&explain).unwrap())
1343}
1344
1345/// Helper function to create a Postgres source.
1346///
1347/// IMPORTANT: Make sure to call closure that is returned at the end of the test to clean up
1348/// Postgres state.
1349///
1350/// WARNING: If multiple tests use this, and the tests are run in parallel, then make sure the test
1351/// use different postgres tables.
1352pub async fn create_postgres_source_with_table<'a>(
1353    server: &TestServer,
1354    mz_client: &Client,
1355    table_name: &str,
1356    table_schema: &str,
1357    source_name: &str,
1358) -> (
1359    Client,
1360    impl FnOnce(&'a Client, &'a Client) -> LocalBoxFuture<'a, ()>,
1361) {
1362    server
1363        .enable_feature_flags(&["enable_create_table_from_source"])
1364        .await;
1365
1366    let postgres_url = env::var("POSTGRES_URL")
1367        .map_err(|_| anyhow!("POSTGRES_URL environment variable is not set"))
1368        .unwrap();
1369
1370    let (pg_client, connection) = tokio_postgres::connect(&postgres_url, postgres::NoTls)
1371        .await
1372        .unwrap();
1373
1374    let pg_config: tokio_postgres::Config = postgres_url.parse().unwrap();
1375    let user = pg_config.get_user().unwrap_or("postgres");
1376    let db_name = pg_config.get_dbname().unwrap_or(user);
1377    let ports = pg_config.get_ports();
1378    let port = if ports.is_empty() { 5432 } else { ports[0] };
1379    let hosts = pg_config.get_hosts();
1380    let host = if hosts.is_empty() {
1381        "localhost".to_string()
1382    } else {
1383        match &hosts[0] {
1384            Host::Tcp(host) => host.to_string(),
1385            Host::Unix(host) => host.to_str().unwrap().to_string(),
1386        }
1387    };
1388    let password = pg_config.get_password();
1389
1390    mz_ore::task::spawn(|| "postgres-source-connection", async move {
1391        if let Err(e) = connection.await {
1392            panic!("connection error: {}", e);
1393        }
1394    });
1395
1396    // Create table in Postgres with publication.
1397    let _ = pg_client
1398        .execute(&format!("DROP TABLE IF EXISTS {table_name};"), &[])
1399        .await
1400        .unwrap();
1401    let _ = pg_client
1402        .execute(&format!("DROP PUBLICATION IF EXISTS {source_name};"), &[])
1403        .await
1404        .unwrap();
1405    let _ = pg_client
1406        .execute(&format!("CREATE TABLE {table_name} {table_schema};"), &[])
1407        .await
1408        .unwrap();
1409    let _ = pg_client
1410        .execute(
1411            &format!("ALTER TABLE {table_name} REPLICA IDENTITY FULL;"),
1412            &[],
1413        )
1414        .await
1415        .unwrap();
1416    let _ = pg_client
1417        .execute(
1418            &format!("CREATE PUBLICATION {source_name} FOR TABLE {table_name};"),
1419            &[],
1420        )
1421        .await
1422        .unwrap();
1423
1424    // Create postgres source in Materialize.
1425    let mut connection_str = format!("HOST '{host}', PORT {port}, USER {user}, DATABASE {db_name}");
1426    if let Some(password) = password {
1427        let password = std::str::from_utf8(password).unwrap();
1428        mz_client
1429            .batch_execute(&format!("CREATE SECRET s AS '{password}'"))
1430            .await
1431            .unwrap();
1432        connection_str = format!("{connection_str}, PASSWORD SECRET s");
1433    }
1434    mz_client
1435        .batch_execute(&format!(
1436            "CREATE CONNECTION pgconn TO POSTGRES ({connection_str})"
1437        ))
1438        .await
1439        .unwrap();
1440    mz_client
1441        .batch_execute(&format!(
1442            "CREATE SOURCE {source_name}
1443            FROM POSTGRES
1444            CONNECTION pgconn
1445            (PUBLICATION '{source_name}')"
1446        ))
1447        .await
1448        .unwrap();
1449    mz_client
1450        .batch_execute(&format!(
1451            "CREATE TABLE {table_name}
1452            FROM SOURCE {source_name}
1453            (REFERENCE {table_name});"
1454        ))
1455        .await
1456        .unwrap();
1457
1458    let table_name = table_name.to_string();
1459    let source_name = source_name.to_string();
1460    (
1461        pg_client,
1462        move |mz_client: &'a Client, pg_client: &'a Client| {
1463            let f: Pin<Box<dyn Future<Output = ()> + 'a>> = Box::pin(async move {
1464                mz_client
1465                    .batch_execute(&format!("DROP SOURCE {source_name} CASCADE;"))
1466                    .await
1467                    .unwrap();
1468                mz_client
1469                    .batch_execute("DROP CONNECTION pgconn;")
1470                    .await
1471                    .unwrap();
1472
1473                let _ = pg_client
1474                    .execute(&format!("DROP PUBLICATION {source_name};"), &[])
1475                    .await
1476                    .unwrap();
1477                let _ = pg_client
1478                    .execute(&format!("DROP TABLE {table_name};"), &[])
1479                    .await
1480                    .unwrap();
1481            });
1482            f
1483        },
1484    )
1485}
1486
1487pub async fn wait_for_pg_table_population(mz_client: &Client, view_name: &str, source_rows: i64) {
1488    let current_isolation = mz_client
1489        .query_one("SHOW transaction_isolation", &[])
1490        .await
1491        .unwrap()
1492        .get::<_, String>(0);
1493    mz_client
1494        .batch_execute("SET transaction_isolation = SERIALIZABLE")
1495        .await
1496        .unwrap();
1497    Retry::default()
1498        .retry_async(|_| async move {
1499            let rows = mz_client
1500                .query_one(&format!("SELECT COUNT(*) FROM {view_name};"), &[])
1501                .await
1502                .unwrap()
1503                .get::<_, i64>(0);
1504            if rows == source_rows {
1505                Ok(())
1506            } else {
1507                Err(format!(
1508                    "Waiting for {source_rows} row to be ingested. Currently at {rows}."
1509                ))
1510            }
1511        })
1512        .await
1513        .unwrap();
1514    mz_client
1515        .batch_execute(&format!(
1516            "SET transaction_isolation = '{current_isolation}'"
1517        ))
1518        .await
1519        .unwrap();
1520}
1521
1522// Initializes a websocket connection. Returns the init messages before the initial ReadyForQuery.
1523pub fn auth_with_ws(
1524    ws: &mut WebSocket<MaybeTlsStream<TcpStream>>,
1525    mut options: BTreeMap<String, String>,
1526) -> Result<Vec<WebSocketResponse>, anyhow::Error> {
1527    if !options.contains_key("welcome_message") {
1528        options.insert("welcome_message".into(), "off".into());
1529    }
1530    auth_with_ws_impl(
1531        ws,
1532        Message::Text(
1533            serde_json::to_string(&WebSocketAuth::Basic {
1534                user: "materialize".into(),
1535                password: "".into(),
1536                options,
1537            })
1538            .unwrap()
1539            .into(),
1540        ),
1541    )
1542}
1543
1544pub fn auth_with_ws_impl(
1545    ws: &mut WebSocket<MaybeTlsStream<TcpStream>>,
1546    auth_message: Message,
1547) -> Result<Vec<WebSocketResponse>, anyhow::Error> {
1548    ws.send(auth_message)?;
1549
1550    // Wait for initial ready response.
1551    let mut msgs = Vec::new();
1552    loop {
1553        let resp = ws.read()?;
1554        match resp {
1555            Message::Text(msg) => {
1556                let msg: WebSocketResponse = serde_json::from_str(&msg).unwrap();
1557                match msg {
1558                    WebSocketResponse::ReadyForQuery(_) => break,
1559                    msg => {
1560                        msgs.push(msg);
1561                    }
1562                }
1563            }
1564            Message::Ping(_) => continue,
1565            Message::Close(None) => return Err(anyhow!("ws closed after auth")),
1566            Message::Close(Some(close_frame)) => {
1567                return Err(anyhow!("ws closed after auth").context(close_frame));
1568            }
1569            _ => panic!("unexpected response: {:?}", resp),
1570        }
1571    }
1572    Ok(msgs)
1573}
1574
1575pub fn make_header<H: Header>(h: H) -> HeaderMap {
1576    let mut map = HeaderMap::new();
1577    map.typed_insert(h);
1578    map
1579}
1580
1581pub fn make_pg_tls<F>(configure: F) -> MakeTlsConnector
1582where
1583    F: FnOnce(&mut SslConnectorBuilder) -> Result<(), ErrorStack>,
1584{
1585    let mut connector_builder = SslConnector::builder(SslMethod::tls()).unwrap();
1586    // Disable TLS v1.3 because `postgres` and `hyper` produce stabler error
1587    // messages with TLS v1.2.
1588    //
1589    // Briefly, in TLS v1.3, failing to present a client certificate does not
1590    // error during the TLS handshake, as it does in TLS v1.2, but on the first
1591    // attempt to read from the stream. But both `postgres` and `hyper` write a
1592    // bunch of data before attempting to read from the stream. With a failed
1593    // TLS v1.3 connection, sometimes `postgres` and `hyper` succeed in writing
1594    // out this data, and then return a nice error message on the call to read.
1595    // But sometimes the connection is closed before they write out the data,
1596    // and so they report "connection closed" before they ever call read, never
1597    // noticing the underlying SSL error.
1598    //
1599    // It's unclear who's bug this is. Is it on `hyper`/`postgres` to call read
1600    // if writing to the stream fails to see if a TLS error occured? Is it on
1601    // OpenSSL to provide a better API [1]? Is it a protocol issue that ought to
1602    // be corrected in TLS v1.4? We don't want to answer these questions, so we
1603    // just avoid TLS v1.3 for now.
1604    //
1605    // [1]: https://github.com/openssl/openssl/issues/11118
1606    let options = connector_builder.options() | SslOptions::NO_TLSV1_3;
1607    connector_builder.set_options(options);
1608    configure(&mut connector_builder).unwrap();
1609    MakeTlsConnector::new(connector_builder.build())
1610}
1611
1612/// A certificate authority for use in tests.
1613pub struct Ca {
1614    pub dir: TempDir,
1615    pub name: X509Name,
1616    pub cert: X509,
1617    pub pkey: PKey<Private>,
1618}
1619
1620impl Ca {
1621    fn make_ca(name: &str, parent: Option<&Ca>) -> Result<Ca, Box<dyn Error>> {
1622        let dir = tempfile::tempdir()?;
1623        let rsa = Rsa::generate(2048)?;
1624        let pkey = PKey::from_rsa(rsa)?;
1625        let name = {
1626            let mut builder = X509NameBuilder::new()?;
1627            builder.append_entry_by_nid(Nid::COMMONNAME, name)?;
1628            builder.build()
1629        };
1630        let cert = {
1631            let mut builder = X509::builder()?;
1632            builder.set_version(2)?;
1633            builder.set_pubkey(&pkey)?;
1634            builder.set_issuer_name(parent.map(|ca| &ca.name).unwrap_or(&name))?;
1635            builder.set_subject_name(&name)?;
1636            builder.set_not_before(&*Asn1Time::days_from_now(0)?)?;
1637            builder.set_not_after(&*Asn1Time::days_from_now(365)?)?;
1638            builder.append_extension(BasicConstraints::new().critical().ca().build()?)?;
1639            builder.sign(
1640                parent.map(|ca| &ca.pkey).unwrap_or(&pkey),
1641                MessageDigest::sha256(),
1642            )?;
1643            builder.build()
1644        };
1645        fs::write(dir.path().join("ca.crt"), cert.to_pem()?)?;
1646        Ok(Ca {
1647            dir,
1648            name,
1649            cert,
1650            pkey,
1651        })
1652    }
1653
1654    /// Creates a new root certificate authority.
1655    pub fn new_root(name: &str) -> Result<Ca, Box<dyn Error>> {
1656        Ca::make_ca(name, None)
1657    }
1658
1659    /// Returns the path to the CA's certificate.
1660    pub fn ca_cert_path(&self) -> PathBuf {
1661        self.dir.path().join("ca.crt")
1662    }
1663
1664    /// Requests a new intermediate certificate authority.
1665    pub fn request_ca(&self, name: &str) -> Result<Ca, Box<dyn Error>> {
1666        Ca::make_ca(name, Some(self))
1667    }
1668
1669    /// Generates a certificate with the specified Common Name (CN) that is
1670    /// signed by the CA.
1671    ///
1672    /// Returns the paths to the certificate and key.
1673    pub fn request_client_cert(&self, name: &str) -> Result<(PathBuf, PathBuf), Box<dyn Error>> {
1674        self.request_cert(name, iter::empty())
1675    }
1676
1677    /// Like `request_client_cert`, but permits specifying additional IP
1678    /// addresses to attach as Subject Alternate Names.
1679    pub fn request_cert<I>(&self, name: &str, ips: I) -> Result<(PathBuf, PathBuf), Box<dyn Error>>
1680    where
1681        I: IntoIterator<Item = IpAddr>,
1682    {
1683        let rsa = Rsa::generate(2048)?;
1684        let pkey = PKey::from_rsa(rsa)?;
1685        let subject_name = {
1686            let mut builder = X509NameBuilder::new()?;
1687            builder.append_entry_by_nid(Nid::COMMONNAME, name)?;
1688            builder.build()
1689        };
1690        let cert = {
1691            let mut builder = X509::builder()?;
1692            builder.set_version(2)?;
1693            builder.set_pubkey(&pkey)?;
1694            builder.set_issuer_name(self.cert.subject_name())?;
1695            builder.set_subject_name(&subject_name)?;
1696            builder.set_not_before(&*Asn1Time::days_from_now(0)?)?;
1697            builder.set_not_after(&*Asn1Time::days_from_now(365)?)?;
1698            for ip in ips {
1699                builder.append_extension(
1700                    SubjectAlternativeName::new()
1701                        .ip(&ip.to_string())
1702                        .build(&builder.x509v3_context(None, None))?,
1703                )?;
1704            }
1705            builder.sign(&self.pkey, MessageDigest::sha256())?;
1706            builder.build()
1707        };
1708        let cert_path = self.dir.path().join(Path::new(name).with_extension("crt"));
1709        let key_path = self.dir.path().join(Path::new(name).with_extension("key"));
1710        fs::write(&cert_path, cert.to_pem()?)?;
1711        fs::write(&key_path, pkey.private_key_to_pem_pkcs8()?)?;
1712        Ok((cert_path, key_path))
1713    }
1714}