LCOV - code coverage report
Current view: top level - proxy/src - proxy.rs (source / functions) Coverage Total Hit
Test: 190869232aac3a234374e5bb62582e91cf5f5818.info Lines: 13.4 % 246 33
Test Date: 2024-02-23 13:21:27 Functions: 14.1 % 71 10

            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              : 
      11              : use crate::{
      12              :     auth,
      13              :     cancellation::{self, CancellationHandler},
      14              :     compute,
      15              :     config::{ProxyConfig, TlsConfig},
      16              :     context::RequestMonitoring,
      17              :     error::ReportableError,
      18              :     metrics::{NUM_CLIENT_CONNECTION_GAUGE, NUM_CONNECTION_REQUESTS_GAUGE},
      19              :     protocol2::WithClientIp,
      20              :     proxy::handshake::{handshake, HandshakeData},
      21              :     rate_limiter::EndpointRateLimiter,
      22              :     stream::{PqStream, Stream},
      23              :     EndpointCacheKey,
      24              : };
      25              : use anyhow::{bail, Context};
      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, info_span, 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 :     endpoint_rate_limiter: Arc<EndpointRateLimiter>,
      65            0 :     cancellation_handler: Arc<CancellationHandler>,
      66            0 : ) -> anyhow::Result<()> {
      67            0 :     scopeguard::defer! {
      68            0 :         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 session_id = uuid::Uuid::new_v4();
      83            0 :         let cancellation_handler = Arc::clone(&cancellation_handler);
      84            0 :         let endpoint_rate_limiter = endpoint_rate_limiter.clone();
      85              : 
      86            0 :         let session_span = info_span!(
      87            0 :             "handle_client",
      88            0 :             ?session_id,
      89            0 :             peer_addr = tracing::field::Empty,
      90            0 :             ep = tracing::field::Empty,
      91            0 :         );
      92              : 
      93            0 :         connections.spawn(
      94            0 :             async move {
      95            0 :                 info!("accepted postgres client connection");
      96              : 
      97            0 :                 let mut socket = WithClientIp::new(socket);
      98            0 :                 let mut peer_addr = peer_addr.ip();
      99            0 :                 if let Some(addr) = socket.wait_for_addr().await? {
     100            0 :                     peer_addr = addr.ip();
     101            0 :                     tracing::Span::current().record("peer_addr", &tracing::field::display(addr));
     102            0 :                 } else if config.require_client_ip {
     103            0 :                     bail!("missing required client IP");
     104            0 :                 }
     105              : 
     106            0 :                 socket
     107            0 :                     .inner
     108            0 :                     .set_nodelay(true)
     109            0 :                     .context("failed to set socket option")?;
     110              : 
     111            0 :                 let mut ctx = RequestMonitoring::new(session_id, peer_addr, "tcp", &config.region);
     112              : 
     113            0 :                 let res = handle_client(
     114            0 :                     config,
     115            0 :                     &mut ctx,
     116            0 :                     cancellation_handler,
     117            0 :                     socket,
     118            0 :                     ClientMode::Tcp,
     119            0 :                     endpoint_rate_limiter,
     120            0 :                 )
     121            0 :                 .await;
     122              : 
     123            0 :                 match res {
     124            0 :                     Err(e) => {
     125            0 :                         // todo: log and push to ctx the error kind
     126            0 :                         ctx.set_error_kind(e.get_error_kind());
     127            0 :                         ctx.log();
     128            0 :                         Err(e.into())
     129              :                     }
     130              :                     Ok(None) => {
     131            0 :                         ctx.set_success();
     132            0 :                         ctx.log();
     133            0 :                         Ok(())
     134              :                     }
     135            0 :                     Ok(Some(p)) => {
     136            0 :                         ctx.set_success();
     137            0 :                         ctx.log();
     138            0 :                         p.proxy_pass().await
     139              :                     }
     140              :                 }
     141            0 :             }
     142            0 :             .unwrap_or_else(move |e| {
     143            0 :                 // Acknowledge that the task has finished with an error.
     144            0 :                 error!("per-client task finished with an error: {e:#}");
     145            0 :             })
     146            0 :             .instrument(session_span),
     147            0 :         );
     148              :     }
     149              : 
     150            0 :     connections.close();
     151            0 :     drop(listener);
     152            0 : 
     153            0 :     // Drain connections
     154            0 :     connections.wait().await;
     155              : 
     156            0 :     Ok(())
     157            0 : }
     158              : 
     159              : pub enum ClientMode {
     160              :     Tcp,
     161              :     Websockets { hostname: Option<String> },
     162              : }
     163              : 
     164              : /// Abstracts the logic of handling TCP vs WS clients
     165              : impl ClientMode {
     166            0 :     pub fn allow_cleartext(&self) -> bool {
     167            0 :         match self {
     168            0 :             ClientMode::Tcp => false,
     169            0 :             ClientMode::Websockets { .. } => true,
     170              :         }
     171            0 :     }
     172              : 
     173            0 :     pub fn allow_self_signed_compute(&self, config: &ProxyConfig) -> bool {
     174            0 :         match self {
     175            0 :             ClientMode::Tcp => config.allow_self_signed_compute,
     176            0 :             ClientMode::Websockets { .. } => false,
     177              :         }
     178            0 :     }
     179              : 
     180            0 :     fn hostname<'a, S>(&'a self, s: &'a Stream<S>) -> Option<&'a str> {
     181            0 :         match self {
     182            0 :             ClientMode::Tcp => s.sni_hostname(),
     183            0 :             ClientMode::Websockets { hostname } => hostname.as_deref(),
     184              :         }
     185            0 :     }
     186              : 
     187            0 :     fn handshake_tls<'a>(&self, tls: Option<&'a TlsConfig>) -> Option<&'a TlsConfig> {
     188            0 :         match self {
     189            0 :             ClientMode::Tcp => tls,
     190              :             // TLS is None here if using websockets, because the connection is already encrypted.
     191            0 :             ClientMode::Websockets { .. } => None,
     192              :         }
     193            0 :     }
     194              : }
     195              : 
     196            0 : #[derive(Debug, Error)]
     197              : // almost all errors should be reported to the user, but there's a few cases where we cannot
     198              : // 1. Cancellation: we are not allowed to tell the client any cancellation statuses for security reasons
     199              : // 2. Handshake: handshake reports errors if it can, otherwise if the handshake fails due to protocol violation,
     200              : //    we cannot be sure the client even understands our error message
     201              : // 3. PrepareClient: The client disconnected, so we can't tell them anyway...
     202              : pub enum ClientRequestError {
     203              :     #[error("{0}")]
     204              :     Cancellation(#[from] cancellation::CancelError),
     205              :     #[error("{0}")]
     206              :     Handshake(#[from] handshake::HandshakeError),
     207              :     #[error("{0}")]
     208              :     HandshakeTimeout(#[from] tokio::time::error::Elapsed),
     209              :     #[error("{0}")]
     210              :     PrepareClient(#[from] std::io::Error),
     211              :     #[error("{0}")]
     212              :     ReportedError(#[from] crate::stream::ReportedError),
     213              : }
     214              : 
     215              : impl ReportableError for ClientRequestError {
     216            0 :     fn get_error_kind(&self) -> crate::error::ErrorKind {
     217            0 :         match self {
     218            0 :             ClientRequestError::Cancellation(e) => e.get_error_kind(),
     219            0 :             ClientRequestError::Handshake(e) => e.get_error_kind(),
     220            0 :             ClientRequestError::HandshakeTimeout(_) => crate::error::ErrorKind::RateLimit,
     221            0 :             ClientRequestError::ReportedError(e) => e.get_error_kind(),
     222            0 :             ClientRequestError::PrepareClient(_) => crate::error::ErrorKind::ClientDisconnect,
     223              :         }
     224            0 :     }
     225              : }
     226              : 
     227            0 : pub async fn handle_client<S: AsyncRead + AsyncWrite + Unpin>(
     228            0 :     config: &'static ProxyConfig,
     229            0 :     ctx: &mut RequestMonitoring,
     230            0 :     cancellation_handler: Arc<CancellationHandler>,
     231            0 :     stream: S,
     232            0 :     mode: ClientMode,
     233            0 :     endpoint_rate_limiter: Arc<EndpointRateLimiter>,
     234            0 : ) -> Result<Option<ProxyPassthrough<S>>, ClientRequestError> {
     235            0 :     info!(
     236            0 :         protocol = ctx.protocol,
     237            0 :         "handling interactive connection from client"
     238            0 :     );
     239              : 
     240            0 :     let proto = ctx.protocol;
     241            0 :     let _client_gauge = NUM_CLIENT_CONNECTION_GAUGE
     242            0 :         .with_label_values(&[proto])
     243            0 :         .guard();
     244            0 :     let _request_gauge = NUM_CONNECTION_REQUESTS_GAUGE
     245            0 :         .with_label_values(&[proto])
     246            0 :         .guard();
     247            0 : 
     248            0 :     let tls = config.tls_config.as_ref();
     249            0 : 
     250            0 :     let pause = ctx.latency_timer.pause();
     251            0 :     let do_handshake = handshake(stream, mode.handshake_tls(tls));
     252            0 :     let (mut stream, params) =
     253            0 :         match tokio::time::timeout(config.handshake_timeout, do_handshake).await?? {
     254            0 :             HandshakeData::Startup(stream, params) => (stream, params),
     255            0 :             HandshakeData::Cancel(cancel_key_data) => {
     256            0 :                 return Ok(cancellation_handler
     257            0 :                     .cancel_session(cancel_key_data, ctx.session_id)
     258            0 :                     .await
     259            0 :                     .map(|()| None)?)
     260              :             }
     261              :         };
     262            0 :     drop(pause);
     263            0 : 
     264            0 :     let hostname = mode.hostname(stream.get_ref());
     265            0 : 
     266            0 :     let common_names = tls.map(|tls| &tls.common_names);
     267            0 : 
     268            0 :     // Extract credentials which we're going to use for auth.
     269            0 :     let result = config
     270            0 :         .auth_backend
     271            0 :         .as_ref()
     272            0 :         .map(|_| auth::ComputeUserInfoMaybeEndpoint::parse(ctx, &params, hostname, common_names))
     273            0 :         .transpose();
     274              : 
     275            0 :     let user_info = match result {
     276            0 :         Ok(user_info) => user_info,
     277            0 :         Err(e) => stream.throw_error(e).await?,
     278              :     };
     279              : 
     280              :     // check rate limit
     281            0 :     if let Some(ep) = user_info.get_endpoint() {
     282            0 :         if !endpoint_rate_limiter.check(ep) {
     283            0 :             return stream
     284            0 :                 .throw_error(auth::AuthError::too_many_connections())
     285            0 :                 .await?;
     286            0 :         }
     287            0 :     }
     288              : 
     289            0 :     let user = user_info.get_user().to_owned();
     290            0 :     let user_info = match user_info
     291            0 :         .authenticate(
     292            0 :             ctx,
     293            0 :             &mut stream,
     294            0 :             mode.allow_cleartext(),
     295            0 :             &config.authentication_config,
     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 { params: &params },
     312            0 :         &user_info,
     313            0 :         mode.allow_self_signed_compute(config),
     314            0 :     )
     315            0 :     .or_else(|e| stream.throw_error(e))
     316            0 :     .await?;
     317              : 
     318            0 :     let session = cancellation_handler.get_session();
     319            0 :     prepare_client_connection(&node, &session, &mut stream).await?;
     320              : 
     321              :     // Before proxy passing, forward to compute whatever data is left in the
     322              :     // PqStream input buffer. Normally there is none, but our serverless npm
     323              :     // driver in pipeline mode sends startup, password and first query
     324              :     // immediately after opening the connection.
     325            0 :     let (stream, read_buf) = stream.into_inner();
     326            0 :     node.stream.write_all(&read_buf).await?;
     327              : 
     328            0 :     Ok(Some(ProxyPassthrough {
     329            0 :         client: stream,
     330            0 :         aux: node.aux.clone(),
     331            0 :         compute: node,
     332            0 :         req: _request_gauge,
     333            0 :         conn: _client_gauge,
     334            0 :         cancel: session,
     335            0 :     }))
     336            0 : }
     337              : 
     338              : /// Finish client connection initialization: confirm auth success, send params, etc.
     339            0 : #[tracing::instrument(skip_all)]
     340              : async fn prepare_client_connection(
     341              :     node: &compute::PostgresConnection,
     342              :     session: &cancellation::Session,
     343              :     stream: &mut PqStream<impl AsyncRead + AsyncWrite + Unpin>,
     344              : ) -> Result<(), std::io::Error> {
     345              :     // Register compute's query cancellation token and produce a new, unique one.
     346              :     // The new token (cancel_key_data) will be sent to the client.
     347              :     let cancel_key_data = session.enable_query_cancellation(node.cancel_closure.clone());
     348              : 
     349              :     // Forward all postgres connection params to the client.
     350              :     // Right now the implementation is very hacky and inefficent (ideally,
     351              :     // we don't need an intermediate hashmap), but at least it should be correct.
     352              :     for (name, value) in &node.params {
     353              :         // TODO: Theoretically, this could result in a big pile of params...
     354              :         stream.write_message_noflush(&Be::ParameterStatus {
     355              :             name: name.as_bytes(),
     356              :             value: value.as_bytes(),
     357              :         })?;
     358              :     }
     359              : 
     360              :     stream
     361              :         .write_message_noflush(&Be::BackendKeyData(cancel_key_data))?
     362              :         .write_message(&Be::ReadyForQuery)
     363              :         .await?;
     364              : 
     365              :     Ok(())
     366              : }
     367              : 
     368           26 : #[derive(Debug, Clone, PartialEq, Eq, Default)]
     369              : pub struct NeonOptions(Vec<(SmolStr, SmolStr)>);
     370              : 
     371              : impl NeonOptions {
     372           22 :     pub fn parse_params(params: &StartupMessageParams) -> Self {
     373           22 :         params
     374           22 :             .options_raw()
     375           22 :             .map(Self::parse_from_iter)
     376           22 :             .unwrap_or_default()
     377           22 :     }
     378           14 :     pub fn parse_options_raw(options: &str) -> Self {
     379           14 :         Self::parse_from_iter(StartupMessageParams::parse_options_raw(options))
     380           14 :     }
     381              : 
     382           26 :     fn parse_from_iter<'a>(options: impl Iterator<Item = &'a str>) -> Self {
     383           26 :         let mut options = options
     384           26 :             .filter_map(neon_option)
     385           26 :             .map(|(k, v)| (k.into(), v.into()))
     386           26 :             .collect_vec();
     387           26 :         options.sort();
     388           26 :         Self(options)
     389           26 :     }
     390              : 
     391            8 :     pub fn get_cache_key(&self, prefix: &str) -> EndpointCacheKey {
     392            8 :         // prefix + format!(" {k}:{v}")
     393            8 :         // kinda jank because SmolStr is immutable
     394            8 :         std::iter::once(prefix)
     395            8 :             .chain(self.0.iter().flat_map(|(k, v)| [" ", &**k, ":", &**v]))
     396            8 :             .collect::<SmolStr>()
     397            8 :             .into()
     398            8 :     }
     399              : 
     400              :     /// <https://swagger.io/docs/specification/serialization/> DeepObject format
     401              :     /// `paramName[prop1]=value1&paramName[prop2]=value2&...`
     402            0 :     pub fn to_deep_object(&self) -> Vec<(SmolStr, SmolStr)> {
     403            0 :         self.0
     404            0 :             .iter()
     405            0 :             .map(|(k, v)| (format_smolstr!("options[{}]", k), v.clone()))
     406            0 :             .collect()
     407            0 :     }
     408              : }
     409              : 
     410           64 : pub fn neon_option(bytes: &str) -> Option<(&str, &str)> {
     411           64 :     static RE: OnceCell<Regex> = OnceCell::new();
     412           64 :     let re = RE.get_or_init(|| Regex::new(r"^neon_(\w+):(.+)").unwrap());
     413              : 
     414           64 :     let cap = re.captures(bytes)?;
     415            8 :     let (_, [k, v]) = cap.extract();
     416            8 :     Some((k, v))
     417           64 : }
        

Generated by: LCOV version 2.1-beta