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

Generated by: LCOV version 2.1-beta