Line data Source code
1 : #[cfg(any(test, feature = "testing"))]
2 : pub mod mock;
3 : pub mod neon;
4 :
5 : use std::hash::Hash;
6 : use std::sync::Arc;
7 : use std::time::Duration;
8 :
9 : use dashmap::DashMap;
10 : use tokio::time::Instant;
11 : use tracing::info;
12 :
13 : use super::messages::{ControlPlaneError, MetricsAuxInfo};
14 : use crate::auth::backend::jwt::{AuthRule, FetchAuthRules, FetchAuthRulesError};
15 : use crate::auth::backend::{ComputeCredentialKeys, ComputeUserInfo};
16 : use crate::auth::IpPattern;
17 : use crate::cache::endpoints::EndpointsCache;
18 : use crate::cache::project_info::ProjectInfoCacheImpl;
19 : use crate::cache::{Cached, TimedLru};
20 : use crate::config::{CacheOptions, EndpointCacheConfig, ProjectInfoCacheOptions};
21 : use crate::context::RequestMonitoring;
22 : use crate::error::ReportableError;
23 : use crate::intern::ProjectIdInt;
24 : use crate::metrics::ApiLockMetrics;
25 : use crate::rate_limiter::{DynamicLimiter, Outcome, RateLimiterConfig, Token};
26 : use crate::{compute, scram, EndpointCacheKey, EndpointId};
27 :
28 : pub(crate) mod errors {
29 : use thiserror::Error;
30 :
31 : use super::ApiLockError;
32 : use crate::control_plane::messages::{self, ControlPlaneError, Reason};
33 : use crate::error::{io_error, ErrorKind, ReportableError, UserFacingError};
34 : use crate::proxy::retry::CouldRetry;
35 :
36 : /// A go-to error message which doesn't leak any detail.
37 : pub(crate) const REQUEST_FAILED: &str = "Console request failed";
38 :
39 : /// Common console API error.
40 0 : #[derive(Debug, Error)]
41 : pub(crate) enum ApiError {
42 : /// Error returned by the console itself.
43 : #[error("{REQUEST_FAILED} with {0}")]
44 : ControlPlane(Box<ControlPlaneError>),
45 :
46 : /// Various IO errors like broken pipe or malformed payload.
47 : #[error("{REQUEST_FAILED}: {0}")]
48 : Transport(#[from] std::io::Error),
49 : }
50 :
51 : impl ApiError {
52 : /// Returns HTTP status code if it's the reason for failure.
53 0 : pub(crate) fn get_reason(&self) -> messages::Reason {
54 0 : match self {
55 0 : ApiError::ControlPlane(e) => e.get_reason(),
56 0 : ApiError::Transport(_) => messages::Reason::Unknown,
57 : }
58 0 : }
59 : }
60 :
61 : impl UserFacingError for ApiError {
62 0 : fn to_string_client(&self) -> String {
63 0 : match self {
64 : // To minimize risks, only select errors are forwarded to users.
65 0 : ApiError::ControlPlane(c) => c.get_user_facing_message(),
66 0 : ApiError::Transport(_) => REQUEST_FAILED.to_owned(),
67 : }
68 0 : }
69 : }
70 :
71 : impl ReportableError for ApiError {
72 3 : fn get_error_kind(&self) -> crate::error::ErrorKind {
73 3 : match self {
74 3 : ApiError::ControlPlane(e) => match e.get_reason() {
75 0 : Reason::RoleProtected => ErrorKind::User,
76 0 : Reason::ResourceNotFound => ErrorKind::User,
77 0 : Reason::ProjectNotFound => ErrorKind::User,
78 0 : Reason::EndpointNotFound => ErrorKind::User,
79 0 : Reason::BranchNotFound => ErrorKind::User,
80 0 : Reason::RateLimitExceeded => ErrorKind::ServiceRateLimit,
81 0 : Reason::NonDefaultBranchComputeTimeExceeded => ErrorKind::Quota,
82 0 : Reason::ActiveTimeQuotaExceeded => ErrorKind::Quota,
83 0 : Reason::ComputeTimeQuotaExceeded => ErrorKind::Quota,
84 0 : Reason::WrittenDataQuotaExceeded => ErrorKind::Quota,
85 0 : Reason::DataTransferQuotaExceeded => ErrorKind::Quota,
86 0 : Reason::LogicalSizeQuotaExceeded => ErrorKind::Quota,
87 0 : Reason::ConcurrencyLimitReached => ErrorKind::ControlPlane,
88 0 : Reason::LockAlreadyTaken => ErrorKind::ControlPlane,
89 0 : Reason::RunningOperations => ErrorKind::ControlPlane,
90 0 : Reason::ActiveEndpointsLimitExceeded => ErrorKind::ControlPlane,
91 3 : Reason::Unknown => ErrorKind::ControlPlane,
92 : },
93 0 : ApiError::Transport(_) => crate::error::ErrorKind::ControlPlane,
94 : }
95 3 : }
96 : }
97 :
98 : impl CouldRetry for ApiError {
99 6 : fn could_retry(&self) -> bool {
100 6 : match self {
101 : // retry some transport errors
102 0 : Self::Transport(io) => io.could_retry(),
103 6 : Self::ControlPlane(e) => e.could_retry(),
104 : }
105 6 : }
106 : }
107 :
108 : impl From<reqwest::Error> for ApiError {
109 0 : fn from(e: reqwest::Error) -> Self {
110 0 : io_error(e).into()
111 0 : }
112 : }
113 :
114 : impl From<reqwest_middleware::Error> for ApiError {
115 0 : fn from(e: reqwest_middleware::Error) -> Self {
116 0 : io_error(e).into()
117 0 : }
118 : }
119 :
120 0 : #[derive(Debug, Error)]
121 : pub(crate) enum GetAuthInfoError {
122 : // We shouldn't include the actual secret here.
123 : #[error("Console responded with a malformed auth secret")]
124 : BadSecret,
125 :
126 : #[error(transparent)]
127 : ApiError(ApiError),
128 : }
129 :
130 : // This allows more useful interactions than `#[from]`.
131 : impl<E: Into<ApiError>> From<E> for GetAuthInfoError {
132 0 : fn from(e: E) -> Self {
133 0 : Self::ApiError(e.into())
134 0 : }
135 : }
136 :
137 : impl UserFacingError for GetAuthInfoError {
138 0 : fn to_string_client(&self) -> String {
139 0 : match self {
140 : // We absolutely should not leak any secrets!
141 0 : Self::BadSecret => REQUEST_FAILED.to_owned(),
142 : // However, API might return a meaningful error.
143 0 : Self::ApiError(e) => e.to_string_client(),
144 : }
145 0 : }
146 : }
147 :
148 : impl ReportableError for GetAuthInfoError {
149 0 : fn get_error_kind(&self) -> crate::error::ErrorKind {
150 0 : match self {
151 0 : Self::BadSecret => crate::error::ErrorKind::ControlPlane,
152 0 : Self::ApiError(_) => crate::error::ErrorKind::ControlPlane,
153 : }
154 0 : }
155 : }
156 :
157 0 : #[derive(Debug, Error)]
158 : pub(crate) enum WakeComputeError {
159 : #[error("Console responded with a malformed compute address: {0}")]
160 : BadComputeAddress(Box<str>),
161 :
162 : #[error(transparent)]
163 : ApiError(ApiError),
164 :
165 : #[error("Too many connections attempts")]
166 : TooManyConnections,
167 :
168 : #[error("error acquiring resource permit: {0}")]
169 : TooManyConnectionAttempts(#[from] ApiLockError),
170 : }
171 :
172 : // This allows more useful interactions than `#[from]`.
173 : impl<E: Into<ApiError>> From<E> for WakeComputeError {
174 0 : fn from(e: E) -> Self {
175 0 : Self::ApiError(e.into())
176 0 : }
177 : }
178 :
179 : impl UserFacingError for WakeComputeError {
180 0 : fn to_string_client(&self) -> String {
181 0 : match self {
182 : // We shouldn't show user the address even if it's broken.
183 : // Besides, user is unlikely to care about this detail.
184 0 : Self::BadComputeAddress(_) => REQUEST_FAILED.to_owned(),
185 : // However, API might return a meaningful error.
186 0 : Self::ApiError(e) => e.to_string_client(),
187 :
188 0 : Self::TooManyConnections => self.to_string(),
189 :
190 : Self::TooManyConnectionAttempts(_) => {
191 0 : "Failed to acquire permit to connect to the database. Too many database connection attempts are currently ongoing.".to_owned()
192 : }
193 : }
194 0 : }
195 : }
196 :
197 : impl ReportableError for WakeComputeError {
198 3 : fn get_error_kind(&self) -> crate::error::ErrorKind {
199 3 : match self {
200 0 : Self::BadComputeAddress(_) => crate::error::ErrorKind::ControlPlane,
201 3 : Self::ApiError(e) => e.get_error_kind(),
202 0 : Self::TooManyConnections => crate::error::ErrorKind::RateLimit,
203 0 : Self::TooManyConnectionAttempts(e) => e.get_error_kind(),
204 : }
205 3 : }
206 : }
207 :
208 : impl CouldRetry for WakeComputeError {
209 3 : fn could_retry(&self) -> bool {
210 3 : match self {
211 0 : Self::BadComputeAddress(_) => false,
212 3 : Self::ApiError(e) => e.could_retry(),
213 0 : Self::TooManyConnections => false,
214 0 : Self::TooManyConnectionAttempts(_) => false,
215 : }
216 3 : }
217 : }
218 :
219 0 : #[derive(Debug, Error)]
220 : pub enum GetEndpointJwksError {
221 : #[error("endpoint not found")]
222 : EndpointNotFound,
223 :
224 : #[error("failed to build control plane request: {0}")]
225 : RequestBuild(#[source] reqwest::Error),
226 :
227 : #[error("failed to send control plane request: {0}")]
228 : RequestExecute(#[source] reqwest_middleware::Error),
229 :
230 : #[error(transparent)]
231 : ControlPlane(#[from] ApiError),
232 :
233 : #[cfg(any(test, feature = "testing"))]
234 : #[error(transparent)]
235 : TokioPostgres(#[from] tokio_postgres::Error),
236 :
237 : #[cfg(any(test, feature = "testing"))]
238 : #[error(transparent)]
239 : ParseUrl(#[from] url::ParseError),
240 :
241 : #[cfg(any(test, feature = "testing"))]
242 : #[error(transparent)]
243 : TaskJoin(#[from] tokio::task::JoinError),
244 : }
245 : }
246 :
247 : /// Auth secret which is managed by the cloud.
248 : #[derive(Clone, Eq, PartialEq, Debug)]
249 : pub(crate) enum AuthSecret {
250 : #[cfg(any(test, feature = "testing"))]
251 : /// Md5 hash of user's password.
252 : Md5([u8; 16]),
253 :
254 : /// [SCRAM](crate::scram) authentication info.
255 : Scram(scram::ServerSecret),
256 : }
257 :
258 : #[derive(Default)]
259 : pub(crate) struct AuthInfo {
260 : pub(crate) secret: Option<AuthSecret>,
261 : /// List of IP addresses allowed for the autorization.
262 : pub(crate) allowed_ips: Vec<IpPattern>,
263 : /// Project ID. This is used for cache invalidation.
264 : pub(crate) project_id: Option<ProjectIdInt>,
265 : }
266 :
267 : /// Info for establishing a connection to a compute node.
268 : /// This is what we get after auth succeeded, but not before!
269 : #[derive(Clone)]
270 : pub(crate) struct NodeInfo {
271 : /// Compute node connection params.
272 : /// It's sad that we have to clone this, but this will improve
273 : /// once we migrate to a bespoke connection logic.
274 : pub(crate) config: compute::ConnCfg,
275 :
276 : /// Labels for proxy's metrics.
277 : pub(crate) aux: MetricsAuxInfo,
278 :
279 : /// Whether we should accept self-signed certificates (for testing)
280 : pub(crate) allow_self_signed_compute: bool,
281 : }
282 :
283 : impl NodeInfo {
284 0 : pub(crate) async fn connect(
285 0 : &self,
286 0 : ctx: &RequestMonitoring,
287 0 : timeout: Duration,
288 0 : ) -> Result<compute::PostgresConnection, compute::ConnectionError> {
289 0 : self.config
290 0 : .connect(
291 0 : ctx,
292 0 : self.allow_self_signed_compute,
293 0 : self.aux.clone(),
294 0 : timeout,
295 0 : )
296 0 : .await
297 0 : }
298 4 : pub(crate) fn reuse_settings(&mut self, other: Self) {
299 4 : self.allow_self_signed_compute = other.allow_self_signed_compute;
300 4 : self.config.reuse_password(other.config);
301 4 : }
302 :
303 6 : pub(crate) fn set_keys(&mut self, keys: &ComputeCredentialKeys) {
304 6 : match keys {
305 : #[cfg(any(test, feature = "testing"))]
306 6 : ComputeCredentialKeys::Password(password) => self.config.password(password),
307 0 : ComputeCredentialKeys::AuthKeys(auth_keys) => self.config.auth_keys(*auth_keys),
308 0 : ComputeCredentialKeys::JwtPayload(_) | ComputeCredentialKeys::None => &mut self.config,
309 : };
310 6 : }
311 : }
312 :
313 : pub(crate) type NodeInfoCache =
314 : TimedLru<EndpointCacheKey, Result<NodeInfo, Box<ControlPlaneError>>>;
315 : pub(crate) type CachedNodeInfo = Cached<&'static NodeInfoCache, NodeInfo>;
316 : pub(crate) type CachedRoleSecret = Cached<&'static ProjectInfoCacheImpl, Option<AuthSecret>>;
317 : pub(crate) type CachedAllowedIps = Cached<&'static ProjectInfoCacheImpl, Arc<Vec<IpPattern>>>;
318 :
319 : /// This will allocate per each call, but the http requests alone
320 : /// already require a few allocations, so it should be fine.
321 : pub(crate) trait Api {
322 : /// Get the client's auth secret for authentication.
323 : /// Returns option because user not found situation is special.
324 : /// We still have to mock the scram to avoid leaking information that user doesn't exist.
325 : async fn get_role_secret(
326 : &self,
327 : ctx: &RequestMonitoring,
328 : user_info: &ComputeUserInfo,
329 : ) -> Result<CachedRoleSecret, errors::GetAuthInfoError>;
330 :
331 : async fn get_allowed_ips_and_secret(
332 : &self,
333 : ctx: &RequestMonitoring,
334 : user_info: &ComputeUserInfo,
335 : ) -> Result<(CachedAllowedIps, Option<CachedRoleSecret>), errors::GetAuthInfoError>;
336 :
337 : async fn get_endpoint_jwks(
338 : &self,
339 : ctx: &RequestMonitoring,
340 : endpoint: EndpointId,
341 : ) -> Result<Vec<AuthRule>, errors::GetEndpointJwksError>;
342 :
343 : /// Wake up the compute node and return the corresponding connection info.
344 : async fn wake_compute(
345 : &self,
346 : ctx: &RequestMonitoring,
347 : user_info: &ComputeUserInfo,
348 : ) -> Result<CachedNodeInfo, errors::WakeComputeError>;
349 : }
350 :
351 : #[non_exhaustive]
352 : #[derive(Clone)]
353 : pub enum ControlPlaneBackend {
354 : /// Current Management API (V2).
355 : Management(neon::Api),
356 : /// Local mock control plane.
357 : #[cfg(any(test, feature = "testing"))]
358 : PostgresMock(mock::Api),
359 : /// Internal testing
360 : #[cfg(test)]
361 : #[allow(private_interfaces)]
362 : Test(Box<dyn crate::auth::backend::TestBackend>),
363 : }
364 :
365 : impl Api for ControlPlaneBackend {
366 0 : async fn get_role_secret(
367 0 : &self,
368 0 : ctx: &RequestMonitoring,
369 0 : user_info: &ComputeUserInfo,
370 0 : ) -> Result<CachedRoleSecret, errors::GetAuthInfoError> {
371 0 : match self {
372 0 : Self::Management(api) => api.get_role_secret(ctx, user_info).await,
373 : #[cfg(any(test, feature = "testing"))]
374 0 : Self::PostgresMock(api) => api.get_role_secret(ctx, user_info).await,
375 : #[cfg(test)]
376 : Self::Test(_) => {
377 0 : unreachable!("this function should never be called in the test backend")
378 : }
379 : }
380 0 : }
381 :
382 0 : async fn get_allowed_ips_and_secret(
383 0 : &self,
384 0 : ctx: &RequestMonitoring,
385 0 : user_info: &ComputeUserInfo,
386 0 : ) -> Result<(CachedAllowedIps, Option<CachedRoleSecret>), errors::GetAuthInfoError> {
387 0 : match self {
388 0 : Self::Management(api) => api.get_allowed_ips_and_secret(ctx, user_info).await,
389 : #[cfg(any(test, feature = "testing"))]
390 0 : Self::PostgresMock(api) => api.get_allowed_ips_and_secret(ctx, user_info).await,
391 : #[cfg(test)]
392 0 : Self::Test(api) => api.get_allowed_ips_and_secret(),
393 : }
394 0 : }
395 :
396 0 : async fn get_endpoint_jwks(
397 0 : &self,
398 0 : ctx: &RequestMonitoring,
399 0 : endpoint: EndpointId,
400 0 : ) -> Result<Vec<AuthRule>, errors::GetEndpointJwksError> {
401 0 : match self {
402 0 : Self::Management(api) => api.get_endpoint_jwks(ctx, endpoint).await,
403 : #[cfg(any(test, feature = "testing"))]
404 0 : Self::PostgresMock(api) => api.get_endpoint_jwks(ctx, endpoint).await,
405 : #[cfg(test)]
406 0 : Self::Test(_api) => Ok(vec![]),
407 : }
408 0 : }
409 :
410 13 : async fn wake_compute(
411 13 : &self,
412 13 : ctx: &RequestMonitoring,
413 13 : user_info: &ComputeUserInfo,
414 13 : ) -> Result<CachedNodeInfo, errors::WakeComputeError> {
415 13 : match self {
416 0 : Self::Management(api) => api.wake_compute(ctx, user_info).await,
417 : #[cfg(any(test, feature = "testing"))]
418 0 : Self::PostgresMock(api) => api.wake_compute(ctx, user_info).await,
419 : #[cfg(test)]
420 13 : Self::Test(api) => api.wake_compute(),
421 : }
422 13 : }
423 : }
424 :
425 : /// Various caches for [`control_plane`](super).
426 : pub struct ApiCaches {
427 : /// Cache for the `wake_compute` API method.
428 : pub(crate) node_info: NodeInfoCache,
429 : /// Cache which stores project_id -> endpoint_ids mapping.
430 : pub project_info: Arc<ProjectInfoCacheImpl>,
431 : /// List of all valid endpoints.
432 : pub endpoints_cache: Arc<EndpointsCache>,
433 : }
434 :
435 : impl ApiCaches {
436 0 : pub fn new(
437 0 : wake_compute_cache_config: CacheOptions,
438 0 : project_info_cache_config: ProjectInfoCacheOptions,
439 0 : endpoint_cache_config: EndpointCacheConfig,
440 0 : ) -> Self {
441 0 : Self {
442 0 : node_info: NodeInfoCache::new(
443 0 : "node_info_cache",
444 0 : wake_compute_cache_config.size,
445 0 : wake_compute_cache_config.ttl,
446 0 : true,
447 0 : ),
448 0 : project_info: Arc::new(ProjectInfoCacheImpl::new(project_info_cache_config)),
449 0 : endpoints_cache: Arc::new(EndpointsCache::new(endpoint_cache_config)),
450 0 : }
451 0 : }
452 : }
453 :
454 : /// Various caches for [`control_plane`](super).
455 : pub struct ApiLocks<K> {
456 : name: &'static str,
457 : node_locks: DashMap<K, Arc<DynamicLimiter>>,
458 : config: RateLimiterConfig,
459 : timeout: Duration,
460 : epoch: std::time::Duration,
461 : metrics: &'static ApiLockMetrics,
462 : }
463 :
464 0 : #[derive(Debug, thiserror::Error)]
465 : pub(crate) enum ApiLockError {
466 : #[error("timeout acquiring resource permit")]
467 : TimeoutError(#[from] tokio::time::error::Elapsed),
468 : }
469 :
470 : impl ReportableError for ApiLockError {
471 0 : fn get_error_kind(&self) -> crate::error::ErrorKind {
472 0 : match self {
473 0 : ApiLockError::TimeoutError(_) => crate::error::ErrorKind::RateLimit,
474 0 : }
475 0 : }
476 : }
477 :
478 : impl<K: Hash + Eq + Clone> ApiLocks<K> {
479 0 : pub fn new(
480 0 : name: &'static str,
481 0 : config: RateLimiterConfig,
482 0 : shards: usize,
483 0 : timeout: Duration,
484 0 : epoch: std::time::Duration,
485 0 : metrics: &'static ApiLockMetrics,
486 0 : ) -> prometheus::Result<Self> {
487 0 : Ok(Self {
488 0 : name,
489 0 : node_locks: DashMap::with_shard_amount(shards),
490 0 : config,
491 0 : timeout,
492 0 : epoch,
493 0 : metrics,
494 0 : })
495 0 : }
496 :
497 0 : pub(crate) async fn get_permit(&self, key: &K) -> Result<WakeComputePermit, ApiLockError> {
498 0 : if self.config.initial_limit == 0 {
499 0 : return Ok(WakeComputePermit {
500 0 : permit: Token::disabled(),
501 0 : });
502 0 : }
503 0 : let now = Instant::now();
504 0 : let semaphore = {
505 : // get fast path
506 0 : if let Some(semaphore) = self.node_locks.get(key) {
507 0 : semaphore.clone()
508 : } else {
509 0 : self.node_locks
510 0 : .entry(key.clone())
511 0 : .or_insert_with(|| {
512 0 : self.metrics.semaphores_registered.inc();
513 0 : DynamicLimiter::new(self.config)
514 0 : })
515 0 : .clone()
516 : }
517 : };
518 0 : let permit = semaphore.acquire_timeout(self.timeout).await;
519 :
520 0 : self.metrics
521 0 : .semaphore_acquire_seconds
522 0 : .observe(now.elapsed().as_secs_f64());
523 0 : info!("acquired permit {:?}", now.elapsed().as_secs_f64());
524 0 : Ok(WakeComputePermit { permit: permit? })
525 0 : }
526 :
527 0 : pub async fn garbage_collect_worker(&self) {
528 0 : if self.config.initial_limit == 0 {
529 0 : return;
530 0 : }
531 0 : let mut interval =
532 0 : tokio::time::interval(self.epoch / (self.node_locks.shards().len()) as u32);
533 : loop {
534 0 : for (i, shard) in self.node_locks.shards().iter().enumerate() {
535 0 : interval.tick().await;
536 : // temporary lock a single shard and then clear any semaphores that aren't currently checked out
537 : // race conditions: if strong_count == 1, there's no way that it can increase while the shard is locked
538 : // therefore releasing it is safe from race conditions
539 0 : info!(
540 : name = self.name,
541 : shard = i,
542 0 : "performing epoch reclamation on api lock"
543 : );
544 0 : let mut lock = shard.write();
545 0 : let timer = self.metrics.reclamation_lag_seconds.start_timer();
546 0 : let count = lock
547 0 : .extract_if(|_, semaphore| Arc::strong_count(semaphore.get_mut()) == 1)
548 0 : .count();
549 0 : drop(lock);
550 0 : self.metrics.semaphores_unregistered.inc_by(count as u64);
551 0 : timer.observe();
552 0 : }
553 : }
554 0 : }
555 : }
556 :
557 : pub(crate) struct WakeComputePermit {
558 : permit: Token,
559 : }
560 :
561 : impl WakeComputePermit {
562 0 : pub(crate) fn should_check_cache(&self) -> bool {
563 0 : !self.permit.is_disabled()
564 0 : }
565 0 : pub(crate) fn release(self, outcome: Outcome) {
566 0 : self.permit.release(outcome);
567 0 : }
568 0 : pub(crate) fn release_result<T, E>(self, res: Result<T, E>) -> Result<T, E> {
569 0 : match res {
570 0 : Ok(_) => self.release(Outcome::Success),
571 0 : Err(_) => self.release(Outcome::Overload),
572 : }
573 0 : res
574 0 : }
575 : }
576 :
577 : impl FetchAuthRules for ControlPlaneBackend {
578 0 : async fn fetch_auth_rules(
579 0 : &self,
580 0 : ctx: &RequestMonitoring,
581 0 : endpoint: EndpointId,
582 0 : ) -> Result<Vec<AuthRule>, FetchAuthRulesError> {
583 0 : self.get_endpoint_jwks(ctx, endpoint)
584 0 : .await
585 0 : .map_err(FetchAuthRulesError::GetEndpointJwks)
586 0 : }
587 : }
|