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::{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 : 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 : info!(
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: tokio_postgres::Connection<Socket, 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 : let pool_clone = pool.clone();
181 0 :
182 0 : let db_user = conn_info.db_and_user();
183 0 : let idle = global_pool.get_idle_timeout();
184 0 : let cancel = CancellationToken::new();
185 0 : let cancelled = cancel.clone().cancelled_owned();
186 0 :
187 0 : tokio::spawn(
188 0 : async move {
189 0 : let _conn_gauge = conn_gauge;
190 0 : let mut idle_timeout = pin!(tokio::time::sleep(idle));
191 0 : let mut cancelled = pin!(cancelled);
192 0 :
193 0 : poll_fn(move |cx| {
194 0 : if cancelled.as_mut().poll(cx).is_ready() {
195 0 : info!("connection dropped");
196 0 : return Poll::Ready(())
197 0 : }
198 0 :
199 0 : match rx.has_changed() {
200 : Ok(true) => {
201 0 : session_id = *rx.borrow_and_update();
202 0 : info!(%session_id, "changed session");
203 0 : idle_timeout.as_mut().reset(Instant::now() + idle);
204 : }
205 : Err(_) => {
206 0 : info!("connection dropped");
207 0 : return Poll::Ready(())
208 : }
209 0 : _ => {}
210 : }
211 :
212 : // 5 minute idle connection timeout
213 0 : if idle_timeout.as_mut().poll(cx).is_ready() {
214 0 : idle_timeout.as_mut().reset(Instant::now() + idle);
215 0 : info!("connection idle");
216 0 : if let Some(pool) = pool.clone().upgrade() {
217 : // remove client from pool - should close the connection if it's idle.
218 : // does nothing if the client is currently checked-out and in-use
219 0 : if pool.global_pool.write().remove_client(db_user.clone(), conn_id) {
220 0 : info!("idle connection removed");
221 0 : }
222 0 : }
223 0 : }
224 :
225 : loop {
226 0 : let message = ready!(connection.poll_message(cx));
227 :
228 0 : match message {
229 0 : Some(Ok(AsyncMessage::Notice(notice))) => {
230 0 : info!(%session_id, "notice: {}", notice);
231 : }
232 0 : Some(Ok(AsyncMessage::Notification(notif))) => {
233 0 : warn!(%session_id, pid = notif.process_id(), channel = notif.channel(), "notification received");
234 : }
235 : Some(Ok(_)) => {
236 0 : warn!(%session_id, "unknown message");
237 : }
238 0 : Some(Err(e)) => {
239 0 : error!(%session_id, "connection error: {}", e);
240 0 : break
241 : }
242 : None => {
243 0 : info!("connection closed");
244 0 : break
245 : }
246 : }
247 : }
248 :
249 : // remove from connection pool
250 0 : if let Some(pool) = pool.clone().upgrade() {
251 0 : if pool.global_pool.write().remove_client(db_user.clone(), conn_id) {
252 0 : info!("closed connection removed");
253 0 : }
254 0 : }
255 :
256 0 : Poll::Ready(())
257 0 : }).await;
258 :
259 0 : }
260 0 : .instrument(span));
261 0 :
262 0 : let inner = ClientInnerCommon {
263 0 : inner: client,
264 0 : aux,
265 0 : conn_id,
266 0 : data: ClientDataEnum::Local(ClientDataLocal {
267 0 : session: tx,
268 0 : cancel,
269 0 : key,
270 0 : jti: 0,
271 0 : }),
272 0 : };
273 0 :
274 0 : Client::new(
275 0 : inner,
276 0 : conn_info,
277 0 : Arc::downgrade(&pool_clone.upgrade().unwrap().global_pool),
278 0 : )
279 0 : }
280 :
281 : impl ClientInnerCommon<tokio_postgres::Client> {
282 0 : pub(crate) async fn set_jwt_session(&mut self, payload: &[u8]) -> Result<(), HttpConnError> {
283 0 : if let ClientDataEnum::Local(local_data) = &mut self.data {
284 0 : local_data.jti += 1;
285 0 : let token = resign_jwt(&local_data.key, payload, local_data.jti)?;
286 :
287 : // initiates the auth session
288 0 : self.inner.simple_query("discard all").await?;
289 0 : self.inner
290 0 : .query(
291 0 : "select auth.jwt_session_init($1)",
292 0 : &[&token as &(dyn ToSql + Sync)],
293 0 : )
294 0 : .await?;
295 :
296 0 : let pid = self.inner.get_process_id();
297 0 : info!(pid, jti = local_data.jti, "user session state init");
298 0 : Ok(())
299 : } else {
300 0 : panic!("unexpected client data type");
301 : }
302 0 : }
303 : }
304 :
305 : /// implements relatively efficient in-place json object key upserting
306 : ///
307 : /// only supports top-level keys
308 1 : fn upsert_json_object(
309 1 : payload: &[u8],
310 1 : key: &str,
311 1 : value: &RawValue,
312 1 : ) -> Result<String, serde_json::Error> {
313 1 : let mut payload = serde_json::from_slice::<IndexMap<&str, &RawValue>>(payload)?;
314 1 : payload.insert(key, value);
315 1 : serde_json::to_string(&payload)
316 1 : }
317 :
318 1 : fn resign_jwt(sk: &SigningKey, payload: &[u8], jti: u64) -> Result<String, HttpConnError> {
319 1 : let mut buffer = itoa::Buffer::new();
320 1 :
321 1 : // encode the jti integer to a json rawvalue
322 1 : let jti = serde_json::from_str::<&RawValue>(buffer.format(jti)).unwrap();
323 :
324 : // update the jti in-place
325 1 : let payload =
326 1 : upsert_json_object(payload, "jti", jti).map_err(HttpConnError::JwtPayloadError)?;
327 :
328 : // sign the jwt
329 1 : let token = sign_jwt(sk, payload.as_bytes());
330 1 :
331 1 : Ok(token)
332 1 : }
333 :
334 1 : fn sign_jwt(sk: &SigningKey, payload: &[u8]) -> String {
335 1 : let header_len = 20;
336 1 : let payload_len = Base64UrlUnpadded::encoded_len(payload);
337 1 : let signature_len = Base64UrlUnpadded::encoded_len(&[0; 64]);
338 1 : let total_len = header_len + payload_len + signature_len + 2;
339 1 :
340 1 : let mut jwt = String::with_capacity(total_len);
341 1 : let cap = jwt.capacity();
342 1 :
343 1 : // we only need an empty header with the alg specified.
344 1 : // base64url(r#"{"alg":"ES256"}"#) == "eyJhbGciOiJFUzI1NiJ9"
345 1 : jwt.push_str("eyJhbGciOiJFUzI1NiJ9.");
346 1 :
347 1 : // encode the jwt payload in-place
348 1 : base64::encode_config_buf(payload, base64::URL_SAFE_NO_PAD, &mut jwt);
349 1 :
350 1 : // create the signature from the encoded header || payload
351 1 : let sig: Signature = sk.sign(jwt.as_bytes());
352 1 :
353 1 : jwt.push('.');
354 1 :
355 1 : // encode the jwt signature in-place
356 1 : base64::encode_config_buf(sig.to_bytes(), base64::URL_SAFE_NO_PAD, &mut jwt);
357 1 :
358 1 : debug_assert_eq!(
359 1 : jwt.len(),
360 : total_len,
361 0 : "the jwt len should match our expected len"
362 : );
363 1 : debug_assert_eq!(jwt.capacity(), cap, "the jwt capacity should not change");
364 :
365 1 : jwt
366 1 : }
367 :
368 : #[cfg(test)]
369 : mod tests {
370 : use p256::ecdsa::SigningKey;
371 : use typed_json::json;
372 :
373 : use super::resign_jwt;
374 :
375 : #[test]
376 1 : fn jwt_token_snapshot() {
377 1 : let key = SigningKey::from_bytes(&[1; 32].into()).unwrap();
378 1 : let data =
379 1 : json!({"foo":"bar","jti":"foo\nbar","nested":{"jti":"tricky nesting"}}).to_string();
380 1 :
381 1 : let jwt = resign_jwt(&key, data.as_bytes(), 2).unwrap();
382 1 :
383 1 : // To validate the JWT, copy the JWT string and paste it into https://jwt.io/.
384 1 : // In the public-key box, paste the following jwk public key
385 1 : // `{"kty":"EC","crv":"P-256","x":"b_A7lJJBzh2t1DUZ5pYOCoW0GmmgXDKBA6orzhWUyhY","y":"PE91OlW_AdxT9sCwx-7ni0DG_30lqW4igrmJzvccFEo"}`
386 1 :
387 1 : // let pub_key = p256::ecdsa::VerifyingKey::from(&key);
388 1 : // let pub_key = p256::PublicKey::from(pub_key);
389 1 : // println!("{}", pub_key.to_jwk_string());
390 1 :
391 1 : assert_eq!(jwt, "eyJhbGciOiJFUzI1NiJ9.eyJmb28iOiJiYXIiLCJqdGkiOjIsIm5lc3RlZCI6eyJqdGkiOiJ0cmlja3kgbmVzdGluZyJ9fQ.pYf0LxoJ8sDgpmsYOgrbNecOSipnPBEGwnZzB-JhW2cONrKlqRsgXwK8_cOsyolGy-hTTe8GXbWTl_UdpF5RyA");
392 1 : }
393 : }
|