LCOV - code coverage report
Current view: top level - proxy/src/binary - pg_sni_router.rs (source / functions) Coverage Total Hit
Test: 1e20c4f2b28aa592527961bb32170ebbd2c9172f.info Lines: 0.0 % 232 0
Test Date: 2025-07-16 12:29:03 Functions: 0.0 % 14 0

            Line data    Source code
       1              : //! A stand-alone program that routes connections, e.g. from
       2              : //! `aaa--bbb--1234.external.domain` to `aaa.bbb.internal.domain:1234`.
       3              : //!
       4              : //! This allows connecting to pods/services running in the same Kubernetes cluster from
       5              : //! the outside. Similar to an ingress controller for HTTPS.
       6              : 
       7              : use std::io;
       8              : use std::net::SocketAddr;
       9              : use std::path::Path;
      10              : use std::sync::Arc;
      11              : 
      12              : use anyhow::{Context, anyhow, bail, ensure};
      13              : use clap::Arg;
      14              : use futures::future::Either;
      15              : use futures::{FutureExt, TryFutureExt};
      16              : use itertools::Itertools;
      17              : use rustls::crypto::ring;
      18              : use rustls::pki_types::{DnsName, PrivateKeyDer};
      19              : use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt};
      20              : use tokio::net::TcpListener;
      21              : use tokio_rustls::TlsConnector;
      22              : use tokio_rustls::server::TlsStream;
      23              : use tokio_util::sync::CancellationToken;
      24              : use tracing::{Instrument, error, info};
      25              : use utils::project_git_version;
      26              : use utils::sentry_init::init_sentry;
      27              : 
      28              : use crate::context::RequestContext;
      29              : use crate::metrics::{Metrics, ThreadPoolMetrics};
      30              : use crate::pglb::TlsRequired;
      31              : use crate::pqproto::FeStartupPacket;
      32              : use crate::protocol2::ConnectionInfo;
      33              : use crate::proxy::{ErrorSource, copy_bidirectional_client_compute};
      34              : use crate::stream::{PqStream, Stream};
      35              : use crate::util::run_until_cancelled;
      36              : 
      37              : project_git_version!(GIT_VERSION);
      38              : 
      39            0 : fn cli() -> clap::Command {
      40            0 :     clap::Command::new("Neon proxy/router")
      41            0 :         .version(GIT_VERSION)
      42            0 :         .arg(
      43            0 :             Arg::new("listen")
      44            0 :                 .short('l')
      45            0 :                 .long("listen")
      46            0 :                 .help("listen for incoming client connections on ip:port")
      47            0 :                 .default_value("127.0.0.1:4432"),
      48              :         )
      49            0 :         .arg(
      50            0 :             Arg::new("listen-tls")
      51            0 :                 .long("listen-tls")
      52            0 :                 .help("listen for incoming client connections on ip:port, requiring TLS to compute")
      53            0 :                 .default_value("127.0.0.1:4433"),
      54              :         )
      55            0 :         .arg(
      56            0 :             Arg::new("tls-key")
      57            0 :                 .short('k')
      58            0 :                 .long("tls-key")
      59            0 :                 .help("path to TLS key for client postgres connections")
      60            0 :                 .required(true),
      61              :         )
      62            0 :         .arg(
      63            0 :             Arg::new("tls-cert")
      64            0 :                 .short('c')
      65            0 :                 .long("tls-cert")
      66            0 :                 .help("path to TLS cert for client postgres connections")
      67            0 :                 .required(true),
      68              :         )
      69            0 :         .arg(
      70            0 :             Arg::new("dest")
      71            0 :                 .short('d')
      72            0 :                 .long("destination")
      73            0 :                 .help("append this domain zone to the SNI hostname to get the destination address")
      74            0 :                 .required(true),
      75              :         )
      76            0 : }
      77              : 
      78            0 : pub async fn run() -> anyhow::Result<()> {
      79            0 :     let _logging_guard = crate::logging::init().await?;
      80            0 :     let _panic_hook_guard = utils::logging::replace_panic_hook_with_tracing_panic_hook();
      81            0 :     let _sentry_guard = init_sentry(Some(GIT_VERSION.into()), &[]);
      82              : 
      83            0 :     Metrics::install(Arc::new(ThreadPoolMetrics::new(0)));
      84              : 
      85            0 :     let args = cli().get_matches();
      86            0 :     let destination: String = args
      87            0 :         .get_one::<String>("dest")
      88            0 :         .expect("string argument defined")
      89            0 :         .parse()?;
      90              : 
      91              :     // Configure TLS
      92            0 :     let tls_config = match (
      93            0 :         args.get_one::<String>("tls-key"),
      94            0 :         args.get_one::<String>("tls-cert"),
      95              :     ) {
      96            0 :         (Some(key_path), Some(cert_path)) => parse_tls(key_path.as_ref(), cert_path.as_ref())?,
      97            0 :         _ => bail!("tls-key and tls-cert must be specified"),
      98              :     };
      99              : 
     100            0 :     let compute_tls_config =
     101            0 :         Arc::new(crate::tls::client_config::compute_client_config_with_root_certs()?);
     102              : 
     103              :     // Start listening for incoming client connections
     104            0 :     let proxy_address: SocketAddr = args
     105            0 :         .get_one::<String>("listen")
     106            0 :         .expect("listen argument defined")
     107            0 :         .parse()?;
     108            0 :     let proxy_address_compute_tls: SocketAddr = args
     109            0 :         .get_one::<String>("listen-tls")
     110            0 :         .expect("listen-tls argument defined")
     111            0 :         .parse()?;
     112              : 
     113            0 :     info!("Starting sni router on {proxy_address}");
     114            0 :     info!("Starting sni router on {proxy_address_compute_tls}");
     115            0 :     let proxy_listener = TcpListener::bind(proxy_address).await?;
     116            0 :     let proxy_listener_compute_tls = TcpListener::bind(proxy_address_compute_tls).await?;
     117              : 
     118            0 :     let cancellation_token = CancellationToken::new();
     119            0 :     let dest = Arc::new(destination);
     120              : 
     121            0 :     let main = tokio::spawn(task_main(
     122            0 :         dest.clone(),
     123            0 :         tls_config.clone(),
     124            0 :         None,
     125            0 :         proxy_listener,
     126            0 :         cancellation_token.clone(),
     127              :     ))
     128            0 :     .map(crate::error::flatten_err);
     129              : 
     130            0 :     let main_tls = tokio::spawn(task_main(
     131            0 :         dest,
     132            0 :         tls_config,
     133            0 :         Some(compute_tls_config),
     134            0 :         proxy_listener_compute_tls,
     135            0 :         cancellation_token.clone(),
     136              :     ))
     137            0 :     .map(crate::error::flatten_err);
     138            0 :     let signals_task = tokio::spawn(crate::signals::handle(cancellation_token, || {}));
     139              : 
     140              :     // the signal task cant ever succeed.
     141              :     // the main task can error, or can succeed on cancellation.
     142              :     // we want to immediately exit on either of these cases
     143            0 :     let main = futures::future::try_join(main, main_tls);
     144            0 :     let signal = match futures::future::select(signals_task, main).await {
     145            0 :         Either::Left((res, _)) => crate::error::flatten_err(res)?,
     146            0 :         Either::Right((res, _)) => {
     147            0 :             res?;
     148            0 :             return Ok(());
     149              :         }
     150              :     };
     151              : 
     152              :     // maintenance tasks return `Infallible` success values, this is an impossible value
     153              :     // so this match statically ensures that there are no possibilities for that value
     154              :     match signal {}
     155            0 : }
     156              : 
     157            0 : pub(super) fn parse_tls(
     158            0 :     key_path: &Path,
     159            0 :     cert_path: &Path,
     160            0 : ) -> anyhow::Result<Arc<rustls::ServerConfig>> {
     161            0 :     let key = {
     162            0 :         let key_bytes = std::fs::read(key_path).context("TLS key file")?;
     163              : 
     164            0 :         let mut keys = rustls_pemfile::pkcs8_private_keys(&mut &key_bytes[..]).collect_vec();
     165              : 
     166            0 :         ensure!(keys.len() == 1, "keys.len() = {} (should be 1)", keys.len());
     167              :         PrivateKeyDer::Pkcs8(
     168            0 :             keys.pop()
     169            0 :                 .expect("keys should not be empty")
     170            0 :                 .context(format!(
     171            0 :                     "Failed to read TLS keys at '{}'",
     172            0 :                     key_path.display()
     173            0 :                 ))?,
     174              :         )
     175              :     };
     176              : 
     177            0 :     let cert_chain_bytes = std::fs::read(cert_path).context(format!(
     178            0 :         "Failed to read TLS cert file at '{}.'",
     179            0 :         cert_path.display()
     180            0 :     ))?;
     181              : 
     182            0 :     let cert_chain: Vec<_> = {
     183            0 :         rustls_pemfile::certs(&mut &cert_chain_bytes[..])
     184            0 :             .try_collect()
     185            0 :             .with_context(|| {
     186            0 :                 format!(
     187            0 :                     "Failed to read TLS certificate chain from bytes from file at '{}'.",
     188            0 :                     cert_path.display()
     189              :                 )
     190            0 :             })?
     191              :     };
     192              : 
     193            0 :     let tls_config =
     194            0 :         rustls::ServerConfig::builder_with_provider(Arc::new(ring::default_provider()))
     195            0 :             .with_protocol_versions(&[&rustls::version::TLS13, &rustls::version::TLS12])
     196            0 :             .context("ring should support TLS1.2 and TLS1.3")?
     197            0 :             .with_no_client_auth()
     198            0 :             .with_single_cert(cert_chain, key)?
     199            0 :             .into();
     200              : 
     201            0 :     Ok(tls_config)
     202            0 : }
     203              : 
     204            0 : pub(super) async fn task_main(
     205            0 :     dest_suffix: Arc<String>,
     206            0 :     tls_config: Arc<rustls::ServerConfig>,
     207            0 :     compute_tls_config: Option<Arc<rustls::ClientConfig>>,
     208            0 :     listener: tokio::net::TcpListener,
     209            0 :     cancellation_token: CancellationToken,
     210            0 : ) -> anyhow::Result<()> {
     211              :     // When set for the server socket, the keepalive setting
     212              :     // will be inherited by all accepted client sockets.
     213            0 :     socket2::SockRef::from(&listener).set_keepalive(true)?;
     214              : 
     215            0 :     let connections = tokio_util::task::task_tracker::TaskTracker::new();
     216              : 
     217            0 :     while let Some(accept_result) =
     218            0 :         run_until_cancelled(listener.accept(), &cancellation_token).await
     219              :     {
     220            0 :         let (socket, peer_addr) = accept_result?;
     221              : 
     222            0 :         let session_id = uuid::Uuid::new_v4();
     223            0 :         let tls_config = Arc::clone(&tls_config);
     224            0 :         let dest_suffix = Arc::clone(&dest_suffix);
     225            0 :         let compute_tls_config = compute_tls_config.clone();
     226              : 
     227            0 :         connections.spawn(
     228            0 :             async move {
     229            0 :                 socket
     230            0 :                     .set_nodelay(true)
     231            0 :                     .context("failed to set socket option")?;
     232              : 
     233            0 :                 let ctx = RequestContext::new(
     234            0 :                     session_id,
     235            0 :                     ConnectionInfo {
     236            0 :                         addr: peer_addr,
     237            0 :                         extra: None,
     238            0 :                     },
     239            0 :                     crate::metrics::Protocol::SniRouter,
     240              :                 );
     241            0 :                 handle_client(ctx, dest_suffix, tls_config, compute_tls_config, socket).await
     242            0 :             }
     243            0 :             .unwrap_or_else(|e| {
     244            0 :                 if let Some(FirstMessage(io_error)) = e.downcast_ref() {
     245              :                     // this is noisy. if we get EOF on the very first message that's likely
     246              :                     // just NLB doing a healthcheck.
     247            0 :                     if io_error.kind() == io::ErrorKind::UnexpectedEof {
     248            0 :                         return;
     249            0 :                     }
     250            0 :                 }
     251              : 
     252              :                 // Acknowledge that the task has finished with an error.
     253            0 :                 error!("per-client task finished with an error: {e:#}");
     254            0 :             })
     255            0 :             .instrument(tracing::info_span!("handle_client", ?session_id)),
     256              :         );
     257              :     }
     258              : 
     259            0 :     connections.close();
     260            0 :     drop(listener);
     261              : 
     262            0 :     connections.wait().await;
     263              : 
     264            0 :     info!("all client connections have finished");
     265            0 :     Ok(())
     266            0 : }
     267              : 
     268              : #[derive(Debug, thiserror::Error)]
     269              : #[error(transparent)]
     270              : struct FirstMessage(io::Error);
     271              : 
     272            0 : async fn ssl_handshake<S: AsyncRead + AsyncWrite + Unpin>(
     273            0 :     ctx: &RequestContext,
     274            0 :     raw_stream: S,
     275            0 :     tls_config: Arc<rustls::ServerConfig>,
     276            0 : ) -> anyhow::Result<TlsStream<S>> {
     277            0 :     let (mut stream, msg) = PqStream::parse_startup(Stream::from_raw(raw_stream))
     278            0 :         .await
     279            0 :         .map_err(FirstMessage)?;
     280              : 
     281            0 :     match msg {
     282              :         FeStartupPacket::SslRequest { direct: None } => {
     283            0 :             let raw = stream.accept_tls().await?;
     284              : 
     285            0 :             Ok(raw
     286            0 :                 .upgrade(tls_config, !ctx.has_private_peer_addr())
     287            0 :                 .await?)
     288              :         }
     289            0 :         unexpected => {
     290            0 :             info!(
     291              :                 ?unexpected,
     292            0 :                 "unexpected startup packet, rejecting connection"
     293              :             );
     294            0 :             Err(stream.throw_error(TlsRequired, None).await)?
     295              :         }
     296              :     }
     297            0 : }
     298              : 
     299            0 : async fn handle_client(
     300            0 :     ctx: RequestContext,
     301            0 :     dest_suffix: Arc<String>,
     302            0 :     tls_config: Arc<rustls::ServerConfig>,
     303            0 :     compute_tls_config: Option<Arc<rustls::ClientConfig>>,
     304            0 :     stream: impl AsyncRead + AsyncWrite + Unpin,
     305            0 : ) -> anyhow::Result<()> {
     306            0 :     let mut tls_stream = ssl_handshake(&ctx, stream, tls_config).await?;
     307              : 
     308              :     // Cut off first part of the SNI domain
     309              :     // We receive required destination details in the format of
     310              :     //   `{k8s_service_name}--{k8s_namespace}--{port}.non-sni-domain`
     311            0 :     let sni = tls_stream
     312            0 :         .get_ref()
     313            0 :         .1
     314            0 :         .server_name()
     315            0 :         .ok_or(anyhow!("SNI missing"))?;
     316            0 :     let dest: Vec<&str> = sni
     317            0 :         .split_once('.')
     318            0 :         .context("invalid SNI")?
     319              :         .0
     320            0 :         .splitn(3, "--")
     321            0 :         .collect();
     322            0 :     let port = dest[2].parse::<u16>().context("invalid port")?;
     323            0 :     let destination = format!("{}.{}.{}:{}", dest[0], dest[1], dest_suffix, port);
     324              : 
     325            0 :     info!("destination: {}", destination);
     326              : 
     327            0 :     let mut client = tokio::net::TcpStream::connect(&destination).await?;
     328              : 
     329            0 :     let client = if let Some(compute_tls_config) = compute_tls_config {
     330            0 :         info!("upgrading TLS");
     331              : 
     332              :         // send SslRequest
     333            0 :         client
     334            0 :             .write_all(b"\x00\x00\x00\x08\x04\xd2\x16\x2f")
     335            0 :             .await?;
     336              : 
     337              :         // wait for S/N respons
     338            0 :         let mut resp = b'N';
     339            0 :         client.read_exact(std::slice::from_mut(&mut resp)).await?;
     340              : 
     341              :         // error if not S
     342            0 :         ensure!(resp == b'S', "compute refused TLS");
     343              : 
     344              :         // upgrade to TLS.
     345            0 :         let domain = DnsName::try_from(destination)?;
     346            0 :         let domain = rustls::pki_types::ServerName::DnsName(domain);
     347            0 :         let client = TlsConnector::from(compute_tls_config)
     348            0 :             .connect(domain, client)
     349            0 :             .await?;
     350            0 :         Connection::Tls(client)
     351              :     } else {
     352            0 :         Connection::Raw(client)
     353              :     };
     354              : 
     355              :     // doesn't yet matter as pg-sni-router doesn't report analytics logs
     356            0 :     ctx.set_success();
     357            0 :     ctx.log_connect();
     358              : 
     359              :     // Starting from here we only proxy the client's traffic.
     360            0 :     info!("performing the proxy pass...");
     361              : 
     362            0 :     let res = match client {
     363            0 :         Connection::Raw(mut c) => copy_bidirectional_client_compute(&mut tls_stream, &mut c).await,
     364            0 :         Connection::Tls(mut c) => copy_bidirectional_client_compute(&mut tls_stream, &mut c).await,
     365              :     };
     366              : 
     367            0 :     match res {
     368            0 :         Ok(_) => Ok(()),
     369            0 :         Err(ErrorSource::Client(err)) => Err(err).context("client"),
     370            0 :         Err(ErrorSource::Compute(err)) => Err(err).context("compute"),
     371              :     }
     372            0 : }
     373              : 
     374              : #[allow(clippy::large_enum_variant)]
     375              : enum Connection {
     376              :     Raw(tokio::net::TcpStream),
     377              :     Tls(tokio_rustls::client::TlsStream<tokio::net::TcpStream>),
     378              : }
        

Generated by: LCOV version 2.1-beta