LCOV - code coverage report
Current view: top level - proxy/src - proxy.rs (source / functions) Coverage Total Hit
Test: 4e30745f424539d3816b821c09fe7733c446c226.info Lines: 14.4 % 250 36
Test Date: 2024-06-19 13:20:49 Functions: 15.5 % 58 9

            Line data    Source code
       1              : #[cfg(test)]
       2              : mod tests;
       3              : 
       4              : pub mod connect_compute;
       5              : mod copy_bidirectional;
       6              : pub mod handshake;
       7              : pub mod passthrough;
       8              : pub mod retry;
       9              : pub mod wake_compute;
      10              : pub use copy_bidirectional::copy_bidirectional_client_compute;
      11              : 
      12              : use crate::{
      13              :     auth,
      14              :     cancellation::{self, CancellationHandlerMain, CancellationHandlerMainInternal},
      15              :     compute,
      16              :     config::{ProxyConfig, TlsConfig},
      17              :     context::RequestMonitoring,
      18              :     error::ReportableError,
      19              :     metrics::{Metrics, NumClientConnectionsGuard},
      20              :     protocol2::read_proxy_protocol,
      21              :     proxy::handshake::{handshake, HandshakeData},
      22              :     rate_limiter::EndpointRateLimiter,
      23              :     stream::{PqStream, Stream},
      24              :     EndpointCacheKey,
      25              : };
      26              : use futures::TryFutureExt;
      27              : use itertools::Itertools;
      28              : use once_cell::sync::OnceCell;
      29              : use pq_proto::{BeMessage as Be, StartupMessageParams};
      30              : use regex::Regex;
      31              : use smol_str::{format_smolstr, SmolStr};
      32              : use std::sync::Arc;
      33              : use thiserror::Error;
      34              : use tokio::io::{AsyncRead, AsyncWrite, AsyncWriteExt};
      35              : use tokio_util::sync::CancellationToken;
      36              : use tracing::{error, info, Instrument};
      37              : 
      38              : use self::{
      39              :     connect_compute::{connect_to_compute, TcpMechanism},
      40              :     passthrough::ProxyPassthrough,
      41              : };
      42              : 
      43              : const ERR_INSECURE_CONNECTION: &str = "connection is insecure (try using `sslmode=require`)";
      44              : 
      45            0 : pub async fn run_until_cancelled<F: std::future::Future>(
      46            0 :     f: F,
      47            0 :     cancellation_token: &CancellationToken,
      48            0 : ) -> Option<F::Output> {
      49            0 :     match futures::future::select(
      50            0 :         std::pin::pin!(f),
      51            0 :         std::pin::pin!(cancellation_token.cancelled()),
      52            0 :     )
      53            0 :     .await
      54              :     {
      55            0 :         futures::future::Either::Left((f, _)) => Some(f),
      56            0 :         futures::future::Either::Right(((), _)) => None,
      57              :     }
      58            0 : }
      59              : 
      60            0 : pub async fn task_main(
      61            0 :     config: &'static ProxyConfig,
      62            0 :     listener: tokio::net::TcpListener,
      63            0 :     cancellation_token: CancellationToken,
      64            0 :     cancellation_handler: Arc<CancellationHandlerMain>,
      65            0 :     endpoint_rate_limiter: Arc<EndpointRateLimiter>,
      66            0 : ) -> anyhow::Result<()> {
      67              :     scopeguard::defer! {
      68              :         info!("proxy has shut down");
      69              :     }
      70              : 
      71              :     // When set for the server socket, the keepalive setting
      72              :     // will be inherited by all accepted client sockets.
      73            0 :     socket2::SockRef::from(&listener).set_keepalive(true)?;
      74              : 
      75            0 :     let connections = tokio_util::task::task_tracker::TaskTracker::new();
      76              : 
      77            0 :     while let Some(accept_result) =
      78            0 :         run_until_cancelled(listener.accept(), &cancellation_token).await
      79              :     {
      80            0 :         let (socket, peer_addr) = accept_result?;
      81              : 
      82            0 :         let conn_gauge = Metrics::get()
      83            0 :             .proxy
      84            0 :             .client_connections
      85            0 :             .guard(crate::metrics::Protocol::Tcp);
      86            0 : 
      87            0 :         let session_id = uuid::Uuid::new_v4();
      88            0 :         let cancellation_handler = Arc::clone(&cancellation_handler);
      89            0 : 
      90            0 :         tracing::info!(protocol = "tcp", %session_id, "accepted new TCP connection");
      91            0 :         let endpoint_rate_limiter2 = endpoint_rate_limiter.clone();
      92            0 : 
      93            0 :         connections.spawn(async move {
      94            0 :             let (socket, peer_addr) = match read_proxy_protocol(socket).await{
      95            0 :                 Ok((socket, Some(addr))) => (socket, addr.ip()),
      96            0 :                 Err(e) => {
      97            0 :                     error!("per-client task finished with an error: {e:#}");
      98            0 :                     return;
      99              :                 }
     100            0 :                 Ok((_socket, None)) if config.require_client_ip => {
     101            0 :                     error!("missing required client IP");
     102            0 :                     return;
     103              :                 }
     104            0 :                 Ok((socket, None)) => (socket, peer_addr.ip())
     105              :             };
     106              : 
     107            0 :             match socket.inner.set_nodelay(true) {
     108            0 :                 Ok(()) => {},
     109            0 :                 Err(e) => {
     110            0 :                     error!("per-client task finished with an error: failed to set socket option: {e:#}");
     111            0 :                     return;
     112              :                 },
     113              :             };
     114              : 
     115            0 :             let mut ctx = RequestMonitoring::new(
     116            0 :                     session_id,
     117            0 :                     peer_addr,
     118            0 :                     crate::metrics::Protocol::Tcp,
     119            0 :                     &config.region,
     120            0 :                 );
     121            0 :             let span = ctx.span.clone();
     122              : 
     123            0 :             let res = handle_client(
     124            0 :                 config,
     125            0 :                 &mut ctx,
     126            0 :                 cancellation_handler,
     127            0 :                 socket,
     128            0 :                 ClientMode::Tcp,
     129            0 :                 endpoint_rate_limiter2,
     130            0 :                 conn_gauge,
     131            0 :             )
     132            0 :             .instrument(span.clone())
     133            0 :             .await;
     134              : 
     135            0 :             match res {
     136            0 :                 Err(e) => {
     137            0 :                     // todo: log and push to ctx the error kind
     138            0 :                     ctx.set_error_kind(e.get_error_kind());
     139              :                     error!(parent: &span, "per-client task finished with an error: {e:#}");
     140              :                 }
     141            0 :                 Ok(None) => {
     142            0 :                     ctx.set_success();
     143            0 :                 }
     144            0 :                 Ok(Some(p)) => {
     145            0 :                     ctx.set_success();
     146            0 :                     ctx.log_connect();
     147            0 :                     match p.proxy_pass().instrument(span.clone()).await {
     148            0 :                         Ok(()) => {}
     149            0 :                         Err(e) => {
     150            0 :                             error!(parent: &span, "per-client task finished with an error: {e:#}");
     151            0 :                         }
     152              :                     }
     153              :                 }
     154              :             }
     155            0 :         });
     156              :     }
     157              : 
     158            0 :     connections.close();
     159            0 :     drop(listener);
     160            0 : 
     161            0 :     // Drain connections
     162            0 :     connections.wait().await;
     163              : 
     164            0 :     Ok(())
     165            0 : }
     166              : 
     167              : pub enum ClientMode {
     168              :     Tcp,
     169              :     Websockets { hostname: Option<String> },
     170              : }
     171              : 
     172              : /// Abstracts the logic of handling TCP vs WS clients
     173              : impl ClientMode {
     174            0 :     pub fn allow_cleartext(&self) -> bool {
     175            0 :         match self {
     176            0 :             ClientMode::Tcp => false,
     177            0 :             ClientMode::Websockets { .. } => true,
     178              :         }
     179            0 :     }
     180              : 
     181            0 :     pub fn allow_self_signed_compute(&self, config: &ProxyConfig) -> bool {
     182            0 :         match self {
     183            0 :             ClientMode::Tcp => config.allow_self_signed_compute,
     184            0 :             ClientMode::Websockets { .. } => false,
     185              :         }
     186            0 :     }
     187              : 
     188            0 :     fn hostname<'a, S>(&'a self, s: &'a Stream<S>) -> Option<&'a str> {
     189            0 :         match self {
     190            0 :             ClientMode::Tcp => s.sni_hostname(),
     191            0 :             ClientMode::Websockets { hostname } => hostname.as_deref(),
     192              :         }
     193            0 :     }
     194              : 
     195            0 :     fn handshake_tls<'a>(&self, tls: Option<&'a TlsConfig>) -> Option<&'a TlsConfig> {
     196            0 :         match self {
     197            0 :             ClientMode::Tcp => tls,
     198              :             // TLS is None here if using websockets, because the connection is already encrypted.
     199            0 :             ClientMode::Websockets { .. } => None,
     200              :         }
     201            0 :     }
     202              : }
     203              : 
     204            0 : #[derive(Debug, Error)]
     205              : // almost all errors should be reported to the user, but there's a few cases where we cannot
     206              : // 1. Cancellation: we are not allowed to tell the client any cancellation statuses for security reasons
     207              : // 2. Handshake: handshake reports errors if it can, otherwise if the handshake fails due to protocol violation,
     208              : //    we cannot be sure the client even understands our error message
     209              : // 3. PrepareClient: The client disconnected, so we can't tell them anyway...
     210              : pub enum ClientRequestError {
     211              :     #[error("{0}")]
     212              :     Cancellation(#[from] cancellation::CancelError),
     213              :     #[error("{0}")]
     214              :     Handshake(#[from] handshake::HandshakeError),
     215              :     #[error("{0}")]
     216              :     HandshakeTimeout(#[from] tokio::time::error::Elapsed),
     217              :     #[error("{0}")]
     218              :     PrepareClient(#[from] std::io::Error),
     219              :     #[error("{0}")]
     220              :     ReportedError(#[from] crate::stream::ReportedError),
     221              : }
     222              : 
     223              : impl ReportableError for ClientRequestError {
     224            0 :     fn get_error_kind(&self) -> crate::error::ErrorKind {
     225            0 :         match self {
     226            0 :             ClientRequestError::Cancellation(e) => e.get_error_kind(),
     227            0 :             ClientRequestError::Handshake(e) => e.get_error_kind(),
     228            0 :             ClientRequestError::HandshakeTimeout(_) => crate::error::ErrorKind::RateLimit,
     229            0 :             ClientRequestError::ReportedError(e) => e.get_error_kind(),
     230            0 :             ClientRequestError::PrepareClient(_) => crate::error::ErrorKind::ClientDisconnect,
     231              :         }
     232            0 :     }
     233              : }
     234              : 
     235            0 : pub async fn handle_client<S: AsyncRead + AsyncWrite + Unpin>(
     236            0 :     config: &'static ProxyConfig,
     237            0 :     ctx: &mut RequestMonitoring,
     238            0 :     cancellation_handler: Arc<CancellationHandlerMain>,
     239            0 :     stream: S,
     240            0 :     mode: ClientMode,
     241            0 :     endpoint_rate_limiter: Arc<EndpointRateLimiter>,
     242            0 :     conn_gauge: NumClientConnectionsGuard<'static>,
     243            0 : ) -> Result<Option<ProxyPassthrough<CancellationHandlerMainInternal, S>>, ClientRequestError> {
     244            0 :     info!(
     245              :         protocol = %ctx.protocol,
     246            0 :         "handling interactive connection from client"
     247              :     );
     248              : 
     249            0 :     let metrics = &Metrics::get().proxy;
     250            0 :     let proto = ctx.protocol;
     251            0 :     let _request_gauge = metrics.connection_requests.guard(proto);
     252            0 : 
     253            0 :     let tls = config.tls_config.as_ref();
     254            0 : 
     255            0 :     let record_handshake_error = !ctx.has_private_peer_addr();
     256            0 :     let pause = ctx.latency_timer.pause(crate::metrics::Waiting::Client);
     257            0 :     let do_handshake = handshake(stream, mode.handshake_tls(tls), record_handshake_error);
     258            0 :     let (mut stream, params) =
     259            0 :         match tokio::time::timeout(config.handshake_timeout, do_handshake).await?? {
     260            0 :             HandshakeData::Startup(stream, params) => (stream, params),
     261            0 :             HandshakeData::Cancel(cancel_key_data) => {
     262            0 :                 return Ok(cancellation_handler
     263            0 :                     .cancel_session(cancel_key_data, ctx.session_id)
     264            0 :                     .await
     265            0 :                     .map(|()| None)?)
     266              :             }
     267              :         };
     268            0 :     drop(pause);
     269            0 : 
     270            0 :     ctx.set_db_options(params.clone());
     271            0 : 
     272            0 :     let hostname = mode.hostname(stream.get_ref());
     273            0 : 
     274            0 :     let common_names = tls.map(|tls| &tls.common_names);
     275            0 : 
     276            0 :     // Extract credentials which we're going to use for auth.
     277            0 :     let result = config
     278            0 :         .auth_backend
     279            0 :         .as_ref()
     280            0 :         .map(|_| auth::ComputeUserInfoMaybeEndpoint::parse(ctx, &params, hostname, common_names))
     281            0 :         .transpose();
     282              : 
     283            0 :     let user_info = match result {
     284            0 :         Ok(user_info) => user_info,
     285            0 :         Err(e) => stream.throw_error(e).await?,
     286              :     };
     287              : 
     288            0 :     let user = user_info.get_user().to_owned();
     289            0 :     let user_info = match user_info
     290            0 :         .authenticate(
     291            0 :             ctx,
     292            0 :             &mut stream,
     293            0 :             mode.allow_cleartext(),
     294            0 :             &config.authentication_config,
     295            0 :             endpoint_rate_limiter,
     296            0 :         )
     297            0 :         .await
     298              :     {
     299            0 :         Ok(auth_result) => auth_result,
     300            0 :         Err(e) => {
     301            0 :             let db = params.get("database");
     302            0 :             let app = params.get("application_name");
     303            0 :             let params_span = tracing::info_span!("", ?user, ?db, ?app);
     304              : 
     305            0 :             return stream.throw_error(e).instrument(params_span).await?;
     306              :         }
     307              :     };
     308              : 
     309            0 :     let mut node = connect_to_compute(
     310            0 :         ctx,
     311            0 :         &TcpMechanism {
     312            0 :             params: &params,
     313            0 :             locks: &config.connect_compute_locks,
     314            0 :         },
     315            0 :         &user_info,
     316            0 :         mode.allow_self_signed_compute(config),
     317            0 :         config.wake_compute_retry_config,
     318            0 :         config.connect_to_compute_retry_config,
     319            0 :     )
     320            0 :     .or_else(|e| stream.throw_error(e))
     321            0 :     .await?;
     322              : 
     323            0 :     let session = cancellation_handler.get_session();
     324            0 :     prepare_client_connection(&node, &session, &mut stream).await?;
     325              : 
     326              :     // Before proxy passing, forward to compute whatever data is left in the
     327              :     // PqStream input buffer. Normally there is none, but our serverless npm
     328              :     // driver in pipeline mode sends startup, password and first query
     329              :     // immediately after opening the connection.
     330            0 :     let (stream, read_buf) = stream.into_inner();
     331            0 :     node.stream.write_all(&read_buf).await?;
     332              : 
     333            0 :     Ok(Some(ProxyPassthrough {
     334            0 :         client: stream,
     335            0 :         aux: node.aux.clone(),
     336            0 :         compute: node,
     337            0 :         req: _request_gauge,
     338            0 :         conn: conn_gauge,
     339            0 :         cancel: session,
     340            0 :     }))
     341            0 : }
     342              : 
     343              : /// Finish client connection initialization: confirm auth success, send params, etc.
     344            0 : #[tracing::instrument(skip_all)]
     345              : async fn prepare_client_connection<P>(
     346              :     node: &compute::PostgresConnection,
     347              :     session: &cancellation::Session<P>,
     348              :     stream: &mut PqStream<impl AsyncRead + AsyncWrite + Unpin>,
     349              : ) -> Result<(), std::io::Error> {
     350              :     // Register compute's query cancellation token and produce a new, unique one.
     351              :     // The new token (cancel_key_data) will be sent to the client.
     352              :     let cancel_key_data = session.enable_query_cancellation(node.cancel_closure.clone());
     353              : 
     354              :     // Forward all postgres connection params to the client.
     355              :     // Right now the implementation is very hacky and inefficent (ideally,
     356              :     // we don't need an intermediate hashmap), but at least it should be correct.
     357              :     for (name, value) in &node.params {
     358              :         // TODO: Theoretically, this could result in a big pile of params...
     359              :         stream.write_message_noflush(&Be::ParameterStatus {
     360              :             name: name.as_bytes(),
     361              :             value: value.as_bytes(),
     362              :         })?;
     363              :     }
     364              : 
     365              :     stream
     366              :         .write_message_noflush(&Be::BackendKeyData(cancel_key_data))?
     367              :         .write_message(&Be::ReadyForQuery)
     368              :         .await?;
     369              : 
     370              :     Ok(())
     371              : }
     372              : 
     373              : #[derive(Debug, Clone, PartialEq, Eq, Default)]
     374              : pub struct NeonOptions(Vec<(SmolStr, SmolStr)>);
     375              : 
     376              : impl NeonOptions {
     377           22 :     pub fn parse_params(params: &StartupMessageParams) -> Self {
     378           22 :         params
     379           22 :             .options_raw()
     380           22 :             .map(Self::parse_from_iter)
     381           22 :             .unwrap_or_default()
     382           22 :     }
     383           14 :     pub fn parse_options_raw(options: &str) -> Self {
     384           14 :         Self::parse_from_iter(StartupMessageParams::parse_options_raw(options))
     385           14 :     }
     386              : 
     387            4 :     pub fn is_ephemeral(&self) -> bool {
     388            4 :         // Currently, neon endpoint options are all reserved for ephemeral endpoints.
     389            4 :         !self.0.is_empty()
     390            4 :     }
     391              : 
     392           26 :     fn parse_from_iter<'a>(options: impl Iterator<Item = &'a str>) -> Self {
     393           26 :         let mut options = options
     394           26 :             .filter_map(neon_option)
     395           26 :             .map(|(k, v)| (k.into(), v.into()))
     396           26 :             .collect_vec();
     397           26 :         options.sort();
     398           26 :         Self(options)
     399           26 :     }
     400              : 
     401            8 :     pub fn get_cache_key(&self, prefix: &str) -> EndpointCacheKey {
     402            8 :         // prefix + format!(" {k}:{v}")
     403            8 :         // kinda jank because SmolStr is immutable
     404            8 :         std::iter::once(prefix)
     405            8 :             .chain(self.0.iter().flat_map(|(k, v)| [" ", &**k, ":", &**v]))
     406            8 :             .collect::<SmolStr>()
     407            8 :             .into()
     408            8 :     }
     409              : 
     410              :     /// <https://swagger.io/docs/specification/serialization/> DeepObject format
     411              :     /// `paramName[prop1]=value1&paramName[prop2]=value2&...`
     412            0 :     pub fn to_deep_object(&self) -> Vec<(SmolStr, SmolStr)> {
     413            0 :         self.0
     414            0 :             .iter()
     415            0 :             .map(|(k, v)| (format_smolstr!("options[{}]", k), v.clone()))
     416            0 :             .collect()
     417            0 :     }
     418              : }
     419              : 
     420           64 : pub fn neon_option(bytes: &str) -> Option<(&str, &str)> {
     421           64 :     static RE: OnceCell<Regex> = OnceCell::new();
     422           64 :     let re = RE.get_or_init(|| Regex::new(r"^neon_(\w+):(.+)").unwrap());
     423              : 
     424           64 :     let cap = re.captures(bytes)?;
     425            8 :     let (_, [k, v]) = cap.extract();
     426            8 :     Some((k, v))
     427           64 : }
        

Generated by: LCOV version 2.1-beta