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::read_proxy_protocol,
21 : proxy::handshake::{handshake, HandshakeData},
22 : rate_limiter::EndpointRateLimiter,
23 : stream::{PqStream, Stream},
24 : EndpointCacheKey,
25 : };
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, 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 : cancellation_handler: Arc<CancellationHandlerMain>,
65 0 : endpoint_rate_limiter: Arc<EndpointRateLimiter>,
66 0 : ) -> anyhow::Result<()> {
67 : scopeguard::defer! {
68 : 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 conn_gauge = Metrics::get()
83 0 : .proxy
84 0 : .client_connections
85 0 : .guard(crate::metrics::Protocol::Tcp);
86 0 :
87 0 : let session_id = uuid::Uuid::new_v4();
88 0 : let cancellation_handler = Arc::clone(&cancellation_handler);
89 0 :
90 0 : tracing::info!(protocol = "tcp", %session_id, "accepted new TCP connection");
91 0 : let endpoint_rate_limiter2 = endpoint_rate_limiter.clone();
92 0 :
93 0 : connections.spawn(async move {
94 0 : let (socket, peer_addr) = match read_proxy_protocol(socket).await{
95 0 : Ok((socket, Some(addr))) => (socket, addr.ip()),
96 0 : Err(e) => {
97 0 : error!("per-client task finished with an error: {e:#}");
98 0 : return;
99 : }
100 0 : Ok((_socket, None)) if config.require_client_ip => {
101 0 : error!("missing required client IP");
102 0 : return;
103 : }
104 0 : Ok((socket, None)) => (socket, peer_addr.ip())
105 : };
106 :
107 0 : match socket.inner.set_nodelay(true) {
108 0 : Ok(()) => {},
109 0 : Err(e) => {
110 0 : error!("per-client task finished with an error: failed to set socket option: {e:#}");
111 0 : return;
112 : },
113 : };
114 :
115 0 : let mut ctx = RequestMonitoring::new(
116 0 : session_id,
117 0 : peer_addr,
118 0 : crate::metrics::Protocol::Tcp,
119 0 : &config.region,
120 0 : );
121 0 : let span = ctx.span.clone();
122 :
123 0 : let res = handle_client(
124 0 : config,
125 0 : &mut ctx,
126 0 : cancellation_handler,
127 0 : socket,
128 0 : ClientMode::Tcp,
129 0 : endpoint_rate_limiter2,
130 0 : conn_gauge,
131 0 : )
132 0 : .instrument(span.clone())
133 0 : .await;
134 :
135 0 : match res {
136 0 : Err(e) => {
137 0 : // todo: log and push to ctx the error kind
138 0 : ctx.set_error_kind(e.get_error_kind());
139 : error!(parent: &span, "per-client task finished with an error: {e:#}");
140 : }
141 0 : Ok(None) => {
142 0 : ctx.set_success();
143 0 : }
144 0 : Ok(Some(p)) => {
145 0 : ctx.set_success();
146 0 : ctx.log_connect();
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 : endpoint_rate_limiter: Arc<EndpointRateLimiter>,
242 0 : conn_gauge: NumClientConnectionsGuard<'static>,
243 0 : ) -> Result<Option<ProxyPassthrough<CancellationHandlerMainInternal, S>>, ClientRequestError> {
244 0 : info!(
245 : protocol = %ctx.protocol,
246 0 : "handling interactive connection from client"
247 : );
248 :
249 0 : let metrics = &Metrics::get().proxy;
250 0 : let proto = ctx.protocol;
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, ¶ms, 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 : endpoint_rate_limiter,
294 0 : )
295 0 : .await
296 : {
297 0 : Ok(auth_result) => auth_result,
298 0 : Err(e) => {
299 0 : let db = params.get("database");
300 0 : let app = params.get("application_name");
301 0 : let params_span = tracing::info_span!("", ?user, ?db, ?app);
302 :
303 0 : return stream.throw_error(e).instrument(params_span).await?;
304 : }
305 : };
306 :
307 0 : let mut node = connect_to_compute(
308 0 : ctx,
309 0 : &TcpMechanism {
310 0 : params: ¶ms,
311 0 : locks: &config.connect_compute_locks,
312 0 : },
313 0 : &user_info,
314 0 : mode.allow_self_signed_compute(config),
315 0 : config.wake_compute_retry_config,
316 0 : config.connect_to_compute_retry_config,
317 0 : )
318 0 : .or_else(|e| stream.throw_error(e))
319 0 : .await?;
320 :
321 0 : let session = cancellation_handler.get_session();
322 0 : prepare_client_connection(&node, &session, &mut stream).await?;
323 :
324 : // Before proxy passing, forward to compute whatever data is left in the
325 : // PqStream input buffer. Normally there is none, but our serverless npm
326 : // driver in pipeline mode sends startup, password and first query
327 : // immediately after opening the connection.
328 0 : let (stream, read_buf) = stream.into_inner();
329 0 : node.stream.write_all(&read_buf).await?;
330 :
331 0 : Ok(Some(ProxyPassthrough {
332 0 : client: stream,
333 0 : aux: node.aux.clone(),
334 0 : compute: node,
335 0 : req: _request_gauge,
336 0 : conn: conn_gauge,
337 0 : cancel: session,
338 0 : }))
339 0 : }
340 :
341 : /// Finish client connection initialization: confirm auth success, send params, etc.
342 0 : #[tracing::instrument(skip_all)]
343 : async fn prepare_client_connection<P>(
344 : node: &compute::PostgresConnection,
345 : session: &cancellation::Session<P>,
346 : stream: &mut PqStream<impl AsyncRead + AsyncWrite + Unpin>,
347 : ) -> Result<(), std::io::Error> {
348 : // Register compute's query cancellation token and produce a new, unique one.
349 : // The new token (cancel_key_data) will be sent to the client.
350 : let cancel_key_data = session.enable_query_cancellation(node.cancel_closure.clone());
351 :
352 : // Forward all postgres connection params to the client.
353 : // Right now the implementation is very hacky and inefficent (ideally,
354 : // we don't need an intermediate hashmap), but at least it should be correct.
355 : for (name, value) in &node.params {
356 : // TODO: Theoretically, this could result in a big pile of params...
357 : stream.write_message_noflush(&Be::ParameterStatus {
358 : name: name.as_bytes(),
359 : value: value.as_bytes(),
360 : })?;
361 : }
362 :
363 : stream
364 : .write_message_noflush(&Be::BackendKeyData(cancel_key_data))?
365 : .write_message(&Be::ReadyForQuery)
366 : .await?;
367 :
368 : Ok(())
369 : }
370 :
371 : #[derive(Debug, Clone, PartialEq, Eq, Default)]
372 : pub struct NeonOptions(Vec<(SmolStr, SmolStr)>);
373 :
374 : impl NeonOptions {
375 22 : pub fn parse_params(params: &StartupMessageParams) -> Self {
376 22 : params
377 22 : .options_raw()
378 22 : .map(Self::parse_from_iter)
379 22 : .unwrap_or_default()
380 22 : }
381 14 : pub fn parse_options_raw(options: &str) -> Self {
382 14 : Self::parse_from_iter(StartupMessageParams::parse_options_raw(options))
383 14 : }
384 :
385 4 : pub fn is_ephemeral(&self) -> bool {
386 4 : // Currently, neon endpoint options are all reserved for ephemeral endpoints.
387 4 : !self.0.is_empty()
388 4 : }
389 :
390 26 : fn parse_from_iter<'a>(options: impl Iterator<Item = &'a str>) -> Self {
391 26 : let mut options = options
392 26 : .filter_map(neon_option)
393 26 : .map(|(k, v)| (k.into(), v.into()))
394 26 : .collect_vec();
395 26 : options.sort();
396 26 : Self(options)
397 26 : }
398 :
399 8 : pub fn get_cache_key(&self, prefix: &str) -> EndpointCacheKey {
400 8 : // prefix + format!(" {k}:{v}")
401 8 : // kinda jank because SmolStr is immutable
402 8 : std::iter::once(prefix)
403 8 : .chain(self.0.iter().flat_map(|(k, v)| [" ", &**k, ":", &**v]))
404 8 : .collect::<SmolStr>()
405 8 : .into()
406 8 : }
407 :
408 : /// <https://swagger.io/docs/specification/serialization/> DeepObject format
409 : /// `paramName[prop1]=value1¶mName[prop2]=value2&...`
410 0 : pub fn to_deep_object(&self) -> Vec<(SmolStr, SmolStr)> {
411 0 : self.0
412 0 : .iter()
413 0 : .map(|(k, v)| (format_smolstr!("options[{}]", k), v.clone()))
414 0 : .collect()
415 0 : }
416 : }
417 :
418 64 : pub fn neon_option(bytes: &str) -> Option<(&str, &str)> {
419 64 : static RE: OnceCell<Regex> = OnceCell::new();
420 64 : let re = RE.get_or_init(|| Regex::new(r"^neon_(\w+):(.+)").unwrap());
421 :
422 64 : let cap = re.captures(bytes)?;
423 8 : let (_, [k, v]) = cap.extract();
424 8 : Some((k, v))
425 64 : }
|