Line data Source code
1 : //! Manages the pool of connections between local_proxy and postgres.
2 : //!
3 : //! The pool is keyed by database and role_name, and can contain multiple connections
4 : //! shared between users.
5 : //!
6 : //! The pool manages the pg_session_jwt extension used for authorizing
7 : //! requests in the db.
8 : //!
9 : //! The first time a db/role pair is seen, local_proxy attempts to install the extension
10 : //! and grant usage to the role on the given schema.
11 :
12 : use std::collections::HashMap;
13 : use std::pin::pin;
14 : use std::sync::atomic::AtomicUsize;
15 : use std::sync::Arc;
16 : use std::task::{ready, Poll};
17 : use std::time::Duration;
18 :
19 : use ed25519_dalek::{Signature, Signer, SigningKey};
20 : use futures::future::poll_fn;
21 : use futures::Future;
22 : use indexmap::IndexMap;
23 : use jose_jwk::jose_b64::base64ct::{Base64UrlUnpadded, Encoding};
24 : use parking_lot::RwLock;
25 : use postgres_client::tls::NoTlsStream;
26 : use postgres_client::AsyncMessage;
27 : use serde_json::value::RawValue;
28 : use tokio::net::TcpStream;
29 : use tokio::time::Instant;
30 : use tokio_util::sync::CancellationToken;
31 : use tracing::{debug, error, info, info_span, warn, Instrument};
32 :
33 : use super::backend::HttpConnError;
34 : use super::conn_pool_lib::{
35 : Client, ClientDataEnum, ClientInnerCommon, ClientInnerExt, ConnInfo, DbUserConn,
36 : EndpointConnPool,
37 : };
38 : use crate::context::RequestContext;
39 : use crate::control_plane::messages::{ColdStartInfo, MetricsAuxInfo};
40 : use crate::metrics::Metrics;
41 :
42 : pub(crate) const EXT_NAME: &str = "pg_session_jwt";
43 : pub(crate) const EXT_VERSION: &str = "0.2.0";
44 : pub(crate) const EXT_SCHEMA: &str = "auth";
45 :
46 : #[derive(Clone)]
47 : pub(crate) struct ClientDataLocal {
48 : session: tokio::sync::watch::Sender<uuid::Uuid>,
49 : cancel: CancellationToken,
50 : key: SigningKey,
51 : jti: u64,
52 : }
53 :
54 : impl ClientDataLocal {
55 0 : pub fn session(&mut self) -> &mut tokio::sync::watch::Sender<uuid::Uuid> {
56 0 : &mut self.session
57 0 : }
58 :
59 0 : pub fn cancel(&mut self) {
60 0 : self.cancel.cancel();
61 0 : }
62 : }
63 :
64 : pub(crate) struct LocalConnPool<C: ClientInnerExt> {
65 : global_pool: Arc<RwLock<EndpointConnPool<C>>>,
66 :
67 : config: &'static crate::config::HttpConfig,
68 : }
69 :
70 : impl<C: ClientInnerExt> LocalConnPool<C> {
71 0 : pub(crate) fn new(config: &'static crate::config::HttpConfig) -> Arc<Self> {
72 0 : Arc::new(Self {
73 0 : global_pool: Arc::new(RwLock::new(EndpointConnPool::new(
74 0 : HashMap::new(),
75 0 : 0,
76 0 : config.pool_options.max_conns_per_endpoint,
77 0 : Arc::new(AtomicUsize::new(0)),
78 0 : config.pool_options.max_total_conns,
79 0 : String::from("local_pool"),
80 0 : ))),
81 0 : config,
82 0 : })
83 0 : }
84 :
85 0 : pub(crate) fn get_idle_timeout(&self) -> Duration {
86 0 : self.config.pool_options.idle_timeout
87 0 : }
88 :
89 0 : pub(crate) fn get(
90 0 : self: &Arc<Self>,
91 0 : ctx: &RequestContext,
92 0 : conn_info: &ConnInfo,
93 0 : ) -> Result<Option<Client<C>>, HttpConnError> {
94 0 : let client = self
95 0 : .global_pool
96 0 : .write()
97 0 : .get_conn_entry(conn_info.db_and_user())
98 0 : .map(|entry| entry.conn);
99 :
100 : // ok return cached connection if found and establish a new one otherwise
101 0 : if let Some(mut client) = client {
102 0 : if client.inner.is_closed() {
103 0 : info!("local_pool: cached connection '{conn_info}' is closed, opening a new one");
104 0 : return Ok(None);
105 0 : }
106 0 :
107 0 : tracing::Span::current()
108 0 : .record("conn_id", tracing::field::display(client.get_conn_id()));
109 0 : tracing::Span::current().record(
110 0 : "pid",
111 0 : tracing::field::display(client.inner.get_process_id()),
112 0 : );
113 0 : debug!(
114 0 : cold_start_info = ColdStartInfo::HttpPoolHit.as_str(),
115 0 : "local_pool: reusing connection '{conn_info}'"
116 : );
117 :
118 0 : match client.get_data() {
119 0 : ClientDataEnum::Local(data) => {
120 0 : data.session().send(ctx.session_id())?;
121 : }
122 :
123 0 : ClientDataEnum::Remote(data) => {
124 0 : data.session().send(ctx.session_id())?;
125 : }
126 0 : ClientDataEnum::Http(_) => (),
127 : }
128 :
129 0 : ctx.set_cold_start_info(ColdStartInfo::HttpPoolHit);
130 0 : ctx.success();
131 0 :
132 0 : return Ok(Some(Client::new(
133 0 : client,
134 0 : conn_info.clone(),
135 0 : Arc::downgrade(&self.global_pool),
136 0 : )));
137 0 : }
138 0 : Ok(None)
139 0 : }
140 :
141 0 : pub(crate) fn initialized(self: &Arc<Self>, conn_info: &ConnInfo) -> bool {
142 0 : if let Some(pool) = self.global_pool.read().get_pool(conn_info.db_and_user()) {
143 0 : return pool.is_initialized();
144 0 : }
145 0 : false
146 0 : }
147 :
148 0 : pub(crate) fn set_initialized(self: &Arc<Self>, conn_info: &ConnInfo) {
149 0 : if let Some(pool) = self
150 0 : .global_pool
151 0 : .write()
152 0 : .get_pool_mut(conn_info.db_and_user())
153 0 : {
154 0 : pool.set_initialized();
155 0 : }
156 0 : }
157 : }
158 :
159 : #[allow(clippy::too_many_arguments)]
160 0 : pub(crate) fn poll_client<C: ClientInnerExt>(
161 0 : global_pool: Arc<LocalConnPool<C>>,
162 0 : ctx: &RequestContext,
163 0 : conn_info: ConnInfo,
164 0 : client: C,
165 0 : mut connection: postgres_client::Connection<TcpStream, NoTlsStream>,
166 0 : key: SigningKey,
167 0 : conn_id: uuid::Uuid,
168 0 : aux: MetricsAuxInfo,
169 0 : ) -> Client<C> {
170 0 : let conn_gauge = Metrics::get().proxy.db_connections.guard(ctx.protocol());
171 0 : let mut session_id = ctx.session_id();
172 0 : let (tx, mut rx) = tokio::sync::watch::channel(session_id);
173 :
174 0 : let span = info_span!(parent: None, "connection", %conn_id);
175 0 : let cold_start_info = ctx.cold_start_info();
176 0 : span.in_scope(|| {
177 0 : info!(cold_start_info = cold_start_info.as_str(), %conn_info, %session_id, "new connection");
178 0 : });
179 0 : let pool = Arc::downgrade(&global_pool);
180 0 :
181 0 : let db_user = conn_info.db_and_user();
182 0 : let idle = global_pool.get_idle_timeout();
183 0 : let cancel = CancellationToken::new();
184 0 : let cancelled = cancel.clone().cancelled_owned();
185 0 :
186 0 : tokio::spawn(
187 0 : async move {
188 0 : let _conn_gauge = conn_gauge;
189 0 : let mut idle_timeout = pin!(tokio::time::sleep(idle));
190 0 : let mut cancelled = pin!(cancelled);
191 0 :
192 0 : poll_fn(move |cx| {
193 0 : if cancelled.as_mut().poll(cx).is_ready() {
194 0 : info!("connection dropped");
195 0 : return Poll::Ready(())
196 0 : }
197 0 :
198 0 : match rx.has_changed() {
199 : Ok(true) => {
200 0 : session_id = *rx.borrow_and_update();
201 0 : info!(%session_id, "changed session");
202 0 : idle_timeout.as_mut().reset(Instant::now() + idle);
203 : }
204 : Err(_) => {
205 0 : info!("connection dropped");
206 0 : return Poll::Ready(())
207 : }
208 0 : _ => {}
209 : }
210 :
211 : // 5 minute idle connection timeout
212 0 : if idle_timeout.as_mut().poll(cx).is_ready() {
213 0 : idle_timeout.as_mut().reset(Instant::now() + idle);
214 0 : info!("connection idle");
215 0 : if let Some(pool) = pool.clone().upgrade() {
216 : // remove client from pool - should close the connection if it's idle.
217 : // does nothing if the client is currently checked-out and in-use
218 0 : if pool.global_pool.write().remove_client(db_user.clone(), conn_id) {
219 0 : info!("idle connection removed");
220 0 : }
221 0 : }
222 0 : }
223 :
224 : loop {
225 0 : let message = ready!(connection.poll_message(cx));
226 :
227 0 : match message {
228 0 : Some(Ok(AsyncMessage::Notice(notice))) => {
229 0 : info!(%session_id, "notice: {}", notice);
230 : }
231 0 : Some(Ok(AsyncMessage::Notification(notif))) => {
232 0 : warn!(%session_id, pid = notif.process_id(), channel = notif.channel(), "notification received");
233 : }
234 : Some(Ok(_)) => {
235 0 : warn!(%session_id, "unknown message");
236 : }
237 0 : Some(Err(e)) => {
238 0 : error!(%session_id, "connection error: {}", e);
239 0 : break
240 : }
241 : None => {
242 0 : info!("connection closed");
243 0 : break
244 : }
245 : }
246 : }
247 :
248 : // remove from connection pool
249 0 : if let Some(pool) = pool.clone().upgrade() {
250 0 : if pool.global_pool.write().remove_client(db_user.clone(), conn_id) {
251 0 : info!("closed connection removed");
252 0 : }
253 0 : }
254 :
255 0 : Poll::Ready(())
256 0 : }).await;
257 :
258 0 : }
259 0 : .instrument(span));
260 0 :
261 0 : let inner = ClientInnerCommon {
262 0 : inner: client,
263 0 : aux,
264 0 : conn_id,
265 0 : data: ClientDataEnum::Local(ClientDataLocal {
266 0 : session: tx,
267 0 : cancel,
268 0 : key,
269 0 : jti: 0,
270 0 : }),
271 0 : };
272 0 :
273 0 : Client::new(inner, conn_info, Arc::downgrade(&global_pool.global_pool))
274 0 : }
275 :
276 : impl ClientInnerCommon<postgres_client::Client> {
277 0 : pub(crate) async fn set_jwt_session(&mut self, payload: &[u8]) -> Result<(), HttpConnError> {
278 0 : if let ClientDataEnum::Local(local_data) = &mut self.data {
279 0 : local_data.jti += 1;
280 0 : let token = resign_jwt(&local_data.key, payload, local_data.jti)?;
281 :
282 : // discard all cannot run in a transaction. must be executed alone.
283 0 : self.inner.batch_execute("discard all").await?;
284 :
285 : // initiates the auth session
286 : // this is safe from query injections as the jwt format free of any escape characters.
287 0 : let query = format!("select auth.jwt_session_init('{token}')");
288 0 : self.inner.batch_execute(&query).await?;
289 :
290 0 : let pid = self.inner.get_process_id();
291 0 : info!(pid, jti = local_data.jti, "user session state init");
292 0 : Ok(())
293 : } else {
294 0 : panic!("unexpected client data type");
295 : }
296 0 : }
297 : }
298 :
299 : /// implements relatively efficient in-place json object key upserting
300 : ///
301 : /// only supports top-level keys
302 1 : fn upsert_json_object(
303 1 : payload: &[u8],
304 1 : key: &str,
305 1 : value: &RawValue,
306 1 : ) -> Result<String, serde_json::Error> {
307 1 : let mut payload = serde_json::from_slice::<IndexMap<&str, &RawValue>>(payload)?;
308 1 : payload.insert(key, value);
309 1 : serde_json::to_string(&payload)
310 1 : }
311 :
312 1 : fn resign_jwt(sk: &SigningKey, payload: &[u8], jti: u64) -> Result<String, HttpConnError> {
313 1 : let mut buffer = itoa::Buffer::new();
314 1 :
315 1 : // encode the jti integer to a json rawvalue
316 1 : let jti = serde_json::from_str::<&RawValue>(buffer.format(jti))
317 1 : .expect("itoa formatted integer should be guaranteed valid json");
318 :
319 : // update the jti in-place
320 1 : let payload =
321 1 : upsert_json_object(payload, "jti", jti).map_err(HttpConnError::JwtPayloadError)?;
322 :
323 : // sign the jwt
324 1 : let token = sign_jwt(sk, payload.as_bytes());
325 1 :
326 1 : Ok(token)
327 1 : }
328 :
329 1 : fn sign_jwt(sk: &SigningKey, payload: &[u8]) -> String {
330 1 : let header_len = 20;
331 1 : let payload_len = Base64UrlUnpadded::encoded_len(payload);
332 1 : let signature_len = Base64UrlUnpadded::encoded_len(&[0; 64]);
333 1 : let total_len = header_len + payload_len + signature_len + 2;
334 1 :
335 1 : let mut jwt = String::with_capacity(total_len);
336 1 : let cap = jwt.capacity();
337 1 :
338 1 : // we only need an empty header with the alg specified.
339 1 : // base64url(r#"{"alg":"EdDSA"}"#) == "eyJhbGciOiJFZERTQSJ9"
340 1 : jwt.push_str("eyJhbGciOiJFZERTQSJ9.");
341 1 :
342 1 : // encode the jwt payload in-place
343 1 : base64::encode_config_buf(payload, base64::URL_SAFE_NO_PAD, &mut jwt);
344 1 :
345 1 : // create the signature from the encoded header || payload
346 1 : let sig: Signature = sk.sign(jwt.as_bytes());
347 1 :
348 1 : jwt.push('.');
349 1 :
350 1 : // encode the jwt signature in-place
351 1 : base64::encode_config_buf(sig.to_bytes(), base64::URL_SAFE_NO_PAD, &mut jwt);
352 1 :
353 1 : debug_assert_eq!(
354 1 : jwt.len(),
355 : total_len,
356 0 : "the jwt len should match our expected len"
357 : );
358 1 : debug_assert_eq!(jwt.capacity(), cap, "the jwt capacity should not change");
359 :
360 1 : jwt
361 1 : }
362 :
363 : #[cfg(test)]
364 : #[expect(clippy::unwrap_used)]
365 : mod tests {
366 : use ed25519_dalek::SigningKey;
367 : use typed_json::json;
368 :
369 : use super::resign_jwt;
370 :
371 : #[test]
372 1 : fn jwt_token_snapshot() {
373 1 : let key = SigningKey::from_bytes(&[1; 32]);
374 1 : let data =
375 1 : json!({"foo":"bar","jti":"foo\nbar","nested":{"jti":"tricky nesting"}}).to_string();
376 1 :
377 1 : let jwt = resign_jwt(&key, data.as_bytes(), 2).unwrap();
378 1 :
379 1 : // To validate the JWT, copy the JWT string and paste it into https://jwt.io/.
380 1 : // In the public-key box, paste the following jwk public key
381 1 : // `{"kty":"OKP","crv":"Ed25519","x":"iojj3XQJ8ZX9UtstPLpdcspnCb8dlBIb83SIAbQPb1w"}`
382 1 : // Note - jwt.io doesn't support EdDSA :(
383 1 : // https://github.com/jsonwebtoken/jsonwebtoken.github.io/issues/509
384 1 :
385 1 : // let jwk = jose_jwk::Key::Okp(jose_jwk::Okp {
386 1 : // crv: jose_jwk::OkpCurves::Ed25519,
387 1 : // x: jose_jwk::jose_b64::serde::Bytes::from(key.verifying_key().to_bytes().to_vec()),
388 1 : // d: None,
389 1 : // });
390 1 : // println!("{}", serde_json::to_string(&jwk).unwrap());
391 1 :
392 1 : assert_eq!(jwt, "eyJhbGciOiJFZERTQSJ9.eyJmb28iOiJiYXIiLCJqdGkiOjIsIm5lc3RlZCI6eyJqdGkiOiJ0cmlja3kgbmVzdGluZyJ9fQ.Cvyc2By33KI0f0obystwdy8PN111L3Sc9_Mr2CU3XshtSqSdxuRxNEZGbb_RvyJf2IzheC_s7aBZ-jLeQ9N0Bg");
393 1 : }
394 : }
|