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 : };
254 0 :
255 0 : Ok(node)
256 0 : }
257 0 : .inspect_err(|e| tracing::debug!(error = ?e))
258 0 : .instrument(info_span!("do_wake_compute"))
259 0 : .await
260 0 : }
261 : }
262 :
263 : impl super::ControlPlaneApi for NeonControlPlaneClient {
264 0 : #[tracing::instrument(skip_all)]
265 : async fn get_role_secret(
266 : &self,
267 : ctx: &RequestContext,
268 : user_info: &ComputeUserInfo,
269 : ) -> Result<CachedRoleSecret, GetAuthInfoError> {
270 : let normalized_ep = &user_info.endpoint.normalize();
271 : let user = &user_info.user;
272 : if let Some(role_secret) = self
273 : .caches
274 : .project_info
275 : .get_role_secret(normalized_ep, user)
276 : {
277 : return Ok(role_secret);
278 : }
279 : let auth_info = self.do_get_auth_info(ctx, user_info).await?;
280 : if let Some(project_id) = auth_info.project_id {
281 : let normalized_ep_int = normalized_ep.into();
282 : self.caches.project_info.insert_role_secret(
283 : project_id,
284 : normalized_ep_int,
285 : user.into(),
286 : auth_info.secret.clone(),
287 : );
288 : self.caches.project_info.insert_allowed_ips(
289 : project_id,
290 : normalized_ep_int,
291 : Arc::new(auth_info.allowed_ips),
292 : );
293 : ctx.set_project_id(project_id);
294 : }
295 : // When we just got a secret, we don't need to invalidate it.
296 : Ok(Cached::new_uncached(auth_info.secret))
297 : }
298 :
299 0 : async fn get_allowed_ips_and_secret(
300 0 : &self,
301 0 : ctx: &RequestContext,
302 0 : user_info: &ComputeUserInfo,
303 0 : ) -> Result<(CachedAllowedIps, Option<CachedRoleSecret>), GetAuthInfoError> {
304 0 : let normalized_ep = &user_info.endpoint.normalize();
305 0 : if let Some(allowed_ips) = self.caches.project_info.get_allowed_ips(normalized_ep) {
306 0 : Metrics::get()
307 0 : .proxy
308 0 : .allowed_ips_cache_misses
309 0 : .inc(CacheOutcome::Hit);
310 0 : return Ok((allowed_ips, None));
311 0 : }
312 0 : Metrics::get()
313 0 : .proxy
314 0 : .allowed_ips_cache_misses
315 0 : .inc(CacheOutcome::Miss);
316 0 : let auth_info = self.do_get_auth_info(ctx, user_info).await?;
317 0 : let allowed_ips = Arc::new(auth_info.allowed_ips);
318 0 : let user = &user_info.user;
319 0 : if let Some(project_id) = auth_info.project_id {
320 0 : let normalized_ep_int = normalized_ep.into();
321 0 : self.caches.project_info.insert_role_secret(
322 0 : project_id,
323 0 : normalized_ep_int,
324 0 : user.into(),
325 0 : auth_info.secret.clone(),
326 0 : );
327 0 : self.caches.project_info.insert_allowed_ips(
328 0 : project_id,
329 0 : normalized_ep_int,
330 0 : allowed_ips.clone(),
331 0 : );
332 0 : ctx.set_project_id(project_id);
333 0 : }
334 0 : Ok((
335 0 : Cached::new_uncached(allowed_ips),
336 0 : Some(Cached::new_uncached(auth_info.secret)),
337 0 : ))
338 0 : }
339 :
340 0 : #[tracing::instrument(skip_all)]
341 : async fn get_endpoint_jwks(
342 : &self,
343 : ctx: &RequestContext,
344 : endpoint: EndpointId,
345 : ) -> Result<Vec<AuthRule>, GetEndpointJwksError> {
346 : self.do_get_endpoint_jwks(ctx, endpoint).await
347 : }
348 :
349 0 : #[tracing::instrument(skip_all)]
350 : async fn wake_compute(
351 : &self,
352 : ctx: &RequestContext,
353 : user_info: &ComputeUserInfo,
354 : ) -> Result<CachedNodeInfo, WakeComputeError> {
355 : let key = user_info.endpoint_cache_key();
356 :
357 : macro_rules! check_cache {
358 : () => {
359 : if let Some(cached) = self.caches.node_info.get(&key) {
360 : let (cached, info) = cached.take_value();
361 0 : let info = info.map_err(|c| {
362 0 : info!(key = &*key, "found cached wake_compute error");
363 0 : WakeComputeError::ControlPlane(ControlPlaneError::Message(Box::new(*c)))
364 0 : })?;
365 :
366 : debug!(key = &*key, "found cached compute node info");
367 : ctx.set_project(info.aux.clone());
368 0 : return Ok(cached.map(|()| info));
369 : }
370 : };
371 : }
372 :
373 : // Every time we do a wakeup http request, the compute node will stay up
374 : // for some time (highly depends on the console's scale-to-zero policy);
375 : // The connection info remains the same during that period of time,
376 : // which means that we might cache it to reduce the load and latency.
377 : check_cache!();
378 :
379 : let permit = self.locks.get_permit(&key).await?;
380 :
381 : // after getting back a permit - it's possible the cache was filled
382 : // double check
383 : if permit.should_check_cache() {
384 : // TODO: if there is something in the cache, mark the permit as success.
385 : check_cache!();
386 : }
387 :
388 : // check rate limit
389 : if !self
390 : .wake_compute_endpoint_rate_limiter
391 : .check(user_info.endpoint.normalize_intern(), 1)
392 : {
393 : return Err(WakeComputeError::TooManyConnections);
394 : }
395 :
396 : let node = permit.release_result(self.do_wake_compute(ctx, user_info).await);
397 : match node {
398 : Ok(node) => {
399 : ctx.set_project(node.aux.clone());
400 : debug!(key = &*key, "created a cache entry for woken compute node");
401 :
402 : let mut stored_node = node.clone();
403 : // store the cached node as 'warm_cached'
404 : stored_node.aux.cold_start_info = ColdStartInfo::WarmCached;
405 :
406 : let (_, cached) = self.caches.node_info.insert_unit(key, Ok(stored_node));
407 :
408 0 : Ok(cached.map(|()| node))
409 : }
410 : Err(err) => match err {
411 : WakeComputeError::ControlPlane(ControlPlaneError::Message(err)) => {
412 : let Some(status) = &err.status else {
413 : return Err(WakeComputeError::ControlPlane(ControlPlaneError::Message(
414 : err,
415 : )));
416 : };
417 :
418 : let reason = status
419 : .details
420 : .error_info
421 0 : .map_or(Reason::Unknown, |x| x.reason);
422 :
423 : // if we can retry this error, do not cache it.
424 : if reason.can_retry() {
425 : return Err(WakeComputeError::ControlPlane(ControlPlaneError::Message(
426 : err,
427 : )));
428 : }
429 :
430 : // at this point, we should only have quota errors.
431 : debug!(
432 : key = &*key,
433 : "created a cache entry for the wake compute error"
434 : );
435 :
436 : self.caches.node_info.insert_ttl(
437 : key,
438 : Err(err.clone()),
439 : Duration::from_secs(30),
440 : );
441 :
442 : Err(WakeComputeError::ControlPlane(ControlPlaneError::Message(
443 : err,
444 : )))
445 : }
446 : err => return Err(err),
447 : },
448 : }
449 : }
450 : }
451 :
452 : /// Parse http response body, taking status code into account.
453 0 : async fn parse_body<T: for<'a> serde::Deserialize<'a>>(
454 0 : response: http::Response,
455 0 : ) -> Result<T, ControlPlaneError> {
456 0 : let status = response.status();
457 0 : if status.is_success() {
458 : // We shouldn't log raw body because it may contain secrets.
459 0 : info!("request succeeded, processing the body");
460 0 : return Ok(response.json().await?);
461 0 : }
462 0 : let s = response.bytes().await?;
463 : // Log plaintext to be able to detect, whether there are some cases not covered by the error struct.
464 0 : info!("response_error plaintext: {:?}", s);
465 :
466 : // Don't throw an error here because it's not as important
467 : // as the fact that the request itself has failed.
468 0 : let mut body = serde_json::from_slice(&s).unwrap_or_else(|e| {
469 0 : warn!("failed to parse error body: {e}");
470 0 : ControlPlaneErrorMessage {
471 0 : error: "reason unclear (malformed error message)".into(),
472 0 : http_status_code: status,
473 0 : status: None,
474 0 : }
475 0 : });
476 0 : body.http_status_code = status;
477 0 :
478 0 : warn!("console responded with an error ({status}): {body:?}");
479 0 : Err(ControlPlaneError::Message(Box::new(body)))
480 0 : }
481 :
482 3 : fn parse_host_port(input: &str) -> Option<(&str, u16)> {
483 3 : let (host, port) = input.rsplit_once(':')?;
484 3 : let ipv6_brackets: &[_] = &['[', ']'];
485 3 : Some((host.trim_matches(ipv6_brackets), port.parse().ok()?))
486 3 : }
487 :
488 : #[cfg(test)]
489 : mod tests {
490 : use super::*;
491 :
492 : #[test]
493 1 : fn test_parse_host_port_v4() {
494 1 : let (host, port) = parse_host_port("127.0.0.1:5432").expect("failed to parse");
495 1 : assert_eq!(host, "127.0.0.1");
496 1 : assert_eq!(port, 5432);
497 1 : }
498 :
499 : #[test]
500 1 : fn test_parse_host_port_v6() {
501 1 : let (host, port) = parse_host_port("[2001:db8::1]:5432").expect("failed to parse");
502 1 : assert_eq!(host, "2001:db8::1");
503 1 : assert_eq!(port, 5432);
504 1 : }
505 :
506 : #[test]
507 1 : fn test_parse_host_port_url() {
508 1 : let (host, port) = parse_host_port("compute-foo-bar-1234.default.svc.cluster.local:5432")
509 1 : .expect("failed to parse");
510 1 : assert_eq!(host, "compute-foo-bar-1234.default.svc.cluster.local");
511 1 : assert_eq!(port, 5432);
512 1 : }
513 : }
|