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 : use std::{net::SocketAddr, sync::Arc};
7 :
8 : use futures::future::Either;
9 : use itertools::Itertools;
10 : use proxy::config::TlsServerEndPoint;
11 : use proxy::context::RequestMonitoring;
12 : use proxy::proxy::run_until_cancelled;
13 : use proxy::{BranchId, EndpointId, ProjectId};
14 : use rustls::pki_types::PrivateKeyDer;
15 : use tokio::net::TcpListener;
16 :
17 : use anyhow::{anyhow, bail, ensure, Context};
18 : use clap::Arg;
19 : use futures::TryFutureExt;
20 : use proxy::console::messages::MetricsAuxInfo;
21 : use proxy::stream::{PqStream, Stream};
22 :
23 : use tokio::io::{AsyncRead, AsyncWrite};
24 : use tokio_util::sync::CancellationToken;
25 : use utils::{project_git_version, sentry_init::init_sentry};
26 :
27 : use tracing::{error, info, Instrument};
28 :
29 : project_git_version!(GIT_VERSION);
30 :
31 0 : fn cli() -> clap::Command {
32 0 : clap::Command::new("Neon proxy/router")
33 0 : .version(GIT_VERSION)
34 0 : .arg(
35 0 : Arg::new("listen")
36 0 : .short('l')
37 0 : .long("listen")
38 0 : .help("listen for incoming client connections on ip:port")
39 0 : .default_value("127.0.0.1:4432"),
40 0 : )
41 0 : .arg(
42 0 : Arg::new("tls-key")
43 0 : .short('k')
44 0 : .long("tls-key")
45 0 : .help("path to TLS key for client postgres connections")
46 0 : .required(true),
47 0 : )
48 0 : .arg(
49 0 : Arg::new("tls-cert")
50 0 : .short('c')
51 0 : .long("tls-cert")
52 0 : .help("path to TLS cert for client postgres connections")
53 0 : .required(true),
54 0 : )
55 0 : .arg(
56 0 : Arg::new("dest")
57 0 : .short('d')
58 0 : .long("destination")
59 0 : .help("append this domain zone to the SNI hostname to get the destination address")
60 0 : .required(true),
61 0 : )
62 0 : }
63 :
64 : #[tokio::main]
65 0 : async fn main() -> anyhow::Result<()> {
66 0 : let _logging_guard = proxy::logging::init().await?;
67 0 : let _panic_hook_guard = utils::logging::replace_panic_hook_with_tracing_panic_hook();
68 0 : let _sentry_guard = init_sentry(Some(GIT_VERSION.into()), &[]);
69 0 :
70 0 : let args = cli().get_matches();
71 0 : let destination: String = args.get_one::<String>("dest").unwrap().parse()?;
72 0 :
73 0 : // Configure TLS
74 0 : let (tls_config, tls_server_end_point): (Arc<rustls::ServerConfig>, TlsServerEndPoint) = match (
75 0 : args.get_one::<String>("tls-key"),
76 0 : args.get_one::<String>("tls-cert"),
77 0 : ) {
78 0 : (Some(key_path), Some(cert_path)) => {
79 0 : let key = {
80 0 : let key_bytes = std::fs::read(key_path).context("TLS key file")?;
81 0 :
82 0 : let mut keys =
83 0 : rustls_pemfile::pkcs8_private_keys(&mut &key_bytes[..]).collect_vec();
84 0 :
85 0 : ensure!(keys.len() == 1, "keys.len() = {} (should be 1)", keys.len());
86 0 : PrivateKeyDer::Pkcs8(
87 0 : keys.pop()
88 0 : .unwrap()
89 0 : .context(format!("Failed to read TLS keys at '{key_path}'"))?,
90 0 : )
91 0 : };
92 0 :
93 0 : let cert_chain_bytes = std::fs::read(cert_path)
94 0 : .context(format!("Failed to read TLS cert file at '{cert_path}.'"))?;
95 0 :
96 0 : let cert_chain: Vec<_> = {
97 0 : rustls_pemfile::certs(&mut &cert_chain_bytes[..])
98 0 : .try_collect()
99 0 : .with_context(|| {
100 0 : format!("Failed to read TLS certificate chain from bytes from file at '{cert_path}'.")
101 0 : })?
102 0 : };
103 0 :
104 0 : // needed for channel bindings
105 0 : let first_cert = cert_chain.first().context("missing certificate")?;
106 0 : let tls_server_end_point = TlsServerEndPoint::new(first_cert)?;
107 0 :
108 0 : let tls_config = rustls::ServerConfig::builder_with_protocol_versions(&[
109 0 : &rustls::version::TLS13,
110 0 : &rustls::version::TLS12,
111 0 : ])
112 0 : .with_no_client_auth()
113 0 : .with_single_cert(cert_chain, key)?
114 0 : .into();
115 0 :
116 0 : (tls_config, tls_server_end_point)
117 0 : }
118 0 : _ => bail!("tls-key and tls-cert must be specified"),
119 0 : };
120 0 :
121 0 : // Start listening for incoming client connections
122 0 : let proxy_address: SocketAddr = args.get_one::<String>("listen").unwrap().parse()?;
123 0 : info!("Starting sni router on {proxy_address}");
124 0 : let proxy_listener = TcpListener::bind(proxy_address).await?;
125 0 :
126 0 : let cancellation_token = CancellationToken::new();
127 0 :
128 0 : let main = tokio::spawn(task_main(
129 0 : Arc::new(destination),
130 0 : tls_config,
131 0 : tls_server_end_point,
132 0 : proxy_listener,
133 0 : cancellation_token.clone(),
134 0 : ));
135 0 : let signals_task = tokio::spawn(proxy::handle_signals(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 signal = match futures::future::select(signals_task, main).await {
141 0 : Either::Left((res, _)) => proxy::flatten_err(res)?,
142 0 : Either::Right((res, _)) => return proxy::flatten_err(res),
143 0 : };
144 0 :
145 0 : // maintenance tasks return `Infallible` success values, this is an impossible value
146 0 : // so this match statically ensures that there are no possibilities for that value
147 0 : match signal {}
148 0 : }
149 :
150 0 : async fn task_main(
151 0 : dest_suffix: Arc<String>,
152 0 : tls_config: Arc<rustls::ServerConfig>,
153 0 : tls_server_end_point: TlsServerEndPoint,
154 0 : listener: tokio::net::TcpListener,
155 0 : cancellation_token: CancellationToken,
156 0 : ) -> anyhow::Result<()> {
157 0 : // When set for the server socket, the keepalive setting
158 0 : // will be inherited by all accepted client sockets.
159 0 : socket2::SockRef::from(&listener).set_keepalive(true)?;
160 :
161 0 : let connections = tokio_util::task::task_tracker::TaskTracker::new();
162 :
163 0 : while let Some(accept_result) =
164 0 : run_until_cancelled(listener.accept(), &cancellation_token).await
165 : {
166 0 : let (socket, peer_addr) = accept_result?;
167 :
168 0 : let session_id = uuid::Uuid::new_v4();
169 0 : let tls_config = Arc::clone(&tls_config);
170 0 : let dest_suffix = Arc::clone(&dest_suffix);
171 0 :
172 0 : connections.spawn(
173 0 : async move {
174 0 : socket
175 0 : .set_nodelay(true)
176 0 : .context("failed to set socket option")?;
177 :
178 0 : info!(%peer_addr, "serving");
179 0 : let ctx = RequestMonitoring::new(session_id, peer_addr.ip(), "sni_router", "sni");
180 0 : handle_client(ctx, dest_suffix, tls_config, tls_server_end_point, socket).await
181 0 : }
182 0 : .unwrap_or_else(|e| {
183 0 : // Acknowledge that the task has finished with an error.
184 0 : error!("per-client task finished with an error: {e:#}");
185 0 : })
186 0 : .instrument(tracing::info_span!("handle_client", ?session_id)),
187 : );
188 : }
189 :
190 0 : connections.close();
191 0 : drop(listener);
192 0 :
193 0 : connections.wait().await;
194 :
195 0 : info!("all client connections have finished");
196 0 : Ok(())
197 0 : }
198 :
199 : const ERR_INSECURE_CONNECTION: &str = "connection is insecure (try using `sslmode=require`)";
200 :
201 0 : async fn ssl_handshake<S: AsyncRead + AsyncWrite + Unpin>(
202 0 : raw_stream: S,
203 0 : tls_config: Arc<rustls::ServerConfig>,
204 0 : tls_server_end_point: TlsServerEndPoint,
205 0 : ) -> anyhow::Result<Stream<S>> {
206 0 : let mut stream = PqStream::new(Stream::from_raw(raw_stream));
207 :
208 0 : let msg = stream.read_startup_packet().await?;
209 : use pq_proto::FeStartupPacket::*;
210 :
211 0 : match msg {
212 : SslRequest => {
213 0 : stream
214 0 : .write_message(&pq_proto::BeMessage::EncryptionResponse(true))
215 0 : .await?;
216 : // Upgrade raw stream into a secure TLS-backed stream.
217 : // NOTE: We've consumed `tls`; this fact will be used later.
218 :
219 0 : let (raw, read_buf) = stream.into_inner();
220 0 : // TODO: Normally, client doesn't send any data before
221 0 : // server says TLS handshake is ok and read_buf is empy.
222 0 : // However, you could imagine pipelining of postgres
223 0 : // SSLRequest + TLS ClientHello in one hunk similar to
224 0 : // pipelining in our node js driver. We should probably
225 0 : // support that by chaining read_buf with the stream.
226 0 : if !read_buf.is_empty() {
227 0 : bail!("data is sent before server replied with EncryptionResponse");
228 0 : }
229 0 :
230 0 : Ok(Stream::Tls {
231 0 : tls: Box::new(raw.upgrade(tls_config).await?),
232 0 : tls_server_end_point,
233 : })
234 : }
235 0 : unexpected => {
236 0 : info!(
237 0 : ?unexpected,
238 0 : "unexpected startup packet, rejecting connection"
239 0 : );
240 0 : stream
241 0 : .throw_error_str(ERR_INSECURE_CONNECTION, proxy::error::ErrorKind::User)
242 0 : .await?
243 : }
244 : }
245 0 : }
246 :
247 0 : async fn handle_client(
248 0 : mut ctx: RequestMonitoring,
249 0 : dest_suffix: Arc<String>,
250 0 : tls_config: Arc<rustls::ServerConfig>,
251 0 : tls_server_end_point: TlsServerEndPoint,
252 0 : stream: impl AsyncRead + AsyncWrite + Unpin,
253 0 : ) -> anyhow::Result<()> {
254 0 : let tls_stream = ssl_handshake(stream, tls_config, tls_server_end_point).await?;
255 :
256 : // Cut off first part of the SNI domain
257 : // We receive required destination details in the format of
258 : // `{k8s_service_name}--{k8s_namespace}--{port}.non-sni-domain`
259 0 : let sni = tls_stream.sni_hostname().ok_or(anyhow!("SNI missing"))?;
260 0 : let dest: Vec<&str> = sni
261 0 : .split_once('.')
262 0 : .context("invalid SNI")?
263 : .0
264 0 : .splitn(3, "--")
265 0 : .collect();
266 0 : let port = dest[2].parse::<u16>().context("invalid port")?;
267 0 : let destination = format!("{}.{}.{}:{}", dest[0], dest[1], dest_suffix, port);
268 0 :
269 0 : info!("destination: {}", destination);
270 :
271 0 : let client = tokio::net::TcpStream::connect(destination).await?;
272 :
273 0 : let metrics_aux: MetricsAuxInfo = MetricsAuxInfo {
274 0 : endpoint_id: (&EndpointId::from("")).into(),
275 0 : project_id: (&ProjectId::from("")).into(),
276 0 : branch_id: (&BranchId::from("")).into(),
277 0 : cold_start_info: proxy::console::messages::ColdStartInfo::Unknown,
278 0 : };
279 0 :
280 0 : // doesn't yet matter as pg-sni-router doesn't report analytics logs
281 0 : ctx.set_success();
282 0 : ctx.log();
283 0 :
284 0 : proxy::proxy::passthrough::proxy_pass(tls_stream, client, metrics_aux).await
285 0 : }
|