Skip to main content

mz_pgwire/
server.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::future::Future;
11use std::net::IpAddr;
12use std::pin::Pin;
13use std::str::FromStr;
14
15use anyhow::Context;
16use async_trait::async_trait;
17use mz_authenticator::GenericOidcAuthenticator;
18use mz_frontegg_auth::Authenticator as FronteggAuthenticator;
19use mz_ore::now::{SYSTEM_TIME, epoch_to_uuid_v7};
20use mz_pgwire_common::{
21    ACCEPT_SSL_ENCRYPTION, CONN_UUID_KEY, Conn, ConnectionCounter, FrontendStartupMessage,
22    MAX_FORWARDED_STARTUP_FRAME_SIZE, MZ_FORWARDED_FOR_KEY, REJECT_ENCRYPTION, TlsStream,
23    decode_startup,
24};
25use mz_server_core::listeners::{AllowedRoles, AuthenticatorKind};
26use mz_server_core::{Connection, ConnectionHandler, ReloadingTlsConfig};
27use openssl::ssl::Ssl;
28use tokio::io::AsyncWriteExt;
29use tokio_metrics::TaskMetrics;
30use tokio_openssl::SslStream;
31use tracing::{debug, error, trace};
32
33use crate::codec::FramedConn;
34use crate::metrics::{Metrics, MetricsConfig};
35use crate::protocol;
36
37/// Configures a [`Server`].
38#[derive(Debug)]
39pub struct Config {
40    /// The label for the mz_connection_status metric.
41    pub label: &'static str,
42    /// A client for the adapter with which the server will communicate.
43    pub adapter_client: mz_adapter::Client,
44    /// The TLS configuration for the server.
45    ///
46    /// If not present, then TLS is not enabled, and clients requests to
47    /// negotiate TLS will be rejected.
48    pub tls: Option<ReloadingTlsConfig>,
49    /// Frontegg JWT authenticator.
50    pub frontegg: Option<FronteggAuthenticator>,
51    /// OIDC authenticator.
52    pub oidc: GenericOidcAuthenticator,
53    /// The authentication method defined by the server's listener
54    /// configuration.
55    pub authenticator_kind: AuthenticatorKind,
56    /// The registry entries that the pgwire server uses to report metrics.
57    pub metrics: MetricsConfig,
58    /// Global connection limit and count
59    pub active_connection_counter: ConnectionCounter,
60    /// Helm chart version
61    pub helm_chart_version: Option<String>,
62    /// Whether to allow reserved users (ie: mz_system).
63    pub allowed_roles: AllowedRoles,
64}
65
66/// A server that communicates with clients via the pgwire protocol.
67pub struct Server {
68    tls: Option<ReloadingTlsConfig>,
69    adapter_client: mz_adapter::Client,
70    authenticator_kind: AuthenticatorKind,
71    frontegg: Option<FronteggAuthenticator>,
72    oidc: GenericOidcAuthenticator,
73    metrics: Metrics,
74    active_connection_counter: ConnectionCounter,
75    helm_chart_version: Option<String>,
76    allowed_roles: AllowedRoles,
77}
78
79#[async_trait]
80impl mz_server_core::Server for Server {
81    const NAME: &'static str = "pgwire";
82
83    fn handle_connection(
84        &self,
85        conn: Connection,
86        tokio_metrics_intervals: impl Iterator<Item = TaskMetrics> + Send + 'static,
87    ) -> ConnectionHandler {
88        // Using fully-qualified syntax means we won't accidentally call
89        // ourselves (i.e., silently infinitely recurse) if the name or type of
90        // `crate::Server::handle_connection` changes.
91        Box::pin(crate::Server::handle_connection(
92            self,
93            conn,
94            tokio_metrics_intervals,
95        ))
96    }
97}
98
99impl Server {
100    /// Constructs a new server.
101    pub fn new(config: Config) -> Server {
102        Server {
103            tls: config.tls,
104            adapter_client: config.adapter_client,
105            authenticator_kind: config.authenticator_kind,
106            frontegg: config.frontegg,
107            oidc: config.oidc,
108            metrics: Metrics::new(config.metrics, config.label),
109            active_connection_counter: config.active_connection_counter,
110            helm_chart_version: config.helm_chart_version,
111            allowed_roles: config.allowed_roles,
112        }
113    }
114
115    #[mz_ore::instrument(level = "debug")]
116    pub fn handle_connection(
117        &self,
118        conn: Connection,
119        tokio_metrics_intervals: impl Iterator<Item = TaskMetrics> + Send + 'static,
120    ) -> impl Future<Output = Result<(), anyhow::Error>> + Send + 'static {
121        let adapter_client = self.adapter_client.clone();
122        let authenticator_kind = self.authenticator_kind;
123        let frontegg = self.frontegg.clone();
124        let oidc = self.oidc.clone();
125        let tls = self.tls.clone();
126        let metrics = self.metrics.clone();
127        let active_connection_counter = self.active_connection_counter.clone();
128        let helm_chart_version = self.helm_chart_version.clone();
129        let allowed_roles = self.allowed_roles;
130
131        // TODO(guswynn): remove this redundant_closure_call
132        #[allow(clippy::redundant_closure_call)]
133        async move {
134            let result = (|| {
135                async move {
136                    let conn_id = adapter_client.new_conn_id()?;
137                    let mut conn = Conn::Unencrypted(conn);
138                    loop {
139                        let message =
140                            decode_startup(&mut conn, MAX_FORWARDED_STARTUP_FRAME_SIZE).await?;
141
142                        match &message {
143                            Some(message) => trace!("cid={} recv={:?}", conn_id, message),
144                            None => trace!("cid={} recv=<eof>", conn_id),
145                        }
146
147                        conn = match message {
148                            // Clients sometimes hang up during the startup sequence, e.g.
149                            // because they receive an unacceptable response to an
150                            // `SslRequest`. This is considered a graceful termination.
151                            None => return Ok(()),
152
153                            Some(FrontendStartupMessage::Startup {
154                                version,
155                                mut params,
156                            }) => {
157                                // If someone (usually the balancer) forwarded a connection UUID,
158                                // then use that, otherwise generate one.
159                                let conn_uuid_handle = conn.inner_mut().uuid_handle();
160                                let conn_uuid = params
161                                    .remove(CONN_UUID_KEY)
162                                    .and_then(|uuid| {
163                                        uuid.parse()
164                                            .inspect_err(|e| {
165                                                error!(
166                                                    "pgwire connection with invalid conn UUID: {e}",
167                                                )
168                                            })
169                                            .ok()
170                                    });
171                                let conn_uuid_forwarded = conn_uuid.is_some();
172                                // FIXME(ptravers): we should be able to inject
173                                // the clock when instantiating the `Server`
174                                // but as of writing there's no great way, I can
175                                // see, to harmonize the lifetimes of the return
176                                // type and &self which must house `NowFn`.
177                                let conn_uuid = conn_uuid.unwrap_or_else(
178                                    || epoch_to_uuid_v7(&(SYSTEM_TIME.clone())()),
179                                );
180                                conn_uuid_handle.set(conn_uuid);
181                                debug!(
182                                    conn_uuid = %conn_uuid_handle.display(),
183                                    conn_uuid_forwarded,
184                                    "starting new pgwire connection in adapter",
185                                );
186
187                                let direct_peer_addr = conn
188                                    .inner_mut()
189                                    .peer_addr()
190                                    .context("fetching peer addr")?
191                                    .ip();
192                                let peer_addr= match params.remove(MZ_FORWARDED_FOR_KEY) {
193                                    Some(ip_str) => {
194                                        match IpAddr::from_str(&ip_str) {
195                                            Ok(ip) => Some(ip),
196                                            Err(e) => {
197                                                error!("pgwire connection with invalid mz_forwarded_for address: {e}");
198                                                None
199                                            }
200                                        }
201                                    }
202                                    None => Some(direct_peer_addr)
203                                };
204                                let mut conn = FramedConn::new(
205                                    conn_id.clone(),
206                                    peer_addr,
207                                    conn,
208                                );
209
210                                protocol::run(protocol::RunParams {
211                                    tls_mode: tls.as_ref().map(|tls| tls.mode),
212                                    adapter_client,
213                                    conn: &mut conn,
214                                    conn_uuid,
215                                    version,
216                                    params,
217                                    frontegg,
218                                    oidc,
219                                    authenticator_kind,
220                                    active_connection_counter,
221                                    helm_chart_version,
222                                    allowed_roles,
223                                    tokio_metrics_intervals,
224                                })
225                                .await?;
226                                conn.flush().await?;
227                                return Ok(());
228                            }
229
230                            Some(FrontendStartupMessage::CancelRequest {
231                                conn_id,
232                                secret_key,
233                            }) => {
234                                adapter_client.cancel_request(conn_id, secret_key);
235                                // For security, the client is not told whether the cancel
236                                // request succeeds or fails.
237                                return Ok(());
238                            }
239
240                            Some(FrontendStartupMessage::SslRequest) => match (conn, &tls) {
241                                (Conn::Unencrypted(mut conn), Some(tls)) => {
242                                    trace!("cid={} send=AcceptSsl", conn_id);
243                                    conn.write_all(&[ACCEPT_SSL_ENCRYPTION]).await?;
244                                    let mut ssl_stream =
245                                        SslStream::new(Ssl::new(&tls.context.get())?, conn)?;
246                                    if let Err(e) = Pin::new(&mut ssl_stream).accept().await {
247                                        let _ = ssl_stream.get_mut().shutdown().await;
248                                        return Err(e.into());
249                                    }
250                                    Conn::Ssl(TlsStream::Openssl(ssl_stream))
251                                }
252                                (mut conn, _) => {
253                                    trace!("cid={} send=RejectSsl", conn_id);
254                                    conn.write_all(&[REJECT_ENCRYPTION]).await?;
255                                    conn
256                                }
257                            },
258
259                            Some(FrontendStartupMessage::GssEncRequest) => {
260                                trace!("cid={} send=RejectGssEnc", conn_id);
261                                conn.write_all(&[REJECT_ENCRYPTION]).await?;
262                                conn
263                            }
264                        }
265                    }
266                }
267            })()
268            .await;
269            metrics.connection_status(result.is_ok()).inc();
270            result
271        }
272    }
273}