Line data Source code
1 : use std::{sync::Arc, time::Duration};
2 :
3 : use async_trait::async_trait;
4 : use tracing::{field::display, info};
5 :
6 : use crate::{
7 : auth::{backend::ComputeCredentials, check_peer_addr_is_in_list, AuthError},
8 : compute,
9 : config::ProxyConfig,
10 : console::{
11 : errors::{GetAuthInfoError, WakeComputeError},
12 : CachedNodeInfo,
13 : },
14 : context::RequestMonitoring,
15 : error::{ErrorKind, ReportableError, UserFacingError},
16 : proxy::connect_compute::ConnectMechanism,
17 : };
18 :
19 : use super::conn_pool::{poll_client, Client, ConnInfo, GlobalConnPool};
20 :
21 : pub struct PoolingBackend {
22 : pub pool: Arc<GlobalConnPool<tokio_postgres::Client>>,
23 : pub config: &'static ProxyConfig,
24 : }
25 :
26 : impl PoolingBackend {
27 0 : pub async fn authenticate(
28 0 : &self,
29 0 : ctx: &mut RequestMonitoring,
30 0 : conn_info: &ConnInfo,
31 0 : ) -> Result<ComputeCredentials, AuthError> {
32 0 : let user_info = conn_info.user_info.clone();
33 0 : let backend = self.config.auth_backend.as_ref().map(|_| user_info.clone());
34 0 : let (allowed_ips, maybe_secret) = backend.get_allowed_ips_and_secret(ctx).await?;
35 0 : if !check_peer_addr_is_in_list(&ctx.peer_addr, &allowed_ips) {
36 0 : return Err(AuthError::ip_address_not_allowed(ctx.peer_addr));
37 0 : }
38 0 : let cached_secret = match maybe_secret {
39 0 : Some(secret) => secret,
40 0 : None => backend.get_role_secret(ctx).await?,
41 : };
42 :
43 0 : let secret = match cached_secret.value.clone() {
44 0 : Some(secret) => self.config.authentication_config.check_rate_limit(
45 0 : ctx,
46 0 : secret,
47 0 : &user_info.endpoint,
48 0 : true,
49 0 : )?,
50 : None => {
51 : // If we don't have an authentication secret, for the http flow we can just return an error.
52 0 : info!("authentication info not found");
53 0 : return Err(AuthError::auth_failed(&*user_info.user));
54 : }
55 : };
56 0 : let auth_outcome =
57 0 : crate::auth::validate_password_and_exchange(&conn_info.password, secret).await?;
58 0 : let res = match auth_outcome {
59 0 : crate::sasl::Outcome::Success(key) => {
60 0 : info!("user successfully authenticated");
61 0 : Ok(key)
62 : }
63 0 : crate::sasl::Outcome::Failure(reason) => {
64 0 : info!("auth backend failed with an error: {reason}");
65 0 : Err(AuthError::auth_failed(&*conn_info.user_info.user))
66 : }
67 : };
68 0 : res.map(|key| ComputeCredentials {
69 0 : info: user_info,
70 0 : keys: key,
71 0 : })
72 0 : }
73 :
74 : // Wake up the destination if needed. Code here is a bit involved because
75 : // we reuse the code from the usual proxy and we need to prepare few structures
76 : // that this code expects.
77 0 : #[tracing::instrument(fields(pid = tracing::field::Empty), skip_all)]
78 : pub async fn connect_to_compute(
79 : &self,
80 : ctx: &mut RequestMonitoring,
81 : conn_info: ConnInfo,
82 : keys: ComputeCredentials,
83 : force_new: bool,
84 : ) -> Result<Client<tokio_postgres::Client>, HttpConnError> {
85 : let maybe_client = if !force_new {
86 0 : info!("pool: looking for an existing connection");
87 : self.pool.get(ctx, &conn_info).await?
88 : } else {
89 0 : info!("pool: pool is disabled");
90 : None
91 : };
92 :
93 : if let Some(client) = maybe_client {
94 : return Ok(client);
95 : }
96 : let conn_id = uuid::Uuid::new_v4();
97 : tracing::Span::current().record("conn_id", display(conn_id));
98 0 : info!(%conn_id, "pool: opening a new connection '{conn_info}'");
99 0 : let backend = self.config.auth_backend.as_ref().map(|_| keys);
100 : crate::proxy::connect_compute::connect_to_compute(
101 : ctx,
102 : &TokioMechanism {
103 : conn_id,
104 : conn_info,
105 : pool: self.pool.clone(),
106 : },
107 : &backend,
108 : false, // do not allow self signed compute for http flow
109 : )
110 : .await
111 : }
112 : }
113 :
114 0 : #[derive(Debug, thiserror::Error)]
115 : pub enum HttpConnError {
116 : #[error("pooled connection closed at inconsistent state")]
117 : ConnectionClosedAbruptly(#[from] tokio::sync::watch::error::SendError<uuid::Uuid>),
118 : #[error("could not connection to compute")]
119 : ConnectionError(#[from] tokio_postgres::Error),
120 :
121 : #[error("could not get auth info")]
122 : GetAuthInfo(#[from] GetAuthInfoError),
123 : #[error("user not authenticated")]
124 : AuthError(#[from] AuthError),
125 : #[error("wake_compute returned error")]
126 : WakeCompute(#[from] WakeComputeError),
127 : }
128 :
129 : impl ReportableError for HttpConnError {
130 0 : fn get_error_kind(&self) -> ErrorKind {
131 0 : match self {
132 0 : HttpConnError::ConnectionClosedAbruptly(_) => ErrorKind::Compute,
133 0 : HttpConnError::ConnectionError(p) => p.get_error_kind(),
134 0 : HttpConnError::GetAuthInfo(a) => a.get_error_kind(),
135 0 : HttpConnError::AuthError(a) => a.get_error_kind(),
136 0 : HttpConnError::WakeCompute(w) => w.get_error_kind(),
137 : }
138 0 : }
139 : }
140 :
141 : impl UserFacingError for HttpConnError {
142 0 : fn to_string_client(&self) -> String {
143 0 : match self {
144 0 : HttpConnError::ConnectionClosedAbruptly(_) => self.to_string(),
145 0 : HttpConnError::ConnectionError(p) => p.to_string(),
146 0 : HttpConnError::GetAuthInfo(c) => c.to_string_client(),
147 0 : HttpConnError::AuthError(c) => c.to_string_client(),
148 0 : HttpConnError::WakeCompute(c) => c.to_string_client(),
149 : }
150 0 : }
151 : }
152 :
153 : struct TokioMechanism {
154 : pool: Arc<GlobalConnPool<tokio_postgres::Client>>,
155 : conn_info: ConnInfo,
156 : conn_id: uuid::Uuid,
157 : }
158 :
159 : #[async_trait]
160 : impl ConnectMechanism for TokioMechanism {
161 : type Connection = Client<tokio_postgres::Client>;
162 : type ConnectError = tokio_postgres::Error;
163 : type Error = HttpConnError;
164 :
165 0 : async fn connect_once(
166 0 : &self,
167 0 : ctx: &mut RequestMonitoring,
168 0 : node_info: &CachedNodeInfo,
169 0 : timeout: Duration,
170 0 : ) -> Result<Self::Connection, Self::ConnectError> {
171 0 : let mut config = (*node_info.config).clone();
172 0 : let config = config
173 0 : .user(&self.conn_info.user_info.user)
174 0 : .password(&*self.conn_info.password)
175 0 : .dbname(&self.conn_info.dbname)
176 0 : .connect_timeout(timeout);
177 :
178 0 : let (client, connection) = config.connect(tokio_postgres::NoTls).await?;
179 :
180 0 : tracing::Span::current().record("pid", &tracing::field::display(client.get_process_id()));
181 0 : Ok(poll_client(
182 0 : self.pool.clone(),
183 0 : ctx,
184 0 : self.conn_info.clone(),
185 0 : client,
186 0 : connection,
187 0 : self.conn_id,
188 0 : node_info.aux.clone(),
189 0 : ))
190 0 : }
191 :
192 0 : fn update_connect_config(&self, _config: &mut compute::ConnCfg) {}
193 : }
|