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