Skip to main content

mz_pgwire_common/
conn.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::pin::Pin;
11use std::sync::{Arc, Mutex};
12use std::task::{Context, Poll};
13
14use async_trait::async_trait;
15use derivative::Derivative;
16use mz_ore::netio::AsyncReady;
17use mz_server_core::TlsMode;
18use openssl::ssl::NameType;
19use tokio::io::{self, AsyncRead, AsyncWrite, Interest, ReadBuf, Ready};
20use tokio_openssl::SslStream;
21use tokio_postgres::error::SqlState;
22
23use crate::ErrorResponse;
24
25pub const CONN_UUID_KEY: &str = "mz_connection_uuid";
26pub const MZ_FORWARDED_FOR_KEY: &str = "mz_forwarded_for";
27
28/// A TLS stream over either the OpenSSL or the rustls backend.
29#[derive(Debug)]
30pub enum TlsStream<A> {
31    /// Wraps connections accepted or dialed with OpenSSL.
32    Openssl(SslStream<A>),
33    /// Server-side rustls session.
34    Server(tokio_rustls::server::TlsStream<A>),
35    /// Client-side rustls session.
36    Client(tokio_rustls::client::TlsStream<A>),
37}
38
39impl<A> TlsStream<A> {
40    /// Returns a mutable reference to the underlying IO stream.
41    pub fn get_mut(&mut self) -> &mut A {
42        match self {
43            TlsStream::Openssl(s) => s.get_mut(),
44            TlsStream::Server(s) => s.get_mut().0,
45            TlsStream::Client(s) => s.get_mut().0,
46        }
47    }
48
49    /// Returns a reference to the underlying IO stream.
50    pub fn get_ref(&self) -> &A {
51        match self {
52            TlsStream::Openssl(s) => s.get_ref(),
53            TlsStream::Server(s) => s.get_ref().0,
54            TlsStream::Client(s) => s.get_ref().0,
55        }
56    }
57
58    /// Returns the SNI host name of the session, if any.
59    ///
60    /// On accepted streams this is the name the client requested. Always
61    /// `None` for rustls client-side streams.
62    pub fn server_name(&self) -> Option<&str> {
63        match self {
64            TlsStream::Openssl(s) => s.ssl().servername(NameType::HOST_NAME),
65            TlsStream::Server(s) => s.get_ref().1.server_name(),
66            TlsStream::Client(_) => None,
67        }
68    }
69}
70
71impl<A: AsyncRead + AsyncWrite + Unpin> AsyncRead for TlsStream<A> {
72    fn poll_read(
73        self: Pin<&mut Self>,
74        cx: &mut Context,
75        buf: &mut ReadBuf,
76    ) -> Poll<io::Result<()>> {
77        match self.get_mut() {
78            TlsStream::Openssl(s) => Pin::new(s).poll_read(cx, buf),
79            TlsStream::Server(s) => Pin::new(s).poll_read(cx, buf),
80            TlsStream::Client(s) => Pin::new(s).poll_read(cx, buf),
81        }
82    }
83}
84
85impl<A: AsyncRead + AsyncWrite + Unpin> AsyncWrite for TlsStream<A> {
86    fn poll_write(self: Pin<&mut Self>, cx: &mut Context, buf: &[u8]) -> Poll<io::Result<usize>> {
87        match self.get_mut() {
88            TlsStream::Openssl(s) => Pin::new(s).poll_write(cx, buf),
89            TlsStream::Server(s) => Pin::new(s).poll_write(cx, buf),
90            TlsStream::Client(s) => Pin::new(s).poll_write(cx, buf),
91        }
92    }
93
94    fn poll_flush(self: Pin<&mut Self>, cx: &mut Context) -> Poll<io::Result<()>> {
95        match self.get_mut() {
96            TlsStream::Openssl(s) => Pin::new(s).poll_flush(cx),
97            TlsStream::Server(s) => Pin::new(s).poll_flush(cx),
98            TlsStream::Client(s) => Pin::new(s).poll_flush(cx),
99        }
100    }
101
102    fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context) -> Poll<io::Result<()>> {
103        match self.get_mut() {
104            TlsStream::Openssl(s) => Pin::new(s).poll_shutdown(cx),
105            TlsStream::Server(s) => Pin::new(s).poll_shutdown(cx),
106            TlsStream::Client(s) => Pin::new(s).poll_shutdown(cx),
107        }
108    }
109}
110
111#[async_trait]
112impl<A> AsyncReady for TlsStream<A>
113where
114    A: AsyncRead + AsyncWrite + AsyncReady + Sync + Unpin,
115{
116    async fn ready(&self, interest: Interest) -> io::Result<Ready> {
117        self.get_ref().ready(interest).await
118    }
119}
120
121#[derive(Debug)]
122pub enum Conn<A> {
123    Unencrypted(A),
124    Ssl(TlsStream<A>),
125}
126
127impl<A> Conn<A> {
128    pub fn inner_mut(&mut self) -> &mut A {
129        match self {
130            Conn::Unencrypted(inner) => inner,
131            Conn::Ssl(inner) => inner.get_mut(),
132        }
133    }
134
135    /// Returns an error if tls_mode is incompatible with this connection's stream type.
136    pub fn ensure_tls_compatibility(
137        &self,
138        tls_mode: &Option<TlsMode>,
139    ) -> Result<(), ErrorResponse> {
140        // Validate that the connection is compatible with the TLS mode.
141        //
142        // The match here explicitly spells out all cases to be resilient to
143        // future changes to TlsMode.
144        match (tls_mode, self) {
145            (None, Conn::Unencrypted(_)) => (),
146            (None, Conn::Ssl(_)) => unreachable!(),
147            (Some(TlsMode::Allow), Conn::Unencrypted(_)) => (),
148            (Some(TlsMode::Allow), Conn::Ssl(_)) => (),
149            (Some(TlsMode::Require), Conn::Ssl(_)) => (),
150            (Some(TlsMode::Require), Conn::Unencrypted(_)) => {
151                return Err(ErrorResponse::fatal(
152                    SqlState::SQLSERVER_REJECTED_ESTABLISHMENT_OF_SQLCONNECTION,
153                    "TLS encryption is required",
154                ));
155            }
156        }
157
158        Ok(())
159    }
160}
161
162impl<A> AsyncRead for Conn<A>
163where
164    A: AsyncRead + AsyncWrite + Unpin,
165{
166    fn poll_read(
167        self: Pin<&mut Self>,
168        cx: &mut Context,
169        buf: &mut ReadBuf,
170    ) -> Poll<io::Result<()>> {
171        match self.get_mut() {
172            Conn::Unencrypted(inner) => Pin::new(inner).poll_read(cx, buf),
173            Conn::Ssl(inner) => Pin::new(inner).poll_read(cx, buf),
174        }
175    }
176}
177
178impl<A> AsyncWrite for Conn<A>
179where
180    A: AsyncRead + AsyncWrite + Unpin,
181{
182    fn poll_write(self: Pin<&mut Self>, cx: &mut Context, buf: &[u8]) -> Poll<io::Result<usize>> {
183        match self.get_mut() {
184            Conn::Unencrypted(inner) => Pin::new(inner).poll_write(cx, buf),
185            Conn::Ssl(inner) => Pin::new(inner).poll_write(cx, buf),
186        }
187    }
188
189    fn poll_flush(self: Pin<&mut Self>, cx: &mut Context) -> Poll<io::Result<()>> {
190        match self.get_mut() {
191            Conn::Unencrypted(inner) => Pin::new(inner).poll_flush(cx),
192            Conn::Ssl(inner) => Pin::new(inner).poll_flush(cx),
193        }
194    }
195
196    fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context) -> Poll<io::Result<()>> {
197        match self.get_mut() {
198            Conn::Unencrypted(inner) => Pin::new(inner).poll_shutdown(cx),
199            Conn::Ssl(inner) => Pin::new(inner).poll_shutdown(cx),
200        }
201    }
202}
203
204#[async_trait]
205impl<A> AsyncReady for Conn<A>
206where
207    A: AsyncRead + AsyncWrite + AsyncReady + Sync + Unpin,
208{
209    async fn ready(&self, interest: Interest) -> io::Result<Ready> {
210        match self {
211            Conn::Unencrypted(inner) => inner.ready(interest).await,
212            Conn::Ssl(inner) => inner.ready(interest).await,
213        }
214    }
215}
216
217/// Metadata about a user that is required to allocate a [`ConnectionHandle`].
218#[derive(Debug, Clone, Copy)]
219pub struct UserMetadata {
220    pub is_admin: bool,
221    pub should_limit_connections: bool,
222}
223
224#[derive(Debug, Clone)]
225pub struct ConnectionCounter {
226    inner: Arc<Mutex<ConnectionCounterInner>>,
227}
228
229impl ConnectionCounter {
230    /// Returns a [`ConnectionHandle`] which must be kept alive for the entire duration of the
231    /// external connection.
232    ///
233    /// Dropping the [`ConnectionHandle`] decrements the connection count.
234    pub fn allocate_connection(
235        &self,
236        metadata: impl Into<UserMetadata>,
237    ) -> Result<Option<ConnectionHandle>, ConnectionError> {
238        let mut inner = self.inner.lock().expect("environmentd panicked");
239        let metadata = metadata.into();
240
241        if !metadata.should_limit_connections {
242            return Ok(None);
243        }
244
245        if (metadata.is_admin && inner.reserved_remaining() > 0)
246            || inner.non_reserved_remaining() > 0
247        {
248            inner.inc_connection_count();
249            Ok(Some(self.create_handle()))
250        } else {
251            Err(ConnectionError::TooManyConnections {
252                current: inner.current,
253                limit: inner.limit,
254            })
255        }
256    }
257
258    /// Updates the maximum number of connections we allow.
259    pub fn update_limit(&self, new_limit: u64) {
260        let mut inner = self.inner.lock().expect("environmentd panicked");
261        inner.limit = new_limit;
262    }
263
264    /// Updates the number of connections we reserve for superusers.
265    pub fn update_superuser_reserved(&self, new_reserve: u64) {
266        let mut inner = self.inner.lock().expect("environmentd panicked");
267        inner.superuser_reserved = new_reserve;
268    }
269
270    fn create_handle(&self) -> ConnectionHandle {
271        let inner = Arc::clone(&self.inner);
272        let decrement_fn = Box::new(move || {
273            let mut inner = inner.lock().expect("environmentd panicked");
274            inner.dec_connection_count();
275        });
276
277        ConnectionHandle {
278            decrement_fn: Some(decrement_fn),
279        }
280    }
281}
282
283impl Default for ConnectionCounter {
284    fn default() -> Self {
285        let inner = ConnectionCounterInner::new(10, 3);
286        ConnectionCounter {
287            inner: Arc::new(Mutex::new(inner)),
288        }
289    }
290}
291
292#[derive(Debug)]
293pub struct ConnectionCounterInner {
294    /// Current number of connections.
295    current: u64,
296    /// Total number of connections allowed.
297    limit: u64,
298    /// Number of connections in `limit` we'll reserve for superusers.
299    superuser_reserved: u64,
300}
301
302impl ConnectionCounterInner {
303    fn new(limit: u64, superuser_reserved: u64) -> Self {
304        assert!(superuser_reserved < limit);
305        ConnectionCounterInner {
306            current: 0,
307            limit,
308            superuser_reserved,
309        }
310    }
311
312    fn inc_connection_count(&mut self) {
313        self.current += 1;
314    }
315
316    fn dec_connection_count(&mut self) {
317        self.current -= 1;
318    }
319
320    /// The number of connections still available to superusers.
321    fn reserved_remaining(&self) -> u64 {
322        // Use a saturating sub in case the limit is reduced below the number
323        // of current connections.
324        self.limit.saturating_sub(self.current)
325    }
326
327    /// The number of connections available to non-superusers.
328    fn non_reserved_remaining(&self) -> u64 {
329        // This ensures that at least a few connections remain for superusers.
330        let limit = self.limit.saturating_sub(self.superuser_reserved);
331        // Use a saturating sub in case the limit is reduced below the number
332        // of current connections.
333        limit.saturating_sub(self.current)
334    }
335}
336
337/// Handle to an open connection, allows us to maintain a count of all connections.
338///
339/// When Drop-ed decrements the count of open connections.
340#[derive(Derivative)]
341#[derivative(Debug)]
342pub struct ConnectionHandle {
343    #[derivative(Debug = "ignore")]
344    decrement_fn: Option<Box<dyn FnOnce() -> () + Send + Sync>>,
345}
346
347impl Drop for ConnectionHandle {
348    fn drop(&mut self) {
349        match self.decrement_fn.take() {
350            Some(decrement_fn) => (decrement_fn)(),
351            None => tracing::error!("ConnectionHandle dropped twice!?"),
352        }
353    }
354}
355
356#[derive(Debug)]
357pub enum ConnectionError {
358    /// There were too many connections
359    TooManyConnections { current: u64, limit: u64 },
360}