LCOV - code coverage report
Current view: top level - proxy/src - proxy.rs (source / functions) Coverage Total Hit
Test: b837401fb09d2d9818b70e630fdb67e9799b7b0d.info Lines: 14.6 % 247 36
Test Date: 2024-04-18 15:32:49 Functions: 12.5 % 72 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::WithClientIp,
      21              :     proxy::handshake::{handshake, HandshakeData},
      22              :     stream::{PqStream, Stream},
      23              :     EndpointCacheKey,
      24              : };
      25              : use futures::TryFutureExt;
      26              : use itertools::Itertools;
      27              : use once_cell::sync::OnceCell;
      28              : use pq_proto::{BeMessage as Be, StartupMessageParams};
      29              : use regex::Regex;
      30              : use smol_str::{format_smolstr, SmolStr};
      31              : use std::sync::Arc;
      32              : use thiserror::Error;
      33              : use tokio::io::{AsyncRead, AsyncWrite, AsyncWriteExt};
      34              : use tokio_util::sync::CancellationToken;
      35              : use tracing::{error, info, Instrument};
      36              : 
      37              : use self::{
      38              :     connect_compute::{connect_to_compute, TcpMechanism},
      39              :     passthrough::ProxyPassthrough,
      40              : };
      41              : 
      42              : const ERR_INSECURE_CONNECTION: &str = "connection is insecure (try using `sslmode=require`)";
      43              : 
      44            0 : pub async fn run_until_cancelled<F: std::future::Future>(
      45            0 :     f: F,
      46            0 :     cancellation_token: &CancellationToken,
      47            0 : ) -> Option<F::Output> {
      48            0 :     match futures::future::select(
      49            0 :         std::pin::pin!(f),
      50            0 :         std::pin::pin!(cancellation_token.cancelled()),
      51            0 :     )
      52            0 :     .await
      53              :     {
      54            0 :         futures::future::Either::Left((f, _)) => Some(f),
      55            0 :         futures::future::Either::Right(((), _)) => None,
      56              :     }
      57            0 : }
      58              : 
      59            0 : pub async fn task_main(
      60            0 :     config: &'static ProxyConfig,
      61            0 :     listener: tokio::net::TcpListener,
      62            0 :     cancellation_token: CancellationToken,
      63            0 :     cancellation_handler: Arc<CancellationHandlerMain>,
      64            0 : ) -> anyhow::Result<()> {
      65            0 :     scopeguard::defer! {
      66            0 :         info!("proxy has shut down");
      67              :     }
      68              : 
      69              :     // When set for the server socket, the keepalive setting
      70              :     // will be inherited by all accepted client sockets.
      71            0 :     socket2::SockRef::from(&listener).set_keepalive(true)?;
      72              : 
      73            0 :     let connections = tokio_util::task::task_tracker::TaskTracker::new();
      74              : 
      75            0 :     while let Some(accept_result) =
      76            0 :         run_until_cancelled(listener.accept(), &cancellation_token).await
      77              :     {
      78            0 :         let (socket, peer_addr) = accept_result?;
      79              : 
      80            0 :         let conn_gauge = Metrics::get()
      81            0 :             .proxy
      82            0 :             .client_connections
      83            0 :             .guard(crate::metrics::Protocol::Tcp);
      84            0 : 
      85            0 :         let session_id = uuid::Uuid::new_v4();
      86            0 :         let cancellation_handler = Arc::clone(&cancellation_handler);
      87            0 : 
      88            0 :         tracing::info!(protocol = "tcp", %session_id, "accepted new TCP connection");
      89              : 
      90            0 :         connections.spawn(async move {
      91            0 :             let mut socket = WithClientIp::new(socket);
      92            0 :             let mut peer_addr = peer_addr.ip();
      93            0 :             match socket.wait_for_addr().await {
      94            0 :                 Ok(Some(addr)) => peer_addr = addr.ip(),
      95            0 :                 Err(e) => {
      96            0 :                     error!("per-client task finished with an error: {e:#}");
      97            0 :                     return;
      98              :                 }
      99            0 :                 Ok(None) if config.require_client_ip => {
     100            0 :                     error!("missing required client IP");
     101            0 :                     return;
     102              :                 }
     103            0 :                 Ok(None) => {}
     104              :             }
     105              : 
     106            0 :             match socket.inner.set_nodelay(true) {
     107            0 :                 Ok(()) => {},
     108            0 :                 Err(e) => {
     109            0 :                     error!("per-client task finished with an error: failed to set socket option: {e:#}");
     110            0 :                     return;
     111              :                 },
     112              :             };
     113              : 
     114            0 :             let mut ctx = RequestMonitoring::new(
     115            0 :                     session_id,
     116            0 :                     peer_addr,
     117            0 :                     crate::metrics::Protocol::Tcp,
     118            0 :                     &config.region,
     119            0 :                 );
     120            0 :             let span = ctx.span.clone();
     121              : 
     122            0 :             let res = handle_client(
     123            0 :                 config,
     124            0 :                 &mut ctx,
     125            0 :                 cancellation_handler,
     126            0 :                 socket,
     127            0 :                 ClientMode::Tcp,
     128            0 :                 conn_gauge,
     129            0 :             )
     130            0 :             .instrument(span.clone())
     131            0 :             .await;
     132              : 
     133            0 :             match res {
     134            0 :                 Err(e) => {
     135            0 :                     // todo: log and push to ctx the error kind
     136            0 :                     ctx.set_error_kind(e.get_error_kind());
     137            0 :                     ctx.log();
     138            0 :                     error!(parent: &span, "per-client task finished with an error: {e:#}");
     139              :                 }
     140            0 :                 Ok(None) => {
     141            0 :                     ctx.set_success();
     142            0 :                     ctx.log();
     143            0 :                 }
     144            0 :                 Ok(Some(p)) => {
     145            0 :                     ctx.set_success();
     146            0 :                     ctx.log();
     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 :     conn_gauge: NumClientConnectionsGuard<'static>,
     242            0 : ) -> Result<Option<ProxyPassthrough<CancellationHandlerMainInternal, S>>, ClientRequestError> {
     243            0 :     info!(
     244            0 :         protocol = %ctx.protocol,
     245            0 :         "handling interactive connection from client"
     246            0 :     );
     247              : 
     248            0 :     let metrics = &Metrics::get().proxy;
     249            0 :     let proto = ctx.protocol;
     250            0 :     // let _client_gauge = metrics.client_connections.guard(proto);
     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 :     let hostname = mode.hostname(stream.get_ref());
     271            0 : 
     272            0 :     let common_names = tls.map(|tls| &tls.common_names);
     273            0 : 
     274            0 :     // Extract credentials which we're going to use for auth.
     275            0 :     let result = config
     276            0 :         .auth_backend
     277            0 :         .as_ref()
     278            0 :         .map(|_| auth::ComputeUserInfoMaybeEndpoint::parse(ctx, &params, hostname, common_names))
     279            0 :         .transpose();
     280              : 
     281            0 :     let user_info = match result {
     282            0 :         Ok(user_info) => user_info,
     283            0 :         Err(e) => stream.throw_error(e).await?,
     284              :     };
     285              : 
     286            0 :     let user = user_info.get_user().to_owned();
     287            0 :     let user_info = match user_info
     288            0 :         .authenticate(
     289            0 :             ctx,
     290            0 :             &mut stream,
     291            0 :             mode.allow_cleartext(),
     292            0 :             &config.authentication_config,
     293            0 :         )
     294            0 :         .await
     295              :     {
     296            0 :         Ok(auth_result) => auth_result,
     297            0 :         Err(e) => {
     298            0 :             let db = params.get("database");
     299            0 :             let app = params.get("application_name");
     300            0 :             let params_span = tracing::info_span!("", ?user, ?db, ?app);
     301              : 
     302            0 :             return stream.throw_error(e).instrument(params_span).await?;
     303              :         }
     304              :     };
     305              : 
     306            0 :     let mut node = connect_to_compute(
     307            0 :         ctx,
     308            0 :         &TcpMechanism { params: &params },
     309            0 :         &user_info,
     310            0 :         mode.allow_self_signed_compute(config),
     311            0 :     )
     312            0 :     .or_else(|e| stream.throw_error(e))
     313            0 :     .await?;
     314              : 
     315            0 :     let session = cancellation_handler.get_session();
     316            0 :     prepare_client_connection(&node, &session, &mut stream).await?;
     317              : 
     318              :     // Before proxy passing, forward to compute whatever data is left in the
     319              :     // PqStream input buffer. Normally there is none, but our serverless npm
     320              :     // driver in pipeline mode sends startup, password and first query
     321              :     // immediately after opening the connection.
     322            0 :     let (stream, read_buf) = stream.into_inner();
     323            0 :     node.stream.write_all(&read_buf).await?;
     324              : 
     325            0 :     Ok(Some(ProxyPassthrough {
     326            0 :         client: stream,
     327            0 :         aux: node.aux.clone(),
     328            0 :         compute: node,
     329            0 :         req: _request_gauge,
     330            0 :         conn: conn_gauge,
     331            0 :         cancel: session,
     332            0 :     }))
     333            0 : }
     334              : 
     335              : /// Finish client connection initialization: confirm auth success, send params, etc.
     336            0 : #[tracing::instrument(skip_all)]
     337              : async fn prepare_client_connection<P>(
     338              :     node: &compute::PostgresConnection,
     339              :     session: &cancellation::Session<P>,
     340              :     stream: &mut PqStream<impl AsyncRead + AsyncWrite + Unpin>,
     341              : ) -> Result<(), std::io::Error> {
     342              :     // Register compute's query cancellation token and produce a new, unique one.
     343              :     // The new token (cancel_key_data) will be sent to the client.
     344              :     let cancel_key_data = session.enable_query_cancellation(node.cancel_closure.clone());
     345              : 
     346              :     // Forward all postgres connection params to the client.
     347              :     // Right now the implementation is very hacky and inefficent (ideally,
     348              :     // we don't need an intermediate hashmap), but at least it should be correct.
     349              :     for (name, value) in &node.params {
     350              :         // TODO: Theoretically, this could result in a big pile of params...
     351              :         stream.write_message_noflush(&Be::ParameterStatus {
     352              :             name: name.as_bytes(),
     353              :             value: value.as_bytes(),
     354              :         })?;
     355              :     }
     356              : 
     357              :     stream
     358              :         .write_message_noflush(&Be::BackendKeyData(cancel_key_data))?
     359              :         .write_message(&Be::ReadyForQuery)
     360              :         .await?;
     361              : 
     362              :     Ok(())
     363              : }
     364              : 
     365              : #[derive(Debug, Clone, PartialEq, Eq, Default)]
     366              : pub struct NeonOptions(Vec<(SmolStr, SmolStr)>);
     367              : 
     368              : impl NeonOptions {
     369           22 :     pub fn parse_params(params: &StartupMessageParams) -> Self {
     370           22 :         params
     371           22 :             .options_raw()
     372           22 :             .map(Self::parse_from_iter)
     373           22 :             .unwrap_or_default()
     374           22 :     }
     375           14 :     pub fn parse_options_raw(options: &str) -> Self {
     376           14 :         Self::parse_from_iter(StartupMessageParams::parse_options_raw(options))
     377           14 :     }
     378              : 
     379            4 :     pub fn is_ephemeral(&self) -> bool {
     380            4 :         // Currently, neon endpoint options are all reserved for ephemeral endpoints.
     381            4 :         !self.0.is_empty()
     382            4 :     }
     383              : 
     384           26 :     fn parse_from_iter<'a>(options: impl Iterator<Item = &'a str>) -> Self {
     385           26 :         let mut options = options
     386           26 :             .filter_map(neon_option)
     387           26 :             .map(|(k, v)| (k.into(), v.into()))
     388           26 :             .collect_vec();
     389           26 :         options.sort();
     390           26 :         Self(options)
     391           26 :     }
     392              : 
     393            8 :     pub fn get_cache_key(&self, prefix: &str) -> EndpointCacheKey {
     394            8 :         // prefix + format!(" {k}:{v}")
     395            8 :         // kinda jank because SmolStr is immutable
     396            8 :         std::iter::once(prefix)
     397            8 :             .chain(self.0.iter().flat_map(|(k, v)| [" ", &**k, ":", &**v]))
     398            8 :             .collect::<SmolStr>()
     399            8 :             .into()
     400            8 :     }
     401              : 
     402              :     /// <https://swagger.io/docs/specification/serialization/> DeepObject format
     403              :     /// `paramName[prop1]=value1&paramName[prop2]=value2&...`
     404            0 :     pub fn to_deep_object(&self) -> Vec<(SmolStr, SmolStr)> {
     405            0 :         self.0
     406            0 :             .iter()
     407            0 :             .map(|(k, v)| (format_smolstr!("options[{}]", k), v.clone()))
     408            0 :             .collect()
     409            0 :     }
     410              : }
     411              : 
     412           64 : pub fn neon_option(bytes: &str) -> Option<(&str, &str)> {
     413           64 :     static RE: OnceCell<Regex> = OnceCell::new();
     414           64 :     let re = RE.get_or_init(|| Regex::new(r"^neon_(\w+):(.+)").unwrap());
     415              : 
     416           64 :     let cap = re.captures(bytes)?;
     417            8 :     let (_, [k, v]) = cap.extract();
     418            8 :     Some((k, v))
     419           64 : }
        

Generated by: LCOV version 2.1-beta