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