LCOV - code coverage report
Current view: top level - proxy/src/control_plane/provider - neon.rs (source / functions) Coverage Total Hit
Test: 903780b8ddc62f532be8f220102da7b91c63a235.info Lines: 7.4 % 284 21
Test Date: 2024-10-25 10:10:57 Functions: 10.8 % 37 4

            Line data    Source code
       1              : //! Production console backend.
       2              : 
       3              : use std::sync::Arc;
       4              : use std::time::Duration;
       5              : 
       6              : use ::http::header::AUTHORIZATION;
       7              : use ::http::HeaderName;
       8              : use futures::TryFutureExt;
       9              : use tokio::time::Instant;
      10              : use tokio_postgres::config::SslMode;
      11              : use tracing::{debug, info, info_span, warn, Instrument};
      12              : 
      13              : use super::super::messages::{ControlPlaneError, GetRoleSecret, WakeCompute};
      14              : use super::errors::{ApiError, GetAuthInfoError, WakeComputeError};
      15              : use super::{
      16              :     ApiCaches, ApiLocks, AuthInfo, AuthSecret, CachedAllowedIps, CachedNodeInfo, CachedRoleSecret,
      17              :     NodeInfo,
      18              : };
      19              : use crate::auth::backend::jwt::AuthRule;
      20              : use crate::auth::backend::ComputeUserInfo;
      21              : use crate::cache::Cached;
      22              : use crate::context::RequestMonitoring;
      23              : use crate::control_plane::errors::GetEndpointJwksError;
      24              : use crate::control_plane::messages::{ColdStartInfo, EndpointJwksResponse, Reason};
      25              : use crate::metrics::{CacheOutcome, Metrics};
      26              : use crate::rate_limiter::WakeComputeRateLimiter;
      27              : use crate::types::{EndpointCacheKey, EndpointId};
      28              : use crate::{compute, http, scram};
      29              : 
      30              : const X_REQUEST_ID: HeaderName = HeaderName::from_static("x-request-id");
      31              : 
      32              : #[derive(Clone)]
      33              : pub struct Api {
      34              :     endpoint: http::Endpoint,
      35              :     pub caches: &'static ApiCaches,
      36              :     pub(crate) locks: &'static ApiLocks<EndpointCacheKey>,
      37              :     pub(crate) wake_compute_endpoint_rate_limiter: Arc<WakeComputeRateLimiter>,
      38              :     // put in a shared ref so we don't copy secrets all over in memory
      39              :     jwt: Arc<str>,
      40              : }
      41              : 
      42              : impl Api {
      43              :     /// Construct an API object containing the auth parameters.
      44            0 :     pub fn new(
      45            0 :         endpoint: http::Endpoint,
      46            0 :         caches: &'static ApiCaches,
      47            0 :         locks: &'static ApiLocks<EndpointCacheKey>,
      48            0 :         wake_compute_endpoint_rate_limiter: Arc<WakeComputeRateLimiter>,
      49            0 :     ) -> Self {
      50            0 :         let jwt = std::env::var("NEON_PROXY_TO_CONTROLPLANE_TOKEN")
      51            0 :             .unwrap_or_default()
      52            0 :             .into();
      53            0 :         Self {
      54            0 :             endpoint,
      55            0 :             caches,
      56            0 :             locks,
      57            0 :             wake_compute_endpoint_rate_limiter,
      58            0 :             jwt,
      59            0 :         }
      60            0 :     }
      61              : 
      62            0 :     pub(crate) fn url(&self) -> &str {
      63            0 :         self.endpoint.url().as_str()
      64            0 :     }
      65              : 
      66            0 :     async fn do_get_auth_info(
      67            0 :         &self,
      68            0 :         ctx: &RequestMonitoring,
      69            0 :         user_info: &ComputeUserInfo,
      70            0 :     ) -> Result<AuthInfo, GetAuthInfoError> {
      71            0 :         if !self
      72            0 :             .caches
      73            0 :             .endpoints_cache
      74            0 :             .is_valid(ctx, &user_info.endpoint.normalize())
      75            0 :             .await
      76              :         {
      77            0 :             info!("endpoint is not valid, skipping the request");
      78            0 :             return Ok(AuthInfo::default());
      79            0 :         }
      80            0 :         let request_id = ctx.session_id().to_string();
      81            0 :         let application_name = ctx.console_application_name();
      82            0 :         async {
      83            0 :             let request = self
      84            0 :                 .endpoint
      85            0 :                 .get_path("proxy_get_role_secret")
      86            0 :                 .header(X_REQUEST_ID, &request_id)
      87            0 :                 .header(AUTHORIZATION, format!("Bearer {}", &self.jwt))
      88            0 :                 .query(&[("session_id", ctx.session_id())])
      89            0 :                 .query(&[
      90            0 :                     ("application_name", application_name.as_str()),
      91            0 :                     ("project", user_info.endpoint.as_str()),
      92            0 :                     ("role", user_info.user.as_str()),
      93            0 :                 ])
      94            0 :                 .build()?;
      95              : 
      96            0 :             info!(url = request.url().as_str(), "sending http request");
      97            0 :             let start = Instant::now();
      98            0 :             let pause = ctx.latency_timer_pause(crate::metrics::Waiting::Cplane);
      99            0 :             let response = self.endpoint.execute(request).await?;
     100            0 :             drop(pause);
     101            0 :             info!(duration = ?start.elapsed(), "received http response");
     102            0 :             let body = match parse_body::<GetRoleSecret>(response).await {
     103            0 :                 Ok(body) => body,
     104              :                 // Error 404 is special: it's ok not to have a secret.
     105              :                 // TODO(anna): retry
     106            0 :                 Err(e) => {
     107            0 :                     return if e.get_reason().is_not_found() {
     108            0 :                         Ok(AuthInfo::default())
     109              :                     } else {
     110            0 :                         Err(e.into())
     111              :                     }
     112              :                 }
     113              :             };
     114              : 
     115            0 :             let secret = if body.role_secret.is_empty() {
     116            0 :                 None
     117              :             } else {
     118            0 :                 let secret = scram::ServerSecret::parse(&body.role_secret)
     119            0 :                     .map(AuthSecret::Scram)
     120            0 :                     .ok_or(GetAuthInfoError::BadSecret)?;
     121            0 :                 Some(secret)
     122              :             };
     123            0 :             let allowed_ips = body.allowed_ips.unwrap_or_default();
     124            0 :             Metrics::get()
     125            0 :                 .proxy
     126            0 :                 .allowed_ips_number
     127            0 :                 .observe(allowed_ips.len() as f64);
     128            0 :             Ok(AuthInfo {
     129            0 :                 secret,
     130            0 :                 allowed_ips,
     131            0 :                 project_id: body.project_id,
     132            0 :             })
     133            0 :         }
     134            0 :         .map_err(crate::error::log_error)
     135            0 :         .instrument(info_span!("http", id = request_id))
     136            0 :         .await
     137            0 :     }
     138              : 
     139            0 :     async fn do_get_endpoint_jwks(
     140            0 :         &self,
     141            0 :         ctx: &RequestMonitoring,
     142            0 :         endpoint: EndpointId,
     143            0 :     ) -> Result<Vec<AuthRule>, GetEndpointJwksError> {
     144            0 :         if !self
     145            0 :             .caches
     146            0 :             .endpoints_cache
     147            0 :             .is_valid(ctx, &endpoint.normalize())
     148            0 :             .await
     149              :         {
     150            0 :             return Err(GetEndpointJwksError::EndpointNotFound);
     151            0 :         }
     152            0 :         let request_id = ctx.session_id().to_string();
     153            0 :         async {
     154            0 :             let request = self
     155            0 :                 .endpoint
     156            0 :                 .get_with_url(|url| {
     157            0 :                     url.path_segments_mut()
     158            0 :                         .push("endpoints")
     159            0 :                         .push(endpoint.as_str())
     160            0 :                         .push("jwks");
     161            0 :                 })
     162            0 :                 .header(X_REQUEST_ID, &request_id)
     163            0 :                 .header(AUTHORIZATION, format!("Bearer {}", &self.jwt))
     164            0 :                 .query(&[("session_id", ctx.session_id())])
     165            0 :                 .build()
     166            0 :                 .map_err(GetEndpointJwksError::RequestBuild)?;
     167              : 
     168            0 :             info!(url = request.url().as_str(), "sending http request");
     169            0 :             let start = Instant::now();
     170            0 :             let pause = ctx.latency_timer_pause(crate::metrics::Waiting::Cplane);
     171            0 :             let response = self
     172            0 :                 .endpoint
     173            0 :                 .execute(request)
     174            0 :                 .await
     175            0 :                 .map_err(GetEndpointJwksError::RequestExecute)?;
     176            0 :             drop(pause);
     177            0 :             info!(duration = ?start.elapsed(), "received http response");
     178              : 
     179            0 :             let body = parse_body::<EndpointJwksResponse>(response).await?;
     180              : 
     181            0 :             let rules = body
     182            0 :                 .jwks
     183            0 :                 .into_iter()
     184            0 :                 .map(|jwks| AuthRule {
     185            0 :                     id: jwks.id,
     186            0 :                     jwks_url: jwks.jwks_url,
     187            0 :                     audience: jwks.jwt_audience,
     188            0 :                     role_names: jwks.role_names,
     189            0 :                 })
     190            0 :                 .collect();
     191            0 : 
     192            0 :             Ok(rules)
     193            0 :         }
     194            0 :         .map_err(crate::error::log_error)
     195            0 :         .instrument(info_span!("http", id = request_id))
     196            0 :         .await
     197            0 :     }
     198              : 
     199            0 :     async fn do_wake_compute(
     200            0 :         &self,
     201            0 :         ctx: &RequestMonitoring,
     202            0 :         user_info: &ComputeUserInfo,
     203            0 :     ) -> Result<NodeInfo, WakeComputeError> {
     204            0 :         let request_id = ctx.session_id().to_string();
     205            0 :         let application_name = ctx.console_application_name();
     206            0 :         async {
     207            0 :             let mut request_builder = self
     208            0 :                 .endpoint
     209            0 :                 .get_path("proxy_wake_compute")
     210            0 :                 .header("X-Request-ID", &request_id)
     211            0 :                 .header("Authorization", format!("Bearer {}", &self.jwt))
     212            0 :                 .query(&[("session_id", ctx.session_id())])
     213            0 :                 .query(&[
     214            0 :                     ("application_name", application_name.as_str()),
     215            0 :                     ("project", user_info.endpoint.as_str()),
     216            0 :                 ]);
     217            0 : 
     218            0 :             let options = user_info.options.to_deep_object();
     219            0 :             if !options.is_empty() {
     220            0 :                 request_builder = request_builder.query(&options);
     221            0 :             }
     222              : 
     223            0 :             let request = request_builder.build()?;
     224              : 
     225            0 :             info!(url = request.url().as_str(), "sending http request");
     226            0 :             let start = Instant::now();
     227            0 :             let pause = ctx.latency_timer_pause(crate::metrics::Waiting::Cplane);
     228            0 :             let response = self.endpoint.execute(request).await?;
     229            0 :             drop(pause);
     230            0 :             info!(duration = ?start.elapsed(), "received http response");
     231            0 :             let body = parse_body::<WakeCompute>(response).await?;
     232              : 
     233              :             // Unfortunately, ownership won't let us use `Option::ok_or` here.
     234            0 :             let (host, port) = match parse_host_port(&body.address) {
     235            0 :                 None => return Err(WakeComputeError::BadComputeAddress(body.address)),
     236            0 :                 Some(x) => x,
     237            0 :             };
     238            0 : 
     239            0 :             // Don't set anything but host and port! This config will be cached.
     240            0 :             // We'll set username and such later using the startup message.
     241            0 :             // TODO: add more type safety (in progress).
     242            0 :             let mut config = compute::ConnCfg::new();
     243            0 :             config.host(host).port(port).ssl_mode(SslMode::Disable); // TLS is not configured on compute nodes.
     244            0 : 
     245            0 :             let node = NodeInfo {
     246            0 :                 config,
     247            0 :                 aux: body.aux,
     248            0 :                 allow_self_signed_compute: false,
     249            0 :             };
     250            0 : 
     251            0 :             Ok(node)
     252            0 :         }
     253            0 :         .map_err(crate::error::log_error)
     254            0 :         .instrument(info_span!("http", id = request_id))
     255            0 :         .await
     256            0 :     }
     257              : }
     258              : 
     259              : impl super::Api for Api {
     260            0 :     #[tracing::instrument(skip_all)]
     261              :     async fn get_role_secret(
     262              :         &self,
     263              :         ctx: &RequestMonitoring,
     264              :         user_info: &ComputeUserInfo,
     265              :     ) -> Result<CachedRoleSecret, GetAuthInfoError> {
     266              :         let normalized_ep = &user_info.endpoint.normalize();
     267              :         let user = &user_info.user;
     268              :         if let Some(role_secret) = self
     269              :             .caches
     270              :             .project_info
     271              :             .get_role_secret(normalized_ep, user)
     272              :         {
     273              :             return Ok(role_secret);
     274              :         }
     275              :         let auth_info = self.do_get_auth_info(ctx, user_info).await?;
     276              :         if let Some(project_id) = auth_info.project_id {
     277              :             let normalized_ep_int = normalized_ep.into();
     278              :             self.caches.project_info.insert_role_secret(
     279              :                 project_id,
     280              :                 normalized_ep_int,
     281              :                 user.into(),
     282              :                 auth_info.secret.clone(),
     283              :             );
     284              :             self.caches.project_info.insert_allowed_ips(
     285              :                 project_id,
     286              :                 normalized_ep_int,
     287              :                 Arc::new(auth_info.allowed_ips),
     288              :             );
     289              :             ctx.set_project_id(project_id);
     290              :         }
     291              :         // When we just got a secret, we don't need to invalidate it.
     292              :         Ok(Cached::new_uncached(auth_info.secret))
     293              :     }
     294              : 
     295            0 :     async fn get_allowed_ips_and_secret(
     296            0 :         &self,
     297            0 :         ctx: &RequestMonitoring,
     298            0 :         user_info: &ComputeUserInfo,
     299            0 :     ) -> Result<(CachedAllowedIps, Option<CachedRoleSecret>), GetAuthInfoError> {
     300            0 :         let normalized_ep = &user_info.endpoint.normalize();
     301            0 :         if let Some(allowed_ips) = self.caches.project_info.get_allowed_ips(normalized_ep) {
     302            0 :             Metrics::get()
     303            0 :                 .proxy
     304            0 :                 .allowed_ips_cache_misses
     305            0 :                 .inc(CacheOutcome::Hit);
     306            0 :             return Ok((allowed_ips, None));
     307            0 :         }
     308            0 :         Metrics::get()
     309            0 :             .proxy
     310            0 :             .allowed_ips_cache_misses
     311            0 :             .inc(CacheOutcome::Miss);
     312            0 :         let auth_info = self.do_get_auth_info(ctx, user_info).await?;
     313            0 :         let allowed_ips = Arc::new(auth_info.allowed_ips);
     314            0 :         let user = &user_info.user;
     315            0 :         if let Some(project_id) = auth_info.project_id {
     316            0 :             let normalized_ep_int = normalized_ep.into();
     317            0 :             self.caches.project_info.insert_role_secret(
     318            0 :                 project_id,
     319            0 :                 normalized_ep_int,
     320            0 :                 user.into(),
     321            0 :                 auth_info.secret.clone(),
     322            0 :             );
     323            0 :             self.caches.project_info.insert_allowed_ips(
     324            0 :                 project_id,
     325            0 :                 normalized_ep_int,
     326            0 :                 allowed_ips.clone(),
     327            0 :             );
     328            0 :             ctx.set_project_id(project_id);
     329            0 :         }
     330            0 :         Ok((
     331            0 :             Cached::new_uncached(allowed_ips),
     332            0 :             Some(Cached::new_uncached(auth_info.secret)),
     333            0 :         ))
     334            0 :     }
     335              : 
     336            0 :     #[tracing::instrument(skip_all)]
     337              :     async fn get_endpoint_jwks(
     338              :         &self,
     339              :         ctx: &RequestMonitoring,
     340              :         endpoint: EndpointId,
     341              :     ) -> Result<Vec<AuthRule>, GetEndpointJwksError> {
     342              :         self.do_get_endpoint_jwks(ctx, endpoint).await
     343              :     }
     344              : 
     345            0 :     #[tracing::instrument(skip_all)]
     346              :     async fn wake_compute(
     347              :         &self,
     348              :         ctx: &RequestMonitoring,
     349              :         user_info: &ComputeUserInfo,
     350              :     ) -> Result<CachedNodeInfo, WakeComputeError> {
     351              :         let key = user_info.endpoint_cache_key();
     352              : 
     353              :         macro_rules! check_cache {
     354              :             () => {
     355              :                 if let Some(cached) = self.caches.node_info.get(&key) {
     356              :                     let (cached, info) = cached.take_value();
     357            0 :                     let info = info.map_err(|c| {
     358            0 :                         info!(key = &*key, "found cached wake_compute error");
     359            0 :                         WakeComputeError::ApiError(ApiError::ControlPlane(Box::new(*c)))
     360            0 :                     })?;
     361              : 
     362              :                     debug!(key = &*key, "found cached compute node info");
     363              :                     ctx.set_project(info.aux.clone());
     364            0 :                     return Ok(cached.map(|()| info));
     365              :                 }
     366              :             };
     367              :         }
     368              : 
     369              :         // Every time we do a wakeup http request, the compute node will stay up
     370              :         // for some time (highly depends on the console's scale-to-zero policy);
     371              :         // The connection info remains the same during that period of time,
     372              :         // which means that we might cache it to reduce the load and latency.
     373              :         check_cache!();
     374              : 
     375              :         let permit = self.locks.get_permit(&key).await?;
     376              : 
     377              :         // after getting back a permit - it's possible the cache was filled
     378              :         // double check
     379              :         if permit.should_check_cache() {
     380              :             check_cache!();
     381              :         }
     382              : 
     383              :         // check rate limit
     384              :         if !self
     385              :             .wake_compute_endpoint_rate_limiter
     386              :             .check(user_info.endpoint.normalize_intern(), 1)
     387              :         {
     388              :             return Err(WakeComputeError::TooManyConnections);
     389              :         }
     390              : 
     391              :         let node = permit.release_result(self.do_wake_compute(ctx, user_info).await);
     392              :         match node {
     393              :             Ok(node) => {
     394              :                 ctx.set_project(node.aux.clone());
     395              :                 debug!(key = &*key, "created a cache entry for woken compute node");
     396              : 
     397              :                 let mut stored_node = node.clone();
     398              :                 // store the cached node as 'warm_cached'
     399              :                 stored_node.aux.cold_start_info = ColdStartInfo::WarmCached;
     400              : 
     401              :                 let (_, cached) = self.caches.node_info.insert_unit(key, Ok(stored_node));
     402              : 
     403            0 :                 Ok(cached.map(|()| node))
     404              :             }
     405              :             Err(err) => match err {
     406              :                 WakeComputeError::ApiError(ApiError::ControlPlane(err)) => {
     407              :                     let Some(status) = &err.status else {
     408              :                         return Err(WakeComputeError::ApiError(ApiError::ControlPlane(err)));
     409              :                     };
     410              : 
     411              :                     let reason = status
     412              :                         .details
     413              :                         .error_info
     414            0 :                         .map_or(Reason::Unknown, |x| x.reason);
     415              : 
     416              :                     // if we can retry this error, do not cache it.
     417              :                     if reason.can_retry() {
     418              :                         return Err(WakeComputeError::ApiError(ApiError::ControlPlane(err)));
     419              :                     }
     420              : 
     421              :                     // at this point, we should only have quota errors.
     422              :                     debug!(
     423              :                         key = &*key,
     424              :                         "created a cache entry for the wake compute error"
     425              :                     );
     426              : 
     427              :                     self.caches.node_info.insert_ttl(
     428              :                         key,
     429              :                         Err(err.clone()),
     430              :                         Duration::from_secs(30),
     431              :                     );
     432              : 
     433              :                     Err(WakeComputeError::ApiError(ApiError::ControlPlane(err)))
     434              :                 }
     435              :                 err => return Err(err),
     436              :             },
     437              :         }
     438              :     }
     439              : }
     440              : 
     441              : /// Parse http response body, taking status code into account.
     442            0 : async fn parse_body<T: for<'a> serde::Deserialize<'a>>(
     443            0 :     response: http::Response,
     444            0 : ) -> Result<T, ApiError> {
     445            0 :     let status = response.status();
     446            0 :     if status.is_success() {
     447              :         // We shouldn't log raw body because it may contain secrets.
     448            0 :         info!("request succeeded, processing the body");
     449            0 :         return Ok(response.json().await?);
     450            0 :     }
     451            0 :     let s = response.bytes().await?;
     452              :     // Log plaintext to be able to detect, whether there are some cases not covered by the error struct.
     453            0 :     info!("response_error plaintext: {:?}", s);
     454              : 
     455              :     // Don't throw an error here because it's not as important
     456              :     // as the fact that the request itself has failed.
     457            0 :     let mut body = serde_json::from_slice(&s).unwrap_or_else(|e| {
     458            0 :         warn!("failed to parse error body: {e}");
     459            0 :         ControlPlaneError {
     460            0 :             error: "reason unclear (malformed error message)".into(),
     461            0 :             http_status_code: status,
     462            0 :             status: None,
     463            0 :         }
     464            0 :     });
     465            0 :     body.http_status_code = status;
     466            0 : 
     467            0 :     warn!("console responded with an error ({status}): {body:?}");
     468            0 :     Err(ApiError::ControlPlane(Box::new(body)))
     469            0 : }
     470              : 
     471            3 : fn parse_host_port(input: &str) -> Option<(&str, u16)> {
     472            3 :     let (host, port) = input.rsplit_once(':')?;
     473            3 :     let ipv6_brackets: &[_] = &['[', ']'];
     474            3 :     Some((host.trim_matches(ipv6_brackets), port.parse().ok()?))
     475            3 : }
     476              : 
     477              : #[cfg(test)]
     478              : mod tests {
     479              :     use super::*;
     480              : 
     481              :     #[test]
     482            1 :     fn test_parse_host_port_v4() {
     483            1 :         let (host, port) = parse_host_port("127.0.0.1:5432").expect("failed to parse");
     484            1 :         assert_eq!(host, "127.0.0.1");
     485            1 :         assert_eq!(port, 5432);
     486            1 :     }
     487              : 
     488              :     #[test]
     489            1 :     fn test_parse_host_port_v6() {
     490            1 :         let (host, port) = parse_host_port("[2001:db8::1]:5432").expect("failed to parse");
     491            1 :         assert_eq!(host, "2001:db8::1");
     492            1 :         assert_eq!(port, 5432);
     493            1 :     }
     494              : 
     495              :     #[test]
     496            1 :     fn test_parse_host_port_url() {
     497            1 :         let (host, port) = parse_host_port("compute-foo-bar-1234.default.svc.cluster.local:5432")
     498            1 :             .expect("failed to parse");
     499            1 :         assert_eq!(host, "compute-foo-bar-1234.default.svc.cluster.local");
     500            1 :         assert_eq!(port, 5432);
     501            1 :     }
     502              : }
        

Generated by: LCOV version 2.1-beta