LCOV - code coverage report
Current view: top level - proxy/src/serverless - local_conn_pool.rs (source / functions) Coverage Total Hit
Test: 3eba1babe267649f8cebefc91c236589db030548.info Lines: 25.8 % 256 66
Test Date: 2024-11-22 12:36:12 Functions: 14.3 % 28 4

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

Generated by: LCOV version 2.1-beta