Skip to main content

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