Skip to main content

mz_balancerd/
lib.rs

1// Copyright Materialize, Inc. and contributors. All rights reserved.
2//
3// Use of this software is governed by the Business Source License
4// included in the LICENSE file.
5//
6// As of the Change Date specified in that file, in accordance with
7// the Business Source License, use of this software will be governed
8// by the Apache License, Version 2.0.
9
10//! The balancerd service is a horizontally scalable, stateless, multi-tenant ingress router for
11//! pgwire and HTTPS connections.
12//!
13//! It listens on pgwire and HTTPS ports. When a new pgwire connection starts, the requested user is
14//! authenticated with frontegg from which a tenant id is returned. From that a target internal
15//! hostname is resolved to an IP address, and the connection is proxied to that address which has a
16//! running environmentd's pgwire port. When a new HTTPS connection starts, its SNI hostname is used
17//! to generate an internal hostname that is resolved to an IP address, which is similarly proxied.
18
19mod codec;
20mod dyncfgs;
21
22use std::collections::BTreeMap;
23use std::net::SocketAddr;
24use std::path::PathBuf;
25use std::pin::Pin;
26use std::str::FromStr;
27use std::sync::Arc;
28use std::time::{Duration, Instant};
29
30use anyhow::Context;
31use axum::response::IntoResponse;
32use axum::{Router, routing};
33use bytes::BytesMut;
34use domain::base::{Name, Rtype};
35use domain::rdata::AllRecordData;
36use domain::resolv::StubResolver;
37use futures::TryFutureExt;
38use futures::stream::BoxStream;
39use hyper::StatusCode;
40use hyper_util::rt::TokioIo;
41use launchdarkly_server_sdk as ld;
42use mz_build_info::{BuildInfo, build_info};
43use mz_dyncfg::ConfigSet;
44use mz_frontegg_auth::Authenticator as FronteggAuthentication;
45use mz_ore::cast::CastFrom;
46use mz_ore::id_gen::conn_id_org_uuid;
47use mz_ore::metrics::{ComputedGauge, IntCounter, IntGauge, MetricsRegistry};
48use mz_ore::netio::AsyncReady;
49use mz_ore::now::{NowFn, SYSTEM_TIME, epoch_to_uuid_v7};
50use mz_ore::task::{JoinSetExt, spawn};
51use mz_ore::tracing::TracingHandle;
52use mz_ore::{metric, netio};
53use mz_pgwire_common::{
54    ACCEPT_SSL_ENCRYPTION, CONN_UUID_KEY, Conn, ErrorResponse, FrontendMessage,
55    FrontendStartupMessage, MZ_FORWARDED_FOR_KEY, REJECT_ENCRYPTION, VERSION_3, decode_startup,
56};
57use mz_server_core::{
58    Connection, ConnectionStream, ListenerHandle, ReloadTrigger, ReloadingSslContext,
59    ReloadingTlsConfig, ServeConfig, ServeDyncfg, TlsCertConfig, TlsMode, listen,
60};
61use openssl::ssl::{NameType, Ssl, SslConnector, SslMethod, SslVerifyMode};
62use prometheus::{IntCounterVec, IntGaugeVec};
63use proxy_header::{ProxiedAddress, ProxyHeader};
64use semver::Version;
65use tokio::io::{self, AsyncRead, AsyncWrite, AsyncWriteExt};
66use tokio::net::TcpStream;
67use tokio::sync::oneshot;
68use tokio::task::JoinSet;
69use tokio_metrics::TaskMetrics;
70use tokio_openssl::SslStream;
71use tokio_postgres::error::SqlState;
72use tower::Service;
73use tracing::{debug, error, warn};
74use uuid::Uuid;
75
76use crate::codec::{BackendMessage, FramedConn};
77use crate::dyncfgs::{
78    INJECT_PROXY_PROTOCOL_HEADER_HTTP, SIGTERM_CONNECTION_WAIT, SIGTERM_LISTEN_WAIT,
79    has_tracing_config_update, tracing_config,
80};
81
82/// Balancer build information.
83pub const BUILD_INFO: BuildInfo = build_info!();
84
85pub struct BalancerConfig {
86    /// Info about which version of the code is running.
87    build_version: Version,
88    /// Listen address for internal HTTP health and metrics server.
89    internal_http_listen_addr: SocketAddr,
90    /// Listen address for pgwire connections.
91    pgwire_listen_addr: SocketAddr,
92    /// Listen address for HTTPS connections.
93    https_listen_addr: SocketAddr,
94    /// DNS resolver for pgwire cancellation requests
95    cancellation_resolver: CancellationResolver,
96    /// DNS resolver.
97    resolver: Resolver,
98    https_sni_addr_template: String,
99    tls: Option<TlsCertConfig>,
100    internal_tls: bool,
101    metrics_registry: MetricsRegistry,
102    reload_certs: BoxStream<'static, Option<oneshot::Sender<Result<(), anyhow::Error>>>>,
103    launchdarkly_sdk_key: Option<String>,
104    config_sync_file_path: Option<PathBuf>,
105    config_sync_timeout: Duration,
106    config_sync_loop_interval: Option<Duration>,
107    cloud_provider: Option<String>,
108    cloud_provider_region: Option<String>,
109    tracing_handle: TracingHandle,
110    default_configs: Vec<(String, String)>,
111}
112
113impl BalancerConfig {
114    pub fn new(
115        build_info: &BuildInfo,
116        internal_http_listen_addr: SocketAddr,
117        pgwire_listen_addr: SocketAddr,
118        https_listen_addr: SocketAddr,
119        cancellation_resolver: CancellationResolver,
120        resolver: Resolver,
121        https_sni_addr_template: String,
122        tls: Option<TlsCertConfig>,
123        internal_tls: bool,
124        metrics_registry: MetricsRegistry,
125        reload_certs: ReloadTrigger,
126        launchdarkly_sdk_key: Option<String>,
127        config_sync_file: Option<PathBuf>,
128        config_sync_timeout: Duration,
129        config_sync_loop_interval: Option<Duration>,
130        cloud_provider: Option<String>,
131        cloud_provider_region: Option<String>,
132        tracing_handle: TracingHandle,
133        default_configs: Vec<(String, String)>,
134    ) -> Self {
135        Self {
136            build_version: build_info.semver_version(),
137            internal_http_listen_addr,
138            pgwire_listen_addr,
139            https_listen_addr,
140            cancellation_resolver,
141            resolver,
142            https_sni_addr_template,
143            tls,
144            internal_tls,
145            metrics_registry,
146            reload_certs,
147            launchdarkly_sdk_key,
148            config_sync_file_path: config_sync_file,
149            config_sync_timeout,
150            config_sync_loop_interval,
151            cloud_provider,
152            cloud_provider_region,
153            tracing_handle,
154            default_configs,
155        }
156    }
157}
158
159/// Prometheus monitoring metrics.
160#[derive(Debug)]
161pub struct BalancerMetrics {
162    _uptime: ComputedGauge,
163}
164
165impl BalancerMetrics {
166    /// Returns a new [BalancerMetrics] instance connected to the registry in cfg.
167    pub fn new(cfg: &BalancerConfig) -> Self {
168        let start = Instant::now();
169        let uptime = cfg.metrics_registry.register_computed_gauge(
170            metric!(
171                name: "mz_balancer_metadata_seconds",
172                help: "server uptime, labels are build metadata",
173                const_labels: {
174                    "version" => cfg.build_version,
175                    "build_type" => if cfg!(release) { "release" } else { "debug" }
176                },
177            ),
178            move || start.elapsed().as_secs_f64(),
179        );
180        BalancerMetrics { _uptime: uptime }
181    }
182}
183
184pub struct BalancerService {
185    cfg: BalancerConfig,
186    pub pgwire: (ListenerHandle, Pin<Box<dyn ConnectionStream>>),
187    pub https: (ListenerHandle, Pin<Box<dyn ConnectionStream>>),
188    pub internal_http: (ListenerHandle, Pin<Box<dyn ConnectionStream>>),
189    _metrics: BalancerMetrics,
190    configs: ConfigSet,
191}
192
193impl BalancerService {
194    pub async fn new(cfg: BalancerConfig) -> Result<Self, anyhow::Error> {
195        let pgwire = listen(&cfg.pgwire_listen_addr).await?;
196        let https = listen(&cfg.https_listen_addr).await?;
197        let internal_http = listen(&cfg.internal_http_listen_addr).await?;
198        let metrics = BalancerMetrics::new(&cfg);
199        let mut configs = ConfigSet::default();
200        configs = dyncfgs::all_dyncfgs(configs);
201        dyncfgs::set_defaults(&configs, cfg.default_configs.clone())?;
202        let tracing_handle = cfg.tracing_handle.clone();
203        // Configure dyncfg sync
204        match (
205            cfg.launchdarkly_sdk_key.as_deref(),
206            cfg.config_sync_file_path.as_deref(),
207        ) {
208            (Some(key), None) => {
209                mz_dyncfg_launchdarkly::sync_launchdarkly_to_configset(
210                    configs.clone(),
211                    &BUILD_INFO,
212                    |builder| {
213                        let region = cfg
214                            .cloud_provider_region
215                            .clone()
216                            .unwrap_or_else(|| String::from("unknown"));
217                        if let Some(provider) = cfg.cloud_provider.clone() {
218                            builder.add_context(
219                                ld::ContextBuilder::new(format!(
220                                    "{}/{}/{}",
221                                    provider, region, cfg.build_version
222                                ))
223                                .kind("balancer")
224                                .set_string("provider", provider)
225                                .set_string("region", region)
226                                .set_string("version", cfg.build_version.to_string())
227                                .build()
228                                .map_err(|e| anyhow::anyhow!(e))?,
229                            );
230                        } else {
231                            builder.add_context(
232                                ld::ContextBuilder::new(format!(
233                                    "{}/{}/{}",
234                                    "unknown", region, cfg.build_version
235                                ))
236                                .anonymous(true) // exclude this user from the dashboard
237                                .kind("balancer")
238                                .set_string("provider", "unknown")
239                                .set_string("region", region)
240                                .set_string("version", cfg.build_version.to_string())
241                                .build()
242                                .map_err(|e| anyhow::anyhow!(e))?,
243                            );
244                        }
245                        Ok(())
246                    },
247                    Some(key),
248                    cfg.config_sync_timeout,
249                    cfg.config_sync_loop_interval,
250                    move |updates, configs| {
251                        if has_tracing_config_update(updates) {
252                            match tracing_config(configs) {
253                                Ok(parameters) => parameters.apply(&tracing_handle),
254                                Err(err) => warn!("unable to update tracing: {err}"),
255                            }
256                        }
257                    },
258                )
259                .await
260                .inspect_err(|e| warn!("LaunchDarkly sync error: {e}"))
261                .ok();
262            }
263            (None, Some(path)) => {
264                mz_dyncfg_file::sync_file_to_configset(
265                    configs.clone(),
266                    path,
267                    cfg.config_sync_timeout,
268                    cfg.config_sync_loop_interval,
269                    move |updates, configs| {
270                        if has_tracing_config_update(updates) {
271                            match tracing_config(configs) {
272                                Ok(parameters) => parameters.apply(&tracing_handle),
273                                Err(err) => warn!("unable to update tracing: {err}"),
274                            }
275                        }
276                    },
277                )
278                .await
279                // If there's an Error, log but continue anyway. If LD is down
280                // we have no way of fetching the previous value of the flag
281                // (unlike the adapter, but it has a durable catalog). The
282                // ConfigSet defaults have been chosen to be good enough if this
283                // is the case.
284                .inspect_err(|e| warn!("File config sync error: {e}"))
285                .ok();
286            }
287            (Some(_), Some(_)) => panic!(
288                "must provide either config_sync_file_path or launchdarkly_sdk_key for config syncing",
289            ),
290            (None, None) => {}
291        };
292        Ok(Self {
293            cfg,
294            pgwire,
295            https,
296            internal_http,
297            _metrics: metrics,
298            configs,
299        })
300    }
301
302    pub async fn serve(self) -> Result<(), anyhow::Error> {
303        let (pgwire_tls, https_tls) = match &self.cfg.tls {
304            Some(tls) => {
305                let context = tls.reloading_context(self.cfg.reload_certs)?;
306                (
307                    Some(ReloadingTlsConfig {
308                        context: context.clone(),
309                        mode: TlsMode::Require,
310                    }),
311                    Some(context),
312                )
313            }
314            None => (None, None),
315        };
316
317        let metrics = ServerMetricsConfig::register_into(&self.cfg.metrics_registry);
318
319        let mut set = JoinSet::new();
320        let mut server_handles = Vec::new();
321        let pgwire_addr = self.pgwire.0.local_addr();
322        let https_addr = self.https.0.local_addr();
323        let internal_http_addr = self.internal_http.0.local_addr();
324
325        {
326            let pgwire = PgwireBalancer {
327                resolver: Arc::new(self.cfg.resolver),
328                cancellation_resolver: Arc::new(self.cfg.cancellation_resolver),
329                tls: pgwire_tls,
330                internal_tls: self.cfg.internal_tls,
331                metrics: ServerMetrics::new(metrics.clone(), "pgwire"),
332                now: SYSTEM_TIME.clone(),
333            };
334            let (handle, stream) = self.pgwire;
335            server_handles.push(handle);
336            set.spawn_named(|| "pgwire_stream", {
337                let config_set = self.configs.clone();
338                async move {
339                    mz_server_core::serve(ServeConfig {
340                        server: pgwire,
341                        conns: stream,
342                        dyncfg: Some(ServeDyncfg {
343                            config_set,
344                            sigterm_wait_config: &SIGTERM_CONNECTION_WAIT,
345                        }),
346                    })
347                    .await;
348                    warn!("pgwire server exited");
349                }
350            });
351        }
352        {
353            let Some((addr, port)) = self.cfg.https_sni_addr_template.split_once(':') else {
354                panic!("expected port in https_addr_template");
355            };
356            let port: u16 = port.parse().expect("unexpected port");
357            let resolver = StubResolver::new();
358            let https = HttpsBalancer {
359                resolver: Arc::from(resolver),
360                tls: https_tls,
361                resolve_template: Arc::from(addr),
362                port,
363                metrics: Arc::from(ServerMetrics::new(metrics, "https")),
364                configs: self.configs.clone(),
365                internal_tls: self.cfg.internal_tls,
366            };
367            let (handle, stream) = self.https;
368            server_handles.push(handle);
369            set.spawn_named(|| "https_stream", {
370                let config_set = self.configs.clone();
371                async move {
372                    mz_server_core::serve(ServeConfig {
373                        server: https,
374                        conns: stream,
375                        dyncfg: Some(ServeDyncfg {
376                            config_set,
377                            sigterm_wait_config: &SIGTERM_CONNECTION_WAIT,
378                        }),
379                    })
380                    .await;
381                    warn!("https server exited");
382                }
383            });
384        }
385        {
386            let router = Router::new()
387                .route(
388                    "/metrics",
389                    routing::get(move || async move {
390                        mz_http_util::handle_prometheus(&self.cfg.metrics_registry).await
391                    }),
392                )
393                .route(
394                    "/api/livez",
395                    routing::get(mz_http_util::handle_liveness_check),
396                )
397                .route("/api/readyz", routing::get(handle_readiness_check));
398            let internal_http = InternalHttpServer { router };
399            let (handle, stream) = self.internal_http;
400            server_handles.push(handle);
401            set.spawn_named(|| "internal_http_stream", async move {
402                mz_server_core::serve(ServeConfig {
403                    server: internal_http,
404                    conns: stream,
405                    // Disable graceful termination because our internal
406                    // monitoring keeps persistent HTTP connections open.
407                    dyncfg: None,
408                })
409                .await;
410                warn!("internal_http server exited");
411            });
412        }
413        #[cfg(unix)]
414        {
415            let mut sigterm =
416                tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())?;
417            set.spawn_named(|| "sigterm_handler", async move {
418                sigterm.recv().await;
419                let wait = SIGTERM_LISTEN_WAIT.get(&self.configs);
420                warn!("received signal TERM - delaying for {:?}!", wait);
421                tokio::time::sleep(wait).await;
422                warn!("sigterm delay complete, dropping server handles");
423                drop(server_handles);
424            });
425        }
426
427        println!("balancerd {} listening...", BUILD_INFO.human_version(None));
428        println!(" TLS enabled: {}", self.cfg.tls.is_some());
429        println!(" pgwire address: {}", pgwire_addr);
430        println!(" HTTPS address: {}", https_addr);
431        println!(" internal HTTP address: {}", internal_http_addr);
432
433        // Wait for all tasks to exit, which can happen on SIGTERM.
434        while let Some(res) = set.join_next().await {
435            if let Err(err) = res {
436                error!("serving task failed: {err}")
437            }
438        }
439        Ok(())
440    }
441}
442
443#[allow(clippy::unused_async)]
444async fn handle_readiness_check() -> impl IntoResponse {
445    (StatusCode::OK, "ready")
446}
447
448struct InternalHttpServer {
449    router: Router,
450}
451
452impl mz_server_core::Server for InternalHttpServer {
453    const NAME: &'static str = "internal_http";
454
455    // TODO(jkosh44) consider forwarding the connection UUID to the adapter.
456    fn handle_connection(
457        &self,
458        conn: Connection,
459        _tokio_metrics_intervals: impl Iterator<Item = TaskMetrics> + Send + 'static,
460    ) -> mz_server_core::ConnectionHandler {
461        let router = self.router.clone();
462        let service = hyper::service::service_fn(move |req| router.clone().call(req));
463        let conn = TokioIo::new(conn);
464
465        Box::pin(async {
466            let http = hyper::server::conn::http1::Builder::new();
467            http.serve_connection(conn, service).err_into().await
468        })
469    }
470}
471
472/// Wraps an IntGauge and automatically `inc`s on init and `drop`s on drop. Callers should not call
473/// `inc().`. Useful for handling multiple task exit points, for example in the case of a panic.
474struct GaugeGuard {
475    gauge: IntGauge,
476}
477
478impl From<IntGauge> for GaugeGuard {
479    fn from(gauge: IntGauge) -> Self {
480        let _self = Self { gauge };
481        _self.gauge.inc();
482        _self
483    }
484}
485
486impl Drop for GaugeGuard {
487    fn drop(&mut self) {
488        self.gauge.dec();
489    }
490}
491
492#[derive(Clone, Debug)]
493struct ServerMetricsConfig {
494    connection_status: IntCounterVec,
495    active_connections: IntGaugeVec,
496    tenant_connections: IntGaugeVec,
497    tenant_connection_rx: IntCounterVec,
498    tenant_connection_tx: IntCounterVec,
499    tenant_pgwire_sni_count: IntCounterVec,
500}
501
502impl ServerMetricsConfig {
503    fn register_into(registry: &MetricsRegistry) -> Self {
504        let connection_status = registry.register(metric!(
505            name: "mz_balancer_connection_status",
506            help: "Count of completed network connections, by status",
507            var_labels: ["source", "status"],
508        ));
509        let active_connections = registry.register(metric!(
510            name: "mz_balancer_connection_active",
511            help: "Count of currently open network connections.",
512            var_labels: ["source"],
513        ));
514        let tenant_connections = registry.register(metric!(
515            name: "mz_balancer_tenant_connection_active",
516            help: "Count of opened network connections by tenant.",
517            var_labels: ["source",  "tenant"]
518        ));
519        let tenant_connection_rx = registry.register(metric!(
520            name: "mz_balancer_tenant_connection_rx",
521            help: "Number of bytes received from a client for a tenant.",
522            var_labels: ["source", "tenant"],
523        ));
524        let tenant_connection_tx = registry.register(metric!(
525            name: "mz_balancer_tenant_connection_tx",
526            help: "Number of bytes sent to a client for a tenant.",
527            var_labels: ["source", "tenant"],
528        ));
529        let tenant_pgwire_sni_count = registry.register(metric!(
530            name: "mz_balancer_tenant_pgwire_sni_count",
531            help: "Count of pgwire connections that have and do not have SNI available per tenant.",
532            var_labels: ["tenant", "has_sni"],
533        ));
534        Self {
535            connection_status,
536            active_connections,
537            tenant_connections,
538            tenant_connection_rx,
539            tenant_connection_tx,
540            tenant_pgwire_sni_count,
541        }
542    }
543}
544
545#[derive(Clone, Debug)]
546struct ServerMetrics {
547    inner: ServerMetricsConfig,
548    source: &'static str,
549}
550
551impl ServerMetrics {
552    fn new(inner: ServerMetricsConfig, source: &'static str) -> Self {
553        let self_ = Self { inner, source };
554
555        // Pre-initialize labels we are planning to use to ensure they are all always emitted as
556        // time series.
557        self_.connection_status(false);
558        self_.connection_status(true);
559        drop(self_.active_connections());
560
561        self_
562    }
563
564    fn connection_status(&self, is_ok: bool) -> IntCounter {
565        self.inner
566            .connection_status
567            .with_label_values(&[self.source, Self::status_label(is_ok)])
568    }
569
570    fn active_connections(&self) -> GaugeGuard {
571        self.inner
572            .active_connections
573            .with_label_values(&[self.source])
574            .into()
575    }
576
577    fn tenant_connections(&self, tenant: &str) -> GaugeGuard {
578        self.inner
579            .tenant_connections
580            .with_label_values(&[self.source, tenant])
581            .into()
582    }
583
584    fn tenant_connections_rx(&self, tenant: &str) -> IntCounter {
585        self.inner
586            .tenant_connection_rx
587            .with_label_values(&[self.source, tenant])
588    }
589
590    fn tenant_connections_tx(&self, tenant: &str) -> IntCounter {
591        self.inner
592            .tenant_connection_tx
593            .with_label_values(&[self.source, tenant])
594    }
595
596    fn tenant_pgwire_sni_count(&self, tenant: &str, has_sni: bool) -> IntCounter {
597        self.inner
598            .tenant_pgwire_sni_count
599            .with_label_values(&[tenant, &has_sni.to_string()])
600    }
601
602    fn status_label(is_ok: bool) -> &'static str {
603        if is_ok { "success" } else { "error" }
604    }
605}
606
607pub enum CancellationResolver {
608    Directory(PathBuf),
609    Static(String),
610}
611
612struct PgwireBalancer {
613    tls: Option<ReloadingTlsConfig>,
614    internal_tls: bool,
615    cancellation_resolver: Arc<CancellationResolver>,
616    resolver: Arc<Resolver>,
617    metrics: ServerMetrics,
618    now: NowFn,
619}
620
621impl PgwireBalancer {
622    #[mz_ore::instrument(level = "debug")]
623    async fn run<'a, A>(
624        conn: &'a mut FramedConn<A>,
625        version: i32,
626        params: BTreeMap<String, String>,
627        resolver: &Resolver,
628        tls_mode: Option<TlsMode>,
629        internal_tls: bool,
630        metrics: &ServerMetrics,
631    ) -> Result<(), io::Error>
632    where
633        A: AsyncRead + AsyncWrite + AsyncReady + Send + Sync + Unpin,
634    {
635        if version != VERSION_3 {
636            return conn
637                .send(ErrorResponse::fatal(
638                    SqlState::SQLSERVER_REJECTED_ESTABLISHMENT_OF_SQLCONNECTION,
639                    "server does not support the client's requested protocol version",
640                ))
641                .await;
642        }
643
644        let Some(user) = params.get("user") else {
645            return conn
646                .send(ErrorResponse::fatal(
647                    SqlState::SQLSERVER_REJECTED_ESTABLISHMENT_OF_SQLCONNECTION,
648                    "user parameter required",
649                ))
650                .await;
651        };
652
653        if let Err(err) = conn.inner().ensure_tls_compatibility(&tls_mode) {
654            return conn.send(err).await;
655        }
656
657        let resolved = match resolver.resolve(conn, user, metrics).await {
658            Ok(v) => v,
659            Err(err) => {
660                return conn
661                    .send(ErrorResponse::fatal(
662                        SqlState::INVALID_PASSWORD,
663                        err.to_string(),
664                    ))
665                    .await;
666            }
667        };
668
669        let _active_guard = resolved
670            .tenant
671            .as_ref()
672            .map(|tenant| metrics.tenant_connections(tenant));
673        let mut mz_stream =
674            match Self::init_stream(conn, resolved.addr, resolved.password, params, internal_tls)
675                .await
676            {
677                Ok(stream) => stream,
678                Err(e) => {
679                    error!("failed to connect to upstream server: {e}");
680                    return conn
681                        .send(ErrorResponse::fatal(
682                            SqlState::SQLSERVER_REJECTED_ESTABLISHMENT_OF_SQLCONNECTION,
683                            "upstream server not available",
684                        ))
685                        .await;
686                }
687            };
688
689        let mut client_counter = CountingConn::new(conn.inner_mut());
690
691        // Now blindly shuffle bytes back and forth until closed.
692        // TODO: Limit total memory use.
693        let res = tokio::io::copy_bidirectional(&mut client_counter, &mut mz_stream).await;
694        if let Some(tenant) = &resolved.tenant {
695            metrics
696                .tenant_connections_tx(tenant)
697                .inc_by(u64::cast_from(client_counter.written));
698            metrics
699                .tenant_connections_rx(tenant)
700                .inc_by(u64::cast_from(client_counter.read));
701        }
702        res?;
703
704        Ok(())
705    }
706
707    #[mz_ore::instrument(level = "debug")]
708    async fn init_stream<'a, A>(
709        conn: &'a mut FramedConn<A>,
710        envd_addr: SocketAddr,
711        password: Option<String>,
712        params: BTreeMap<String, String>,
713        internal_tls: bool,
714    ) -> Result<Conn<TcpStream>, anyhow::Error>
715    where
716        A: AsyncRead + AsyncWrite + AsyncReady + Send + Sync + Unpin,
717    {
718        let mut mz_stream = TcpStream::connect(envd_addr).await?;
719        let mut buf = BytesMut::new();
720
721        let mut mz_stream = if internal_tls {
722            FrontendStartupMessage::SslRequest.encode(&mut buf)?;
723            mz_stream.write_all(&buf).await?;
724            buf.clear();
725            let mut maybe_ssl_request_response = [0u8; 1];
726            let nread =
727                netio::read_exact_or_eof(&mut mz_stream, &mut maybe_ssl_request_response).await?;
728            if nread == 1 && maybe_ssl_request_response == [ACCEPT_SSL_ENCRYPTION] {
729                // do a TLS handshake
730                let mut builder =
731                    SslConnector::builder(SslMethod::tls()).expect("Error creating builder.");
732                // environmentd doesn't yet have a cert we trust, so for now disable verification.
733                builder.set_verify(SslVerifyMode::NONE);
734                let mut ssl = builder
735                    .build()
736                    .configure()?
737                    .into_ssl(&envd_addr.to_string())?;
738                ssl.set_connect_state();
739                Conn::Ssl(SslStream::new(ssl, mz_stream)?)
740            } else {
741                Conn::Unencrypted(mz_stream)
742            }
743        } else {
744            Conn::Unencrypted(mz_stream)
745        };
746
747        // Send initial startup and password messages.
748        let startup = FrontendStartupMessage::Startup {
749            version: VERSION_3,
750            params,
751        };
752        startup.encode(&mut buf)?;
753        mz_stream.write_all(&buf).await?;
754        let client_stream = conn.inner_mut();
755
756        // This early return is important in self managed with SASL mode.
757        // The below code specifically looks for cleartext password requests, but in SASL mode
758        // the server will send a different message type (SASLInitialResponse) that we should
759        // not try to interpret or respond to.
760        // "Why not? That code looks like it should fall back fine?" You may ask.
761        // The below block unconditionally reads 9 bytes from the server. If we don't have
762        // a password or the message isn't a cleartext password request, we forward those 9 bytes
763        // to the client. Then we return the stream to the caller, who will continue shuffling bytes.
764        // The problem is that with TLS enabled between balancerd <-> client, flushing the first 9 bytes
765        // before copying bidirectionally will have the side effect of splitting the auth handshake into
766        // two SSL records. Pgbouncer misbehaves in this scenario, and fails the connection.
767        // PGbouncer shouldn't do this! It's a common footgun of protocols over TLS.
768        // So common in fact that PGbouncer already hit and fixed this issue on the bouncer <-> client side:
769        // once before: https://github.com/pgbouncer/pgbouncer/pull/1058.
770        // We will work to upstream a fix, but in the meantime, this early return avoids the issue entirely.
771        if password.is_none() {
772            return Ok(mz_stream);
773        }
774
775        // Read a single backend message, which may be a password request. Send ours if so.
776        // Otherwise start shuffling bytes. message type (len 1, 'R') + message len (len 4, 8_i32) +
777        // auth type (len 4, 3_i32).
778        let mut maybe_auth_frame = [0; 1 + 4 + 4];
779        let nread = netio::read_exact_or_eof(&mut mz_stream, &mut maybe_auth_frame).await?;
780        // 'R' for auth message, 0008 for message length, 0003 for password cleartext variant.
781        // See: https://www.postgresql.org/docs/current/protocol-message-formats.html#PROTOCOL-MESSAGE-FORMATS-AUTHENTICATIONCLEARTEXTPASSWORD
782        const AUTH_PASSWORD_CLEARTEXT: [u8; 9] = [b'R', 0, 0, 0, 8, 0, 0, 0, 3];
783        if nread == AUTH_PASSWORD_CLEARTEXT.len()
784            && maybe_auth_frame == AUTH_PASSWORD_CLEARTEXT
785            && password.is_some()
786        {
787            // If we got exactly a cleartext password request and have one, send it.
788            let Some(password) = password else {
789                unreachable!("verified some above");
790            };
791            let password = FrontendMessage::Password { password };
792            buf.clear();
793            password.encode(&mut buf)?;
794            mz_stream.write_all(&buf).await?;
795            mz_stream.flush().await?;
796        } else {
797            // Otherwise pass on the bytes we just got. This *might* even be a password request, but
798            // we don't have a password. In which case it can be forwarded up to the client.
799            client_stream.write_all(&maybe_auth_frame[0..nread]).await?;
800        }
801
802        Ok(mz_stream)
803    }
804}
805
806impl mz_server_core::Server for PgwireBalancer {
807    const NAME: &'static str = "pgwire_balancer";
808
809    fn handle_connection(
810        &self,
811        conn: Connection,
812        _tokio_metrics_intervals: impl Iterator<Item = TaskMetrics> + Send + 'static,
813    ) -> mz_server_core::ConnectionHandler {
814        let tls = self.tls.clone();
815        let internal_tls = self.internal_tls;
816        let resolver = Arc::clone(&self.resolver);
817        let inner_metrics = self.metrics.clone();
818        let outer_metrics = self.metrics.clone();
819        let cancellation_resolver = Arc::clone(&self.cancellation_resolver);
820        let conn_uuid = epoch_to_uuid_v7(&(self.now)());
821        let peer_addr = conn.peer_addr();
822        conn.uuid_handle().set(conn_uuid);
823        Box::pin(async move {
824            // TODO: Try to merge this with pgwire/server.rs to avoid the duplication. May not be
825            // worth it.
826            let active_guard = outer_metrics.active_connections();
827            let result: Result<(), anyhow::Error> = async move {
828                let mut conn = Conn::Unencrypted(conn);
829                loop {
830                    let message = decode_startup(&mut conn).await?;
831                    conn = match message {
832                        // Clients sometimes hang up during the startup sequence, e.g.
833                        // because they receive an unacceptable response to an
834                        // `SslRequest`. This is considered a graceful termination.
835                        None => return Ok(()),
836
837                        Some(FrontendStartupMessage::Startup {
838                            version,
839                            mut params,
840                        }) => {
841                            let mut conn = FramedConn::new(conn);
842                            let peer_addr = match peer_addr {
843                                Ok(addr) => addr.ip(),
844                                Err(e) => {
845                                    error!("Invalid peer_addr {:?}", e);
846                                    return Ok(conn
847                                        .send(ErrorResponse::fatal(
848                                            SqlState::SQLSERVER_REJECTED_ESTABLISHMENT_OF_SQLCONNECTION,
849                                            "invalid peer address",
850                                        ))
851                                        .await?);
852                                }
853                            };
854                            debug!(%conn_uuid, %peer_addr,  "starting new pgwire connection in balancer");
855                            let prev =
856                                params.insert(CONN_UUID_KEY.to_string(), conn_uuid.to_string());
857                            if prev.is_some() {
858                                return Ok(conn
859                                    .send(ErrorResponse::fatal(
860                                        SqlState::SQLSERVER_REJECTED_ESTABLISHMENT_OF_SQLCONNECTION,
861                                        format!("invalid parameter '{CONN_UUID_KEY}'"),
862                                    ))
863                                    .await?);
864                            }
865
866                            if let Some(_) = params.insert(MZ_FORWARDED_FOR_KEY.to_string(), peer_addr.to_string().clone()) {
867                                return Ok(conn
868                                    .send(ErrorResponse::fatal(
869                                        SqlState::SQLSERVER_REJECTED_ESTABLISHMENT_OF_SQLCONNECTION,
870                                        format!("invalid parameter '{MZ_FORWARDED_FOR_KEY}'"),
871                                    ))
872                                    .await?);
873                            };
874
875                            Self::run(
876                                &mut conn,
877                                version,
878                                params,
879                                &resolver,
880                                tls.map(|tls| tls.mode),
881                                internal_tls,
882                                &inner_metrics,
883                            )
884                            .await?;
885                            conn.flush().await?;
886                            return Ok(());
887                        }
888
889                        Some(FrontendStartupMessage::CancelRequest {
890                            conn_id,
891                            secret_key,
892                        }) => {
893                            spawn(|| "cancel request", async move {
894                                cancel_request(conn_id, secret_key, &cancellation_resolver).await;
895                            });
896                            // Do not wait on cancel requests to return because cancellation is best
897                            // effort.
898                            return Ok(());
899                        }
900
901                        Some(FrontendStartupMessage::SslRequest) => match (conn, &tls) {
902                            (Conn::Unencrypted(mut conn), Some(tls)) => {
903                                conn.write_all(&[ACCEPT_SSL_ENCRYPTION]).await?;
904                                let mut ssl_stream =
905                                    SslStream::new(Ssl::new(&tls.context.get())?, conn)?;
906                                if let Err(e) = Pin::new(&mut ssl_stream).accept().await {
907                                    let _ = ssl_stream.get_mut().shutdown().await;
908                                    return Err(e.into());
909                                }
910                                Conn::Ssl(ssl_stream)
911                            }
912                            (mut conn, _) => {
913                                conn.write_all(&[REJECT_ENCRYPTION]).await?;
914                                conn
915                            }
916                        },
917
918                        Some(FrontendStartupMessage::GssEncRequest) => {
919                            conn.write_all(&[REJECT_ENCRYPTION]).await?;
920                            conn
921                        }
922                    }
923                }
924            }
925            .await;
926            drop(active_guard);
927            outer_metrics.connection_status(result.is_ok()).inc();
928            Ok(())
929        })
930    }
931}
932
933// A struct that counts bytes exchanged.
934struct CountingConn<C> {
935    inner: C,
936    read: usize,
937    written: usize,
938}
939
940impl<C> CountingConn<C> {
941    fn new(inner: C) -> Self {
942        CountingConn {
943            inner,
944            read: 0,
945            written: 0,
946        }
947    }
948}
949
950impl<C> AsyncRead for CountingConn<C>
951where
952    C: AsyncRead + Unpin,
953{
954    fn poll_read(
955        self: Pin<&mut Self>,
956        cx: &mut std::task::Context<'_>,
957        buf: &mut io::ReadBuf<'_>,
958    ) -> std::task::Poll<std::io::Result<()>> {
959        let counter = self.get_mut();
960        let pin = Pin::new(&mut counter.inner);
961        let bytes = buf.filled().len();
962        let poll = pin.poll_read(cx, buf);
963        let bytes = buf.filled().len() - bytes;
964        if let std::task::Poll::Ready(Ok(())) = poll {
965            counter.read += bytes
966        }
967        poll
968    }
969}
970
971impl<C> AsyncWrite for CountingConn<C>
972where
973    C: AsyncWrite + Unpin,
974{
975    fn poll_write(
976        self: Pin<&mut Self>,
977        cx: &mut std::task::Context<'_>,
978        buf: &[u8],
979    ) -> std::task::Poll<Result<usize, std::io::Error>> {
980        let counter = self.get_mut();
981        let pin = Pin::new(&mut counter.inner);
982        let poll = pin.poll_write(cx, buf);
983        if let std::task::Poll::Ready(Ok(bytes)) = poll {
984            counter.written += bytes
985        }
986        poll
987    }
988
989    fn poll_flush(
990        self: Pin<&mut Self>,
991        cx: &mut std::task::Context<'_>,
992    ) -> std::task::Poll<Result<(), std::io::Error>> {
993        let counter = self.get_mut();
994        let pin = Pin::new(&mut counter.inner);
995        pin.poll_flush(cx)
996    }
997
998    fn poll_shutdown(
999        self: Pin<&mut Self>,
1000        cx: &mut std::task::Context<'_>,
1001    ) -> std::task::Poll<Result<(), std::io::Error>> {
1002        let counter = self.get_mut();
1003        let pin = Pin::new(&mut counter.inner);
1004        pin.poll_shutdown(cx)
1005    }
1006}
1007
1008/// Broadcasts cancellation to all matching environmentds. `conn_id`'s bits [31..20] are the lower
1009/// 12 bits of a UUID for an environmentd/organization. Using that and the template in
1010/// `cancellation_resolver` we generate a hostname. That hostname resolves to all IPs of envds that
1011/// match the UUID (cloud k8s infrastructure maintains that mapping). This function creates a new
1012/// task for each envd and relays the cancellation message to it, broadcasting it to any envd that
1013/// might match the connection.
1014///
1015/// This function returns after it has spawned the tasks, and does not wait for them to complete.
1016/// This is acceptable because cancellation in the Postgres protocol is best effort and has no
1017/// guarantees.
1018///
1019/// The safety of broadcasting this is due to the various randomness in the connection id and secret
1020/// key, which must match exactly in order to execute a query cancellation. The connection id has 19
1021/// bits of randomness, and the secret key the full 32, for a total of 51 bits. That is more than
1022/// 2e15 combinations, enough to nearly certainly prevent two different envds generating identical
1023/// combinations.
1024async fn cancel_request(
1025    conn_id: u32,
1026    secret_key: u32,
1027    cancellation_resolver: &CancellationResolver,
1028) {
1029    let suffix = conn_id_org_uuid(conn_id);
1030    let contents = match cancellation_resolver {
1031        CancellationResolver::Directory(dir) => {
1032            let path = dir.join(&suffix);
1033            match std::fs::read_to_string(&path) {
1034                Ok(contents) => contents,
1035                Err(err) => {
1036                    error!("could not read cancel file {path:?}: {err}");
1037                    return;
1038                }
1039            }
1040        }
1041        CancellationResolver::Static(addr) => addr.to_owned(),
1042    };
1043    let mut all_ips = Vec::new();
1044    for addr in contents.lines() {
1045        let addr = addr.trim();
1046        if addr.is_empty() {
1047            continue;
1048        }
1049        match tokio::net::lookup_host(addr).await {
1050            Ok(ips) => all_ips.extend(ips),
1051            Err(err) => {
1052                error!("{addr} failed resolution: {err}");
1053            }
1054        }
1055    }
1056    let mut buf = BytesMut::with_capacity(16);
1057    let msg = FrontendStartupMessage::CancelRequest {
1058        conn_id,
1059        secret_key,
1060    };
1061    msg.encode(&mut buf).expect("must encode");
1062    let buf = buf.freeze();
1063    for ip in all_ips {
1064        debug!("cancelling {suffix} to {ip}");
1065        let buf = buf.clone();
1066        spawn(|| "cancel request for ip", async move {
1067            let send = async {
1068                let mut stream = TcpStream::connect(&ip).await?;
1069                stream.write_all(&buf).await?;
1070                stream.shutdown().await?;
1071                Ok::<_, io::Error>(())
1072            };
1073            if let Err(err) = send.await {
1074                error!("error mirroring cancel to {ip}: {err}");
1075            }
1076        });
1077    }
1078}
1079
1080struct HttpsBalancer {
1081    resolver: Arc<StubResolver>,
1082    tls: Option<ReloadingSslContext>,
1083    resolve_template: Arc<str>,
1084    port: u16,
1085    metrics: Arc<ServerMetrics>,
1086    configs: ConfigSet,
1087    internal_tls: bool,
1088}
1089
1090impl HttpsBalancer {
1091    async fn resolve(
1092        resolver: &StubResolver,
1093        resolve_template: &str,
1094        port: u16,
1095        servername: Option<&str>,
1096    ) -> Result<ResolvedAddr, anyhow::Error> {
1097        let addr = match &servername {
1098            Some(servername) => resolve_template.replace("{}", servername),
1099            None => resolve_template.to_string(),
1100        };
1101        debug!("https address: {addr}");
1102
1103        // When we lookup the address using SNI, we get a hostname (`3dl07g8zmj91pntk4eo9cfvwe` for
1104        // example), which you convert into a different form for looking up the environment address
1105        // `blncr-3dl07g8zmj91pntk4eo9cfvwe`. When you do a DNS lookup in kubernetes for
1106        // `blncr-3dl07g8zmj91pntk4eo9cfvwe`, you get a CNAME response pointing at environmentd
1107        // `environmentd.environment-58cd23ff-a4d7-4bd0-ad85-a6ff29cc86c3-0.svc.cluster.local`. This
1108        // is of the form `<service>.<namespace>.svc.cluster.local`. That `<namespace>` is the same
1109        // as the environment name, and is based on the tenant ID. `environment-<tenant_id>-<index>`
1110        // We currently only support a single environment per tenant in a region, so `<index>` is
1111        // always 0. Do not rely on this ending in `-0` so in the future multiple envds are
1112        // supported.
1113
1114        // Attempt to get a tenant.
1115        let tenant = resolver.tenant(&addr).await;
1116
1117        // Now do the regular ip lookup, regardless of if there was a CNAME.
1118        let envd_addr = lookup(&format!("{addr}:{port}")).await?;
1119
1120        Ok(ResolvedAddr {
1121            addr: envd_addr,
1122            password: None,
1123            tenant,
1124        })
1125    }
1126}
1127
1128trait StubResolverExt {
1129    async fn tenant(&self, addr: &str) -> Option<String>;
1130}
1131
1132impl StubResolverExt for StubResolver {
1133    /// Finds the tenant of a DNS address. Errors or lack of cname resolution here are ok, because
1134    /// this is only used for metrics.
1135    async fn tenant(&self, addr: &str) -> Option<String> {
1136        let Ok(dname) = Name::<Vec<_>>::from_str(addr) else {
1137            return None;
1138        };
1139        debug!("resolving tenant for {:?}", addr);
1140        // Lookup the CNAME. If there's a CNAME, find the tenant.
1141        let lookup = self.query((dname, Rtype::CNAME)).await;
1142        if let Ok(lookup) = lookup {
1143            if let Ok(answer) = lookup.answer() {
1144                let res = answer.limit_to::<AllRecordData<_, _>>();
1145                for record in res {
1146                    let Ok(record) = record else {
1147                        continue;
1148                    };
1149                    if record.rtype() != Rtype::CNAME {
1150                        continue;
1151                    }
1152                    let cname = record.data();
1153                    let cname = cname.to_string();
1154                    debug!("cname: {cname}");
1155                    return extract_tenant_from_cname(&cname);
1156                }
1157            }
1158        }
1159        None
1160    }
1161}
1162
1163/// Extracts the tenant from a CNAME.
1164fn extract_tenant_from_cname(cname: &str) -> Option<String> {
1165    let mut parts = cname.split('.');
1166    let _service = parts.next();
1167    let Some(namespace) = parts.next() else {
1168        return None;
1169    };
1170    // Trim off the starting `environmentd-`.
1171    let Some((_, namespace)) = namespace.split_once('-') else {
1172        return None;
1173    };
1174    // Trim off the ending `-0` (or some other number).
1175    let Some((tenant, _)) = namespace.rsplit_once('-') else {
1176        return None;
1177    };
1178    // Convert to a Uuid so that this tenant matches the frontegg resolver exactly, because it
1179    // also uses Uuid::to_string.
1180    let Ok(tenant) = Uuid::parse_str(tenant) else {
1181        error!("cname tenant not a uuid: {tenant}");
1182        return None;
1183    };
1184    Some(tenant.to_string())
1185}
1186
1187impl mz_server_core::Server for HttpsBalancer {
1188    const NAME: &'static str = "https_balancer";
1189
1190    // TODO(jkosh44) consider forwarding the connection UUID to the adapter.
1191    fn handle_connection(
1192        &self,
1193        conn: Connection,
1194        _tokio_metrics_intervals: impl Iterator<Item = TaskMetrics> + Send + 'static,
1195    ) -> mz_server_core::ConnectionHandler {
1196        let tls_context = self.tls.clone();
1197        let internal_tls = self.internal_tls.clone();
1198        let resolver = Arc::clone(&self.resolver);
1199        let resolve_template = Arc::clone(&self.resolve_template);
1200        let port = self.port;
1201        let inner_metrics = Arc::clone(&self.metrics);
1202        let outer_metrics = Arc::clone(&self.metrics);
1203        let peer_addr = conn.peer_addr();
1204        let inject_proxy_headers = INJECT_PROXY_PROTOCOL_HEADER_HTTP.get(&self.configs);
1205        Box::pin(async move {
1206            let active_guard = inner_metrics.active_connections();
1207            let result: Result<_, anyhow::Error> = Box::pin(async move {
1208                let peer_addr = peer_addr.context("fetching peer addr")?;
1209                let (mut client_stream, servername): (Box<dyn ClientStream>, Option<String>) =
1210                    match tls_context {
1211                        Some(tls_context) => {
1212                            let mut ssl_stream =
1213                                SslStream::new(Ssl::new(&tls_context.get())?, conn)?;
1214                            if let Err(e) = Pin::new(&mut ssl_stream).accept().await {
1215                                let _ = ssl_stream.get_mut().shutdown().await;
1216                                return Err(e.into());
1217                            }
1218                            let servername: Option<String> =
1219                                ssl_stream.ssl().servername(NameType::HOST_NAME).map(|sn| {
1220                                    match sn.split_once('.') {
1221                                        Some((left, _right)) => left,
1222                                        None => sn,
1223                                    }
1224                                    .into()
1225                                });
1226                            debug!("Found sni servername: {servername:?} (https)");
1227                            (Box::new(ssl_stream), servername)
1228                        }
1229                        _ => (Box::new(conn), None),
1230                    };
1231                let resolved =
1232                    Self::resolve(&resolver, &resolve_template, port, servername.as_deref())
1233                        .await?;
1234                let inner_active_guard = resolved
1235                    .tenant
1236                    .as_ref()
1237                    .map(|tenant| inner_metrics.tenant_connections(tenant));
1238                let mut mz_stream = match TcpStream::connect(resolved.addr).await {
1239                    Ok(stream) => stream,
1240                    Err(e) => {
1241                        error!("failed to connect to upstream server: {e}");
1242                        let body = "upstream server not available";
1243                        // We know this is an HTTPs stream (see name
1244                        // HttpsBalancer), but we actually don't care what type
1245                        // of traffic it is and we only use raw tcp streams.In
1246                        // order to respond with HTTP we have to write this as a
1247                        // raw http message.
1248                        let response = format!(
1249                            "HTTP/1.1 502 Bad Gateway\r\n\
1250                             Content-Type: text/plain\r\n\
1251                             Content-Length: {}\r\n\
1252                             Connection: close\r\n\
1253                             \r\n\
1254                             {}",
1255                            body.len(),
1256                            body
1257                        );
1258                        let _ = client_stream.write_all(response.as_bytes()).await;
1259                        let _ = client_stream.shutdown().await;
1260                        return Ok(());
1261                    }
1262                };
1263
1264                if inject_proxy_headers {
1265                    // Write the tcp proxy header
1266                    let addrs = ProxiedAddress::stream(peer_addr, resolved.addr);
1267                    let header = ProxyHeader::with_address(addrs);
1268                    let mut buf = [0u8; 1024];
1269                    let len = header.encode_to_slice_v2(&mut buf)?;
1270                    mz_stream.write_all(&buf[..len]).await?;
1271                }
1272
1273                let mut mz_stream = if internal_tls {
1274                    // do a TLS handshake
1275                    let mut builder =
1276                        SslConnector::builder(SslMethod::tls()).expect("Error creating builder.");
1277                    // environmentd doesn't yet have a cert we trust, so for now disable verification.
1278                    builder.set_verify(SslVerifyMode::NONE);
1279                    let mut ssl = builder
1280                        .build()
1281                        .configure()?
1282                        .into_ssl(&resolved.addr.to_string())?;
1283                    ssl.set_connect_state();
1284                    Conn::Ssl(SslStream::new(ssl, mz_stream)?)
1285                } else {
1286                    Conn::Unencrypted(mz_stream)
1287                };
1288
1289                let mut client_counter = CountingConn::new(client_stream);
1290
1291                // Now blindly shuffle bytes back and forth until closed.
1292                // TODO: Limit total memory use.
1293                // See corresponding comment in pgwire implementation about ignoring the error.
1294                let _ = tokio::io::copy_bidirectional(&mut client_counter, &mut mz_stream).await;
1295                if let Some(tenant) = &resolved.tenant {
1296                    inner_metrics
1297                        .tenant_connections_tx(tenant)
1298                        .inc_by(u64::cast_from(client_counter.written));
1299                    inner_metrics
1300                        .tenant_connections_rx(tenant)
1301                        .inc_by(u64::cast_from(client_counter.read));
1302                }
1303                drop(inner_active_guard);
1304                Ok(())
1305            })
1306            .await;
1307            drop(active_guard);
1308            outer_metrics.connection_status(result.is_ok()).inc();
1309            if let Err(e) = result {
1310                debug!("connection error: {e}");
1311            }
1312            Ok(())
1313        })
1314    }
1315}
1316
1317#[derive(Debug)]
1318pub struct SniResolver {
1319    pub resolver: StubResolver,
1320    pub template: String,
1321    pub port: u16,
1322}
1323
1324trait ClientStream: AsyncRead + AsyncWrite + Unpin + Send {}
1325impl<T: AsyncRead + AsyncWrite + Unpin + Send> ClientStream for T {}
1326
1327#[derive(Debug)]
1328pub enum Resolver {
1329    Static(String),
1330    MultiTenant(FronteggResolver, Option<SniResolver>),
1331}
1332
1333impl Resolver {
1334    async fn resolve<A>(
1335        &self,
1336        conn: &mut FramedConn<A>,
1337        user: &str,
1338        metrics: &ServerMetrics,
1339    ) -> Result<ResolvedAddr, anyhow::Error>
1340    where
1341        A: AsyncRead + AsyncWrite + Unpin,
1342    {
1343        match self {
1344            Resolver::MultiTenant(
1345                FronteggResolver {
1346                    auth,
1347                    addr_template,
1348                },
1349                sni_resolver,
1350            ) => {
1351                let servername = match conn.inner() {
1352                    Conn::Ssl(ssl_stream) => {
1353                        ssl_stream.ssl().servername(NameType::HOST_NAME).map(|sn| {
1354                            match sn.split_once('.') {
1355                                Some((left, _right)) => left,
1356                                None => sn,
1357                            }
1358                        })
1359                    }
1360                    Conn::Unencrypted(_) => None,
1361                };
1362                let has_sni = servername.is_some();
1363                // We found an SNi
1364                let resolved_addr = match (servername, sni_resolver) {
1365                    (
1366                        Some(servername),
1367                        Some(SniResolver {
1368                            resolver: stub_resolver,
1369                            template: sni_addr_template,
1370                            port,
1371                        }),
1372                    ) => {
1373                        let sni_addr = sni_addr_template.replace("{}", servername);
1374                        let tenant = stub_resolver.tenant(&sni_addr).await;
1375                        let sni_addr = format!("{sni_addr}:{port}");
1376                        let addr = lookup(&sni_addr).await?;
1377                        if tenant.is_some() {
1378                            debug!("SNI header found for tenant {:?}", tenant);
1379                        }
1380                        ResolvedAddr {
1381                            addr,
1382                            password: None,
1383                            tenant,
1384                        }
1385                    }
1386                    _ => {
1387                        conn.send(BackendMessage::AuthenticationCleartextPassword)
1388                            .await?;
1389                        conn.flush().await?;
1390                        let password = match conn.recv().await? {
1391                            Some(FrontendMessage::Password { password }) => password,
1392                            _ => anyhow::bail!("expected Password message"),
1393                        };
1394
1395                        let auth_response = auth.authenticate(user, &password).await;
1396                        let auth_session = match auth_response {
1397                            Ok(auth_session) => auth_session,
1398                            Err(e) => {
1399                                warn!("pgwire connection failed authentication: {}", e);
1400                                // TODO: fix error codes.
1401                                anyhow::bail!("invalid password");
1402                            }
1403                        };
1404
1405                        let addr =
1406                            addr_template.replace("{}", &auth_session.tenant_id().to_string());
1407                        let addr = lookup(&addr).await?;
1408                        let tenant = Some(auth_session.tenant_id().to_string());
1409                        if tenant.is_some() {
1410                            debug!("SNI header NOT found for tenant {:?}", tenant);
1411                        }
1412                        ResolvedAddr {
1413                            addr,
1414                            password: Some(password),
1415                            tenant,
1416                        }
1417                    }
1418                };
1419                metrics
1420                    .tenant_pgwire_sni_count(
1421                        resolved_addr.tenant.as_deref().unwrap_or("unknown"),
1422                        has_sni,
1423                    )
1424                    .inc();
1425
1426                Ok(resolved_addr)
1427            }
1428            Resolver::Static(addr) => {
1429                let addr = lookup(addr).await?;
1430                Ok(ResolvedAddr {
1431                    addr,
1432                    password: None,
1433                    tenant: None,
1434                })
1435            }
1436        }
1437    }
1438}
1439
1440/// Returns the first IP address resolved from the provided hostname.
1441async fn lookup(name: &str) -> Result<SocketAddr, anyhow::Error> {
1442    let mut addrs = tokio::net::lookup_host(name).await?;
1443    match addrs.next() {
1444        Some(addr) => Ok(addr),
1445        None => {
1446            error!("{name} did not resolve to any addresses");
1447            anyhow::bail!("internal error")
1448        }
1449    }
1450}
1451
1452#[derive(Debug)]
1453pub struct FronteggResolver {
1454    pub auth: FronteggAuthentication,
1455    pub addr_template: String,
1456}
1457
1458#[derive(Debug)]
1459struct ResolvedAddr {
1460    addr: SocketAddr,
1461    password: Option<String>,
1462    tenant: Option<String>,
1463}
1464
1465#[cfg(test)]
1466mod tests {
1467    use super::*;
1468
1469    #[mz_ore::test]
1470    fn test_tenant() {
1471        let tests = vec![
1472            ("", None),
1473            (
1474                "environmentd.environment-58cd23ff-a4d7-4bd0-ad85-a6ff29cc86c3-0.svc.cluster.local",
1475                Some("58cd23ff-a4d7-4bd0-ad85-a6ff29cc86c3"),
1476            ),
1477            (
1478                // Variously named parts.
1479                "service.something-58cd23ff-a4d7-4bd0-ad85-a6ff29cc86c3-0.ssvvcc.cloister.faraway",
1480                Some("58cd23ff-a4d7-4bd0-ad85-a6ff29cc86c3"),
1481            ),
1482            (
1483                // No dashes in uuid.
1484                "environmentd.environment-58cd23ffa4d74bd0ad85a6ff29cc86c3-0.svc.cluster.local",
1485                Some("58cd23ff-a4d7-4bd0-ad85-a6ff29cc86c3"),
1486            ),
1487            (
1488                // -1234 suffix.
1489                "environmentd.environment-58cd23ff-a4d7-4bd0-ad85-a6ff29cc86c3-1234.svc.cluster.local",
1490                Some("58cd23ff-a4d7-4bd0-ad85-a6ff29cc86c3"),
1491            ),
1492            (
1493                // Uppercase.
1494                "environmentd.environment-58CD23FF-A4D7-4BD0-AD85-A6FF29CC86C3-0.svc.cluster.local",
1495                Some("58cd23ff-a4d7-4bd0-ad85-a6ff29cc86c3"),
1496            ),
1497            (
1498                // No -number suffix.
1499                "environmentd.environment-58cd23ff-a4d7-4bd0-ad85-a6ff29cc86c3.svc.cluster.local",
1500                None,
1501            ),
1502            (
1503                // No service name.
1504                "environment-58cd23ff-a4d7-4bd0-ad85-a6ff29cc86c3-0.svc.cluster.local",
1505                None,
1506            ),
1507            (
1508                // Invalid UUID.
1509                "environmentd.environment-8cd23ff-a4d7-4bd0-ad85-a6ff29cc86c3-0.svc.cluster.local",
1510                None,
1511            ),
1512        ];
1513        for (name, expect) in tests {
1514            let cname = extract_tenant_from_cname(name);
1515            assert_eq!(
1516                cname.as_deref(),
1517                expect,
1518                "{name} got {cname:?} expected {expect:?}"
1519            );
1520        }
1521    }
1522}