Line data Source code
1 : use std::pin::pin;
2 : use std::sync::Arc;
3 :
4 : use bytes::Bytes;
5 : use futures::future::{select, try_join, Either};
6 : use futures::{StreamExt, TryFutureExt};
7 : use http::header::AUTHORIZATION;
8 : use http::Method;
9 : use http_body_util::combinators::BoxBody;
10 : use http_body_util::{BodyExt, Full};
11 : use hyper::body::{Body, Incoming};
12 : use hyper::http::{HeaderName, HeaderValue};
13 : use hyper::{header, HeaderMap, Request, Response, StatusCode};
14 : use pq_proto::StartupMessageParamsBuilder;
15 : use serde::Serialize;
16 : use serde_json::Value;
17 : use tokio::time;
18 : use tokio_postgres::error::{DbError, ErrorPosition, SqlState};
19 : use tokio_postgres::{GenericClient, IsolationLevel, NoTls, ReadyForQueryStatus, Transaction};
20 : use tokio_util::sync::CancellationToken;
21 : use tracing::{error, info};
22 : use typed_json::json;
23 : use url::Url;
24 : use urlencoding;
25 : use utils::http::error::ApiError;
26 : use uuid::Uuid;
27 :
28 : use super::backend::{LocalProxyConnError, PoolingBackend};
29 : use super::conn_pool::{AuthData, ConnInfoWithAuth};
30 : use super::conn_pool_lib::{self, ConnInfo};
31 : use super::error::HttpCodeError;
32 : use super::http_util::json_response;
33 : use super::json::{json_to_pg_text, pg_text_row_to_json, JsonConversionError};
34 : use crate::auth::backend::{ComputeCredentialKeys, ComputeUserInfo};
35 : use crate::auth::{endpoint_sni, ComputeUserInfoParseError};
36 : use crate::config::{AuthenticationConfig, HttpConfig, ProxyConfig, TlsConfig};
37 : use crate::context::RequestMonitoring;
38 : use crate::error::{ErrorKind, ReportableError, UserFacingError};
39 : use crate::metrics::{HttpDirection, Metrics};
40 : use crate::proxy::{run_until_cancelled, NeonOptions};
41 : use crate::serverless::backend::HttpConnError;
42 : use crate::types::{DbName, RoleName};
43 : use crate::usage_metrics::{MetricCounter, MetricCounterRecorder};
44 :
45 0 : #[derive(serde::Deserialize)]
46 : #[serde(rename_all = "camelCase")]
47 : struct QueryData {
48 : query: String,
49 : #[serde(deserialize_with = "bytes_to_pg_text")]
50 : params: Vec<Option<String>>,
51 : #[serde(default)]
52 : array_mode: Option<bool>,
53 : }
54 :
55 0 : #[derive(serde::Deserialize)]
56 : struct BatchQueryData {
57 : queries: Vec<QueryData>,
58 : }
59 :
60 : #[derive(serde::Deserialize)]
61 : #[serde(untagged)]
62 : enum Payload {
63 : Single(QueryData),
64 : Batch(BatchQueryData),
65 : }
66 :
67 : pub(super) static NEON_REQUEST_ID: HeaderName = HeaderName::from_static("neon-request-id");
68 :
69 : static CONN_STRING: HeaderName = HeaderName::from_static("neon-connection-string");
70 : static RAW_TEXT_OUTPUT: HeaderName = HeaderName::from_static("neon-raw-text-output");
71 : static ARRAY_MODE: HeaderName = HeaderName::from_static("neon-array-mode");
72 : static ALLOW_POOL: HeaderName = HeaderName::from_static("neon-pool-opt-in");
73 : static TXN_ISOLATION_LEVEL: HeaderName = HeaderName::from_static("neon-batch-isolation-level");
74 : static TXN_READ_ONLY: HeaderName = HeaderName::from_static("neon-batch-read-only");
75 : static TXN_DEFERRABLE: HeaderName = HeaderName::from_static("neon-batch-deferrable");
76 :
77 : static HEADER_VALUE_TRUE: HeaderValue = HeaderValue::from_static("true");
78 :
79 0 : fn bytes_to_pg_text<'de, D>(deserializer: D) -> Result<Vec<Option<String>>, D::Error>
80 0 : where
81 0 : D: serde::de::Deserializer<'de>,
82 0 : {
83 : // TODO: consider avoiding the allocation here.
84 0 : let json: Vec<Value> = serde::de::Deserialize::deserialize(deserializer)?;
85 0 : Ok(json_to_pg_text(json))
86 0 : }
87 :
88 0 : #[derive(Debug, thiserror::Error)]
89 : pub(crate) enum ConnInfoError {
90 : #[error("invalid header: {0}")]
91 : InvalidHeader(&'static HeaderName),
92 : #[error("invalid connection string: {0}")]
93 : UrlParseError(#[from] url::ParseError),
94 : #[error("incorrect scheme")]
95 : IncorrectScheme,
96 : #[error("missing database name")]
97 : MissingDbName,
98 : #[error("invalid database name")]
99 : InvalidDbName,
100 : #[error("missing username")]
101 : MissingUsername,
102 : #[error("invalid username: {0}")]
103 : InvalidUsername(#[from] std::string::FromUtf8Error),
104 : #[error("missing authentication credentials: {0}")]
105 : MissingCredentials(Credentials),
106 : #[error("missing hostname")]
107 : MissingHostname,
108 : #[error("invalid hostname: {0}")]
109 : InvalidEndpoint(#[from] ComputeUserInfoParseError),
110 : #[error("malformed endpoint")]
111 : MalformedEndpoint,
112 : }
113 :
114 0 : #[derive(Debug, thiserror::Error)]
115 : pub(crate) enum Credentials {
116 : #[error("required password")]
117 : Password,
118 : #[error("required authorization bearer token in JWT format")]
119 : BearerJwt,
120 : }
121 :
122 : impl ReportableError for ConnInfoError {
123 0 : fn get_error_kind(&self) -> ErrorKind {
124 0 : ErrorKind::User
125 0 : }
126 : }
127 :
128 : impl UserFacingError for ConnInfoError {
129 0 : fn to_string_client(&self) -> String {
130 0 : self.to_string()
131 0 : }
132 : }
133 :
134 0 : fn get_conn_info(
135 0 : config: &'static AuthenticationConfig,
136 0 : ctx: &RequestMonitoring,
137 0 : headers: &HeaderMap,
138 0 : tls: Option<&TlsConfig>,
139 0 : ) -> Result<ConnInfoWithAuth, ConnInfoError> {
140 0 : // HTTP only uses cleartext (for now and likely always)
141 0 : ctx.set_auth_method(crate::context::AuthMethod::Cleartext);
142 :
143 0 : let connection_string = headers
144 0 : .get(&CONN_STRING)
145 0 : .ok_or(ConnInfoError::InvalidHeader(&CONN_STRING))?
146 0 : .to_str()
147 0 : .map_err(|_| ConnInfoError::InvalidHeader(&CONN_STRING))?;
148 :
149 0 : let connection_url = Url::parse(connection_string)?;
150 :
151 0 : let protocol = connection_url.scheme();
152 0 : if protocol != "postgres" && protocol != "postgresql" {
153 0 : return Err(ConnInfoError::IncorrectScheme);
154 0 : }
155 :
156 0 : let mut url_path = connection_url
157 0 : .path_segments()
158 0 : .ok_or(ConnInfoError::MissingDbName)?;
159 :
160 0 : let dbname: DbName =
161 0 : urlencoding::decode(url_path.next().ok_or(ConnInfoError::InvalidDbName)?)?.into();
162 0 : ctx.set_dbname(dbname.clone());
163 :
164 0 : let username = RoleName::from(urlencoding::decode(connection_url.username())?);
165 0 : if username.is_empty() {
166 0 : return Err(ConnInfoError::MissingUsername);
167 0 : }
168 0 : ctx.set_user(username.clone());
169 :
170 0 : let auth = if let Some(auth) = headers.get(&AUTHORIZATION) {
171 0 : if !config.accept_jwts {
172 0 : return Err(ConnInfoError::MissingCredentials(Credentials::Password));
173 0 : }
174 :
175 0 : let auth = auth
176 0 : .to_str()
177 0 : .map_err(|_| ConnInfoError::InvalidHeader(&AUTHORIZATION))?;
178 : AuthData::Jwt(
179 0 : auth.strip_prefix("Bearer ")
180 0 : .ok_or(ConnInfoError::MissingCredentials(Credentials::BearerJwt))?
181 0 : .into(),
182 : )
183 0 : } else if let Some(pass) = connection_url.password() {
184 : // wrong credentials provided
185 0 : if config.accept_jwts {
186 0 : return Err(ConnInfoError::MissingCredentials(Credentials::BearerJwt));
187 0 : }
188 0 :
189 0 : AuthData::Password(match urlencoding::decode_binary(pass.as_bytes()) {
190 0 : std::borrow::Cow::Borrowed(b) => b.into(),
191 0 : std::borrow::Cow::Owned(b) => b.into(),
192 : })
193 0 : } else if config.accept_jwts {
194 0 : return Err(ConnInfoError::MissingCredentials(Credentials::BearerJwt));
195 : } else {
196 0 : return Err(ConnInfoError::MissingCredentials(Credentials::Password));
197 : };
198 :
199 0 : let endpoint = match connection_url.host() {
200 0 : Some(url::Host::Domain(hostname)) => {
201 0 : if let Some(tls) = tls {
202 0 : endpoint_sni(hostname, &tls.common_names)?
203 0 : .ok_or(ConnInfoError::MalformedEndpoint)?
204 : } else {
205 0 : hostname
206 0 : .split_once('.')
207 0 : .map_or(hostname, |(prefix, _)| prefix)
208 0 : .into()
209 : }
210 : }
211 : Some(url::Host::Ipv4(_) | url::Host::Ipv6(_)) | None => {
212 0 : return Err(ConnInfoError::MissingHostname)
213 : }
214 : };
215 0 : ctx.set_endpoint_id(endpoint.clone());
216 0 :
217 0 : let pairs = connection_url.query_pairs();
218 0 :
219 0 : let mut options = Option::None;
220 0 :
221 0 : let mut params = StartupMessageParamsBuilder::default();
222 0 : params.insert("user", &username);
223 0 : params.insert("database", &dbname);
224 0 : for (key, value) in pairs {
225 0 : params.insert(&key, &value);
226 0 : if key == "options" {
227 0 : options = Some(NeonOptions::parse_options_raw(&value));
228 0 : }
229 : }
230 :
231 0 : let user_info = ComputeUserInfo {
232 0 : endpoint,
233 0 : user: username,
234 0 : options: options.unwrap_or_default(),
235 0 : };
236 0 :
237 0 : let conn_info = ConnInfo { user_info, dbname };
238 0 : Ok(ConnInfoWithAuth { conn_info, auth })
239 0 : }
240 :
241 0 : pub(crate) async fn handle(
242 0 : config: &'static ProxyConfig,
243 0 : ctx: RequestMonitoring,
244 0 : request: Request<Incoming>,
245 0 : backend: Arc<PoolingBackend>,
246 0 : cancel: CancellationToken,
247 0 : ) -> Result<Response<BoxBody<Bytes, hyper::Error>>, ApiError> {
248 0 : let result = handle_inner(cancel, config, &ctx, request, backend).await;
249 :
250 0 : let mut response = match result {
251 0 : Ok(r) => {
252 0 : ctx.set_success();
253 0 : r
254 : }
255 0 : Err(e @ SqlOverHttpError::Cancelled(_)) => {
256 0 : let error_kind = e.get_error_kind();
257 0 : ctx.set_error_kind(error_kind);
258 0 :
259 0 : let message = "Query cancelled, connection was terminated";
260 0 :
261 0 : tracing::info!(
262 0 : kind=error_kind.to_metric_label(),
263 0 : error=%e,
264 0 : msg=message,
265 0 : "forwarding error to user"
266 : );
267 :
268 0 : json_response(
269 0 : StatusCode::BAD_REQUEST,
270 0 : json!({ "message": message, "code": SqlState::PROTOCOL_VIOLATION.code() }),
271 0 : )?
272 : }
273 0 : Err(e) => {
274 0 : let error_kind = e.get_error_kind();
275 0 : ctx.set_error_kind(error_kind);
276 0 :
277 0 : let mut message = e.to_string_client();
278 0 : let db_error = match &e {
279 0 : SqlOverHttpError::ConnectCompute(HttpConnError::PostgresConnectionError(e))
280 0 : | SqlOverHttpError::Postgres(e) => e.as_db_error(),
281 0 : _ => None,
282 : };
283 0 : fn get<'a, T: Default>(db: Option<&'a DbError>, x: impl FnOnce(&'a DbError) -> T) -> T {
284 0 : db.map(x).unwrap_or_default()
285 0 : }
286 :
287 0 : if let Some(db_error) = db_error {
288 0 : db_error.message().clone_into(&mut message);
289 0 : }
290 :
291 0 : let position = db_error.and_then(|db| db.position());
292 0 : let (position, internal_position, internal_query) = match position {
293 0 : Some(ErrorPosition::Original(position)) => (Some(position.to_string()), None, None),
294 0 : Some(ErrorPosition::Internal { position, query }) => {
295 0 : (None, Some(position.to_string()), Some(query.clone()))
296 : }
297 0 : None => (None, None, None),
298 : };
299 :
300 0 : let code = get(db_error, |db| db.code().code());
301 0 : let severity = get(db_error, |db| db.severity());
302 0 : let detail = get(db_error, |db| db.detail());
303 0 : let hint = get(db_error, |db| db.hint());
304 0 : let where_ = get(db_error, |db| db.where_());
305 0 : let table = get(db_error, |db| db.table());
306 0 : let column = get(db_error, |db| db.column());
307 0 : let schema = get(db_error, |db| db.schema());
308 0 : let datatype = get(db_error, |db| db.datatype());
309 0 : let constraint = get(db_error, |db| db.constraint());
310 0 : let file = get(db_error, |db| db.file());
311 0 : let line = get(db_error, |db| db.line().map(|l| l.to_string()));
312 0 : let routine = get(db_error, |db| db.routine());
313 0 :
314 0 : tracing::info!(
315 0 : kind=error_kind.to_metric_label(),
316 0 : error=%e,
317 0 : msg=message,
318 0 : "forwarding error to user"
319 : );
320 :
321 0 : json_response(
322 0 : e.get_http_status_code(),
323 0 : json!({
324 0 : "message": message,
325 0 : "code": code,
326 0 : "detail": detail,
327 0 : "hint": hint,
328 0 : "position": position,
329 0 : "internalPosition": internal_position,
330 0 : "internalQuery": internal_query,
331 0 : "severity": severity,
332 0 : "where": where_,
333 0 : "table": table,
334 0 : "column": column,
335 0 : "schema": schema,
336 0 : "dataType": datatype,
337 0 : "constraint": constraint,
338 0 : "file": file,
339 0 : "line": line,
340 0 : "routine": routine,
341 0 : }),
342 0 : )?
343 : }
344 : };
345 :
346 0 : response
347 0 : .headers_mut()
348 0 : .insert("Access-Control-Allow-Origin", HeaderValue::from_static("*"));
349 0 : Ok(response)
350 0 : }
351 :
352 0 : #[derive(Debug, thiserror::Error)]
353 : pub(crate) enum SqlOverHttpError {
354 : #[error("{0}")]
355 : ReadPayload(#[from] ReadPayloadError),
356 : #[error("{0}")]
357 : ConnectCompute(#[from] HttpConnError),
358 : #[error("{0}")]
359 : ConnInfo(#[from] ConnInfoError),
360 : #[error("request is too large (max is {0} bytes)")]
361 : RequestTooLarge(u64),
362 : #[error("response is too large (max is {0} bytes)")]
363 : ResponseTooLarge(usize),
364 : #[error("invalid isolation level")]
365 : InvalidIsolationLevel,
366 : #[error("{0}")]
367 : Postgres(#[from] tokio_postgres::Error),
368 : #[error("{0}")]
369 : JsonConversion(#[from] JsonConversionError),
370 : #[error("{0}")]
371 : Cancelled(SqlOverHttpCancel),
372 : }
373 :
374 : impl ReportableError for SqlOverHttpError {
375 0 : fn get_error_kind(&self) -> ErrorKind {
376 0 : match self {
377 0 : SqlOverHttpError::ReadPayload(e) => e.get_error_kind(),
378 0 : SqlOverHttpError::ConnectCompute(e) => e.get_error_kind(),
379 0 : SqlOverHttpError::ConnInfo(e) => e.get_error_kind(),
380 0 : SqlOverHttpError::RequestTooLarge(_) => ErrorKind::User,
381 0 : SqlOverHttpError::ResponseTooLarge(_) => ErrorKind::User,
382 0 : SqlOverHttpError::InvalidIsolationLevel => ErrorKind::User,
383 0 : SqlOverHttpError::Postgres(p) => p.get_error_kind(),
384 0 : SqlOverHttpError::JsonConversion(_) => ErrorKind::Postgres,
385 0 : SqlOverHttpError::Cancelled(c) => c.get_error_kind(),
386 : }
387 0 : }
388 : }
389 :
390 : impl UserFacingError for SqlOverHttpError {
391 0 : fn to_string_client(&self) -> String {
392 0 : match self {
393 0 : SqlOverHttpError::ReadPayload(p) => p.to_string(),
394 0 : SqlOverHttpError::ConnectCompute(c) => c.to_string_client(),
395 0 : SqlOverHttpError::ConnInfo(c) => c.to_string_client(),
396 0 : SqlOverHttpError::RequestTooLarge(_) => self.to_string(),
397 0 : SqlOverHttpError::ResponseTooLarge(_) => self.to_string(),
398 0 : SqlOverHttpError::InvalidIsolationLevel => self.to_string(),
399 0 : SqlOverHttpError::Postgres(p) => p.to_string(),
400 0 : SqlOverHttpError::JsonConversion(_) => "could not parse postgres response".to_string(),
401 0 : SqlOverHttpError::Cancelled(_) => self.to_string(),
402 : }
403 0 : }
404 : }
405 :
406 : impl HttpCodeError for SqlOverHttpError {
407 0 : fn get_http_status_code(&self) -> StatusCode {
408 0 : match self {
409 0 : SqlOverHttpError::ReadPayload(_) => StatusCode::BAD_REQUEST,
410 0 : SqlOverHttpError::ConnectCompute(h) => match h.get_error_kind() {
411 0 : ErrorKind::User => StatusCode::BAD_REQUEST,
412 0 : _ => StatusCode::INTERNAL_SERVER_ERROR,
413 : },
414 0 : SqlOverHttpError::ConnInfo(_) => StatusCode::BAD_REQUEST,
415 0 : SqlOverHttpError::RequestTooLarge(_) => StatusCode::PAYLOAD_TOO_LARGE,
416 0 : SqlOverHttpError::ResponseTooLarge(_) => StatusCode::INSUFFICIENT_STORAGE,
417 0 : SqlOverHttpError::InvalidIsolationLevel => StatusCode::BAD_REQUEST,
418 0 : SqlOverHttpError::Postgres(_) => StatusCode::BAD_REQUEST,
419 0 : SqlOverHttpError::JsonConversion(_) => StatusCode::INTERNAL_SERVER_ERROR,
420 0 : SqlOverHttpError::Cancelled(_) => StatusCode::INTERNAL_SERVER_ERROR,
421 : }
422 0 : }
423 : }
424 :
425 0 : #[derive(Debug, thiserror::Error)]
426 : pub(crate) enum ReadPayloadError {
427 : #[error("could not read the HTTP request body: {0}")]
428 : Read(#[from] hyper::Error),
429 : #[error("could not parse the HTTP request body: {0}")]
430 : Parse(#[from] serde_json::Error),
431 : }
432 :
433 : impl ReportableError for ReadPayloadError {
434 0 : fn get_error_kind(&self) -> ErrorKind {
435 0 : match self {
436 0 : ReadPayloadError::Read(_) => ErrorKind::ClientDisconnect,
437 0 : ReadPayloadError::Parse(_) => ErrorKind::User,
438 : }
439 0 : }
440 : }
441 :
442 0 : #[derive(Debug, thiserror::Error)]
443 : pub(crate) enum SqlOverHttpCancel {
444 : #[error("query was cancelled")]
445 : Postgres,
446 : #[error("query was cancelled while stuck trying to connect to the database")]
447 : Connect,
448 : }
449 :
450 : impl ReportableError for SqlOverHttpCancel {
451 0 : fn get_error_kind(&self) -> ErrorKind {
452 0 : match self {
453 0 : SqlOverHttpCancel::Postgres => ErrorKind::ClientDisconnect,
454 0 : SqlOverHttpCancel::Connect => ErrorKind::ClientDisconnect,
455 : }
456 0 : }
457 : }
458 :
459 : #[derive(Clone, Copy, Debug)]
460 : struct HttpHeaders {
461 : raw_output: bool,
462 : default_array_mode: bool,
463 : txn_isolation_level: Option<IsolationLevel>,
464 : txn_read_only: bool,
465 : txn_deferrable: bool,
466 : }
467 :
468 : impl HttpHeaders {
469 0 : fn try_parse(headers: &hyper::http::HeaderMap) -> Result<Self, SqlOverHttpError> {
470 0 : // Determine the output options. Default behaviour is 'false'. Anything that is not
471 0 : // strictly 'true' assumed to be false.
472 0 : let raw_output = headers.get(&RAW_TEXT_OUTPUT) == Some(&HEADER_VALUE_TRUE);
473 0 : let default_array_mode = headers.get(&ARRAY_MODE) == Some(&HEADER_VALUE_TRUE);
474 :
475 : // isolation level, read only and deferrable
476 0 : let txn_isolation_level = match headers.get(&TXN_ISOLATION_LEVEL) {
477 0 : Some(x) => Some(
478 0 : map_header_to_isolation_level(x).ok_or(SqlOverHttpError::InvalidIsolationLevel)?,
479 : ),
480 0 : None => None,
481 : };
482 :
483 0 : let txn_read_only = headers.get(&TXN_READ_ONLY) == Some(&HEADER_VALUE_TRUE);
484 0 : let txn_deferrable = headers.get(&TXN_DEFERRABLE) == Some(&HEADER_VALUE_TRUE);
485 0 :
486 0 : Ok(Self {
487 0 : raw_output,
488 0 : default_array_mode,
489 0 : txn_isolation_level,
490 0 : txn_read_only,
491 0 : txn_deferrable,
492 0 : })
493 0 : }
494 : }
495 :
496 0 : fn map_header_to_isolation_level(level: &HeaderValue) -> Option<IsolationLevel> {
497 0 : match level.as_bytes() {
498 0 : b"Serializable" => Some(IsolationLevel::Serializable),
499 0 : b"ReadUncommitted" => Some(IsolationLevel::ReadUncommitted),
500 0 : b"ReadCommitted" => Some(IsolationLevel::ReadCommitted),
501 0 : b"RepeatableRead" => Some(IsolationLevel::RepeatableRead),
502 0 : _ => None,
503 : }
504 0 : }
505 :
506 0 : fn map_isolation_level_to_headers(level: IsolationLevel) -> Option<HeaderValue> {
507 0 : match level {
508 0 : IsolationLevel::ReadUncommitted => Some(HeaderValue::from_static("ReadUncommitted")),
509 0 : IsolationLevel::ReadCommitted => Some(HeaderValue::from_static("ReadCommitted")),
510 0 : IsolationLevel::RepeatableRead => Some(HeaderValue::from_static("RepeatableRead")),
511 0 : IsolationLevel::Serializable => Some(HeaderValue::from_static("Serializable")),
512 0 : _ => None,
513 : }
514 0 : }
515 :
516 0 : async fn handle_inner(
517 0 : cancel: CancellationToken,
518 0 : config: &'static ProxyConfig,
519 0 : ctx: &RequestMonitoring,
520 0 : request: Request<Incoming>,
521 0 : backend: Arc<PoolingBackend>,
522 0 : ) -> Result<Response<BoxBody<Bytes, hyper::Error>>, SqlOverHttpError> {
523 0 : let _requeset_gauge = Metrics::get()
524 0 : .proxy
525 0 : .connection_requests
526 0 : .guard(ctx.protocol());
527 0 : info!(
528 0 : protocol = %ctx.protocol(),
529 0 : "handling interactive connection from client"
530 : );
531 :
532 0 : let conn_info = get_conn_info(
533 0 : &config.authentication_config,
534 0 : ctx,
535 0 : request.headers(),
536 0 : config.tls_config.as_ref(),
537 0 : )?;
538 0 : info!(
539 0 : user = conn_info.conn_info.user_info.user.as_str(),
540 0 : "credentials"
541 : );
542 :
543 0 : match conn_info.auth {
544 0 : AuthData::Jwt(jwt) if config.authentication_config.is_auth_broker => {
545 0 : handle_auth_broker_inner(ctx, request, conn_info.conn_info, jwt, backend).await
546 : }
547 0 : auth => {
548 0 : handle_db_inner(
549 0 : cancel,
550 0 : config,
551 0 : ctx,
552 0 : request,
553 0 : conn_info.conn_info,
554 0 : auth,
555 0 : backend,
556 0 : )
557 0 : .await
558 : }
559 : }
560 0 : }
561 :
562 0 : async fn handle_db_inner(
563 0 : cancel: CancellationToken,
564 0 : config: &'static ProxyConfig,
565 0 : ctx: &RequestMonitoring,
566 0 : request: Request<Incoming>,
567 0 : conn_info: ConnInfo,
568 0 : auth: AuthData,
569 0 : backend: Arc<PoolingBackend>,
570 0 : ) -> Result<Response<BoxBody<Bytes, hyper::Error>>, SqlOverHttpError> {
571 0 : //
572 0 : // Determine the destination and connection params
573 0 : //
574 0 : let headers = request.headers();
575 :
576 : // Allow connection pooling only if explicitly requested
577 : // or if we have decided that http pool is no longer opt-in
578 0 : let allow_pool = !config.http_config.pool_options.opt_in
579 0 : || headers.get(&ALLOW_POOL) == Some(&HEADER_VALUE_TRUE);
580 :
581 0 : let parsed_headers = HttpHeaders::try_parse(headers)?;
582 :
583 0 : let request_content_length = match request.body().size_hint().upper() {
584 0 : Some(v) => v,
585 0 : None => config.http_config.max_request_size_bytes + 1,
586 : };
587 0 : info!(request_content_length, "request size in bytes");
588 0 : Metrics::get()
589 0 : .proxy
590 0 : .http_conn_content_length_bytes
591 0 : .observe(HttpDirection::Request, request_content_length as f64);
592 0 :
593 0 : // we don't have a streaming request support yet so this is to prevent OOM
594 0 : // from a malicious user sending an extremely large request body
595 0 : if request_content_length > config.http_config.max_request_size_bytes {
596 0 : return Err(SqlOverHttpError::RequestTooLarge(
597 0 : config.http_config.max_request_size_bytes,
598 0 : ));
599 0 : }
600 0 :
601 0 : let fetch_and_process_request = Box::pin(
602 0 : async {
603 0 : let body = request.into_body().collect().await?.to_bytes();
604 0 : info!(length = body.len(), "request payload read");
605 0 : let payload: Payload = serde_json::from_slice(&body)?;
606 0 : Ok::<Payload, ReadPayloadError>(payload) // Adjust error type accordingly
607 0 : }
608 0 : .map_err(SqlOverHttpError::from),
609 0 : );
610 0 :
611 0 : let authenticate_and_connect = Box::pin(
612 0 : async {
613 0 : let is_local_proxy = matches!(backend.auth_backend, crate::auth::Backend::Local(_));
614 :
615 0 : let keys = match auth {
616 0 : AuthData::Password(pw) => {
617 0 : backend
618 0 : .authenticate_with_password(ctx, &conn_info.user_info, &pw)
619 0 : .await?
620 : }
621 0 : AuthData::Jwt(jwt) => {
622 0 : backend
623 0 : .authenticate_with_jwt(ctx, &conn_info.user_info, jwt)
624 0 : .await?
625 : }
626 : };
627 :
628 0 : let client = match keys.keys {
629 0 : ComputeCredentialKeys::JwtPayload(payload) if is_local_proxy => {
630 0 : let mut client = backend.connect_to_local_postgres(ctx, conn_info).await?;
631 0 : let (cli_inner, _dsc) = client.client_inner();
632 0 : cli_inner.set_jwt_session(&payload).await?;
633 0 : Client::Local(client)
634 : }
635 : _ => {
636 0 : let client = backend
637 0 : .connect_to_compute(ctx, conn_info, keys, !allow_pool)
638 0 : .await?;
639 0 : Client::Remote(client)
640 : }
641 : };
642 :
643 : // not strictly necessary to mark success here,
644 : // but it's just insurance for if we forget it somewhere else
645 0 : ctx.success();
646 0 : Ok::<_, HttpConnError>(client)
647 0 : }
648 0 : .map_err(SqlOverHttpError::from),
649 0 : );
650 :
651 0 : let (payload, mut client) = match run_until_cancelled(
652 0 : // Run both operations in parallel
653 0 : try_join(
654 0 : pin!(fetch_and_process_request),
655 0 : pin!(authenticate_and_connect),
656 0 : ),
657 0 : &cancel,
658 0 : )
659 0 : .await
660 : {
661 0 : Some(result) => result?,
662 0 : None => return Err(SqlOverHttpError::Cancelled(SqlOverHttpCancel::Connect)),
663 : };
664 :
665 0 : let mut response = Response::builder()
666 0 : .status(StatusCode::OK)
667 0 : .header(header::CONTENT_TYPE, "application/json");
668 :
669 : // Now execute the query and return the result.
670 0 : let json_output = match payload {
671 0 : Payload::Single(stmt) => {
672 0 : stmt.process(&config.http_config, cancel, &mut client, parsed_headers)
673 0 : .await?
674 : }
675 0 : Payload::Batch(statements) => {
676 0 : if parsed_headers.txn_read_only {
677 0 : response = response.header(TXN_READ_ONLY.clone(), &HEADER_VALUE_TRUE);
678 0 : }
679 0 : if parsed_headers.txn_deferrable {
680 0 : response = response.header(TXN_DEFERRABLE.clone(), &HEADER_VALUE_TRUE);
681 0 : }
682 0 : if let Some(txn_isolation_level) = parsed_headers
683 0 : .txn_isolation_level
684 0 : .and_then(map_isolation_level_to_headers)
685 0 : {
686 0 : response = response.header(TXN_ISOLATION_LEVEL.clone(), txn_isolation_level);
687 0 : }
688 :
689 0 : statements
690 0 : .process(&config.http_config, cancel, &mut client, parsed_headers)
691 0 : .await?
692 : }
693 : };
694 :
695 0 : let metrics = client.metrics();
696 0 :
697 0 : let len = json_output.len();
698 0 : let response = response
699 0 : .body(
700 0 : Full::new(Bytes::from(json_output))
701 0 : .map_err(|x| match x {})
702 0 : .boxed(),
703 0 : )
704 0 : // only fails if invalid status code or invalid header/values are given.
705 0 : // these are not user configurable so it cannot fail dynamically
706 0 : .expect("building response payload should not fail");
707 0 :
708 0 : // count the egress bytes - we miss the TLS and header overhead but oh well...
709 0 : // moving this later in the stack is going to be a lot of effort and ehhhh
710 0 : metrics.record_egress(len as u64);
711 0 : Metrics::get()
712 0 : .proxy
713 0 : .http_conn_content_length_bytes
714 0 : .observe(HttpDirection::Response, len as f64);
715 0 :
716 0 : Ok(response)
717 0 : }
718 :
719 : static HEADERS_TO_FORWARD: &[&HeaderName] = &[
720 : &AUTHORIZATION,
721 : &CONN_STRING,
722 : &RAW_TEXT_OUTPUT,
723 : &ARRAY_MODE,
724 : &TXN_ISOLATION_LEVEL,
725 : &TXN_READ_ONLY,
726 : &TXN_DEFERRABLE,
727 : ];
728 :
729 0 : pub(crate) fn uuid_to_header_value(id: Uuid) -> HeaderValue {
730 0 : let mut uuid = [0; uuid::fmt::Hyphenated::LENGTH];
731 0 : HeaderValue::from_str(id.as_hyphenated().encode_lower(&mut uuid[..]))
732 0 : .expect("uuid hyphenated format should be all valid header characters")
733 0 : }
734 :
735 0 : async fn handle_auth_broker_inner(
736 0 : ctx: &RequestMonitoring,
737 0 : request: Request<Incoming>,
738 0 : conn_info: ConnInfo,
739 0 : jwt: String,
740 0 : backend: Arc<PoolingBackend>,
741 0 : ) -> Result<Response<BoxBody<Bytes, hyper::Error>>, SqlOverHttpError> {
742 0 : backend
743 0 : .authenticate_with_jwt(ctx, &conn_info.user_info, jwt)
744 0 : .await
745 0 : .map_err(HttpConnError::from)?;
746 :
747 0 : let mut client = backend.connect_to_local_proxy(ctx, conn_info).await?;
748 :
749 0 : let local_proxy_uri = ::http::Uri::from_static("http://proxy.local/sql");
750 0 :
751 0 : let (mut parts, body) = request.into_parts();
752 0 : let mut req = Request::builder().method(Method::POST).uri(local_proxy_uri);
753 :
754 : // todo(conradludgate): maybe auth-broker should parse these and re-serialize
755 : // these instead just to ensure they remain normalised.
756 0 : for &h in HEADERS_TO_FORWARD {
757 0 : if let Some(hv) = parts.headers.remove(h) {
758 0 : req = req.header(h, hv);
759 0 : }
760 : }
761 0 : req = req.header(&NEON_REQUEST_ID, uuid_to_header_value(ctx.session_id()));
762 0 :
763 0 : let req = req
764 0 : .body(body)
765 0 : .expect("all headers and params received via hyper should be valid for request");
766 0 :
767 0 : // todo: map body to count egress
768 0 : let _metrics = client.metrics();
769 0 :
770 0 : Ok(client
771 0 : .inner
772 0 : .send_request(req)
773 0 : .await
774 0 : .map_err(LocalProxyConnError::from)
775 0 : .map_err(HttpConnError::from)?
776 0 : .map(|b| b.boxed()))
777 0 : }
778 :
779 : impl QueryData {
780 0 : async fn process(
781 0 : self,
782 0 : config: &'static HttpConfig,
783 0 : cancel: CancellationToken,
784 0 : client: &mut Client,
785 0 : parsed_headers: HttpHeaders,
786 0 : ) -> Result<String, SqlOverHttpError> {
787 0 : let (inner, mut discard) = client.inner();
788 0 : let cancel_token = inner.cancel_token();
789 :
790 0 : let res = match select(
791 0 : pin!(query_to_json(config, &*inner, self, &mut 0, parsed_headers)),
792 0 : pin!(cancel.cancelled()),
793 0 : )
794 0 : .await
795 : {
796 : // The query successfully completed.
797 0 : Either::Left((Ok((status, results)), __not_yet_cancelled)) => {
798 0 : discard.check_idle(status);
799 0 :
800 0 : let json_output =
801 0 : serde_json::to_string(&results).expect("json serialization should not fail");
802 0 : Ok(json_output)
803 : }
804 : // The query failed with an error
805 0 : Either::Left((Err(e), __not_yet_cancelled)) => {
806 0 : discard.discard();
807 0 : return Err(e);
808 : }
809 : // The query was cancelled.
810 0 : Either::Right((_cancelled, query)) => {
811 0 : tracing::info!("cancelling query");
812 0 : if let Err(err) = cancel_token.cancel_query(NoTls).await {
813 0 : tracing::warn!(?err, "could not cancel query");
814 0 : }
815 : // wait for the query cancellation
816 0 : match time::timeout(time::Duration::from_millis(100), query).await {
817 : // query successed before it was cancelled.
818 0 : Ok(Ok((status, results))) => {
819 0 : discard.check_idle(status);
820 0 :
821 0 : let json_output = serde_json::to_string(&results)
822 0 : .expect("json serialization should not fail");
823 0 : Ok(json_output)
824 : }
825 : // query failed or was cancelled.
826 0 : Ok(Err(error)) => {
827 0 : let db_error = match &error {
828 : SqlOverHttpError::ConnectCompute(
829 0 : HttpConnError::PostgresConnectionError(e),
830 : )
831 0 : | SqlOverHttpError::Postgres(e) => e.as_db_error(),
832 0 : _ => None,
833 : };
834 :
835 : // if errored for some other reason, it might not be safe to return
836 0 : if !db_error.is_some_and(|e| *e.code() == SqlState::QUERY_CANCELED) {
837 0 : discard.discard();
838 0 : }
839 :
840 0 : Err(SqlOverHttpError::Cancelled(SqlOverHttpCancel::Postgres))
841 : }
842 0 : Err(_timeout) => {
843 0 : discard.discard();
844 0 : Err(SqlOverHttpError::Cancelled(SqlOverHttpCancel::Postgres))
845 : }
846 : }
847 : }
848 : };
849 0 : res
850 0 : }
851 : }
852 :
853 : impl BatchQueryData {
854 0 : async fn process(
855 0 : self,
856 0 : config: &'static HttpConfig,
857 0 : cancel: CancellationToken,
858 0 : client: &mut Client,
859 0 : parsed_headers: HttpHeaders,
860 0 : ) -> Result<String, SqlOverHttpError> {
861 0 : info!("starting transaction");
862 0 : let (inner, mut discard) = client.inner();
863 0 : let cancel_token = inner.cancel_token();
864 0 : let mut builder = inner.build_transaction();
865 0 : if let Some(isolation_level) = parsed_headers.txn_isolation_level {
866 0 : builder = builder.isolation_level(isolation_level);
867 0 : }
868 0 : if parsed_headers.txn_read_only {
869 0 : builder = builder.read_only(true);
870 0 : }
871 0 : if parsed_headers.txn_deferrable {
872 0 : builder = builder.deferrable(true);
873 0 : }
874 :
875 0 : let transaction = builder.start().await.inspect_err(|_| {
876 0 : // if we cannot start a transaction, we should return immediately
877 0 : // and not return to the pool. connection is clearly broken
878 0 : discard.discard();
879 0 : })?;
880 :
881 0 : let json_output = match query_batch(
882 0 : config,
883 0 : cancel.child_token(),
884 0 : &transaction,
885 0 : self,
886 0 : parsed_headers,
887 0 : )
888 0 : .await
889 : {
890 0 : Ok(json_output) => {
891 0 : info!("commit");
892 0 : let status = transaction.commit().await.inspect_err(|_| {
893 0 : // if we cannot commit - for now don't return connection to pool
894 0 : // TODO: get a query status from the error
895 0 : discard.discard();
896 0 : })?;
897 0 : discard.check_idle(status);
898 0 : json_output
899 : }
900 : Err(SqlOverHttpError::Cancelled(_)) => {
901 0 : if let Err(err) = cancel_token.cancel_query(NoTls).await {
902 0 : tracing::warn!(?err, "could not cancel query");
903 0 : }
904 : // TODO: after cancelling, wait to see if we can get a status. maybe the connection is still safe.
905 0 : discard.discard();
906 0 :
907 0 : return Err(SqlOverHttpError::Cancelled(SqlOverHttpCancel::Postgres));
908 : }
909 0 : Err(err) => {
910 0 : info!("rollback");
911 0 : let status = transaction.rollback().await.inspect_err(|_| {
912 0 : // if we cannot rollback - for now don't return connection to pool
913 0 : // TODO: get a query status from the error
914 0 : discard.discard();
915 0 : })?;
916 0 : discard.check_idle(status);
917 0 : return Err(err);
918 : }
919 : };
920 :
921 0 : Ok(json_output)
922 0 : }
923 : }
924 :
925 0 : async fn query_batch(
926 0 : config: &'static HttpConfig,
927 0 : cancel: CancellationToken,
928 0 : transaction: &Transaction<'_>,
929 0 : queries: BatchQueryData,
930 0 : parsed_headers: HttpHeaders,
931 0 : ) -> Result<String, SqlOverHttpError> {
932 0 : let mut results = Vec::with_capacity(queries.queries.len());
933 0 : let mut current_size = 0;
934 0 : for stmt in queries.queries {
935 0 : let query = pin!(query_to_json(
936 0 : config,
937 0 : transaction,
938 0 : stmt,
939 0 : &mut current_size,
940 0 : parsed_headers,
941 0 : ));
942 0 : let cancelled = pin!(cancel.cancelled());
943 0 : let res = select(query, cancelled).await;
944 0 : match res {
945 : // TODO: maybe we should check that the transaction bit is set here
946 0 : Either::Left((Ok((_, values)), _cancelled)) => {
947 0 : results.push(values);
948 0 : }
949 0 : Either::Left((Err(e), _cancelled)) => {
950 0 : return Err(e);
951 : }
952 0 : Either::Right((_cancelled, _)) => {
953 0 : return Err(SqlOverHttpError::Cancelled(SqlOverHttpCancel::Postgres));
954 : }
955 : }
956 : }
957 :
958 0 : let results = json!({ "results": results });
959 0 : let json_output = serde_json::to_string(&results).expect("json serialization should not fail");
960 0 :
961 0 : Ok(json_output)
962 0 : }
963 :
964 0 : async fn query_to_json<T: GenericClient>(
965 0 : config: &'static HttpConfig,
966 0 : client: &T,
967 0 : data: QueryData,
968 0 : current_size: &mut usize,
969 0 : parsed_headers: HttpHeaders,
970 0 : ) -> Result<(ReadyForQueryStatus, impl Serialize), SqlOverHttpError> {
971 0 : info!("executing query");
972 0 : let query_params = data.params;
973 0 : let mut row_stream = std::pin::pin!(client.query_raw_txt(&data.query, query_params).await?);
974 0 : info!("finished executing query");
975 :
976 : // Manually drain the stream into a vector to leave row_stream hanging
977 : // around to get a command tag. Also check that the response is not too
978 : // big.
979 0 : let mut rows: Vec<tokio_postgres::Row> = Vec::new();
980 0 : while let Some(row) = row_stream.next().await {
981 0 : let row = row?;
982 0 : *current_size += row.body_len();
983 0 : rows.push(row);
984 0 : // we don't have a streaming response support yet so this is to prevent OOM
985 0 : // from a malicious query (eg a cross join)
986 0 : if *current_size > config.max_response_size_bytes {
987 0 : return Err(SqlOverHttpError::ResponseTooLarge(
988 0 : config.max_response_size_bytes,
989 0 : ));
990 0 : }
991 : }
992 :
993 0 : let ready = row_stream.ready_status();
994 0 :
995 0 : // grab the command tag and number of rows affected
996 0 : let command_tag = row_stream.command_tag().unwrap_or_default();
997 0 : let mut command_tag_split = command_tag.split(' ');
998 0 : let command_tag_name = command_tag_split.next().unwrap_or_default();
999 0 : let command_tag_count = if command_tag_name == "INSERT" {
1000 : // INSERT returns OID first and then number of rows
1001 0 : command_tag_split.nth(1)
1002 : } else {
1003 : // other commands return number of rows (if any)
1004 0 : command_tag_split.next()
1005 : }
1006 0 : .and_then(|s| s.parse::<i64>().ok());
1007 0 :
1008 0 : info!(
1009 0 : rows = rows.len(),
1010 0 : ?ready,
1011 0 : command_tag,
1012 0 : "finished reading rows"
1013 : );
1014 :
1015 0 : let columns_len = row_stream.columns().len();
1016 0 : let mut fields = Vec::with_capacity(columns_len);
1017 0 : let mut columns = Vec::with_capacity(columns_len);
1018 :
1019 0 : for c in row_stream.columns() {
1020 0 : fields.push(json!({
1021 0 : "name": c.name().to_owned(),
1022 0 : "dataTypeID": c.type_().oid(),
1023 0 : "tableID": c.table_oid(),
1024 0 : "columnID": c.column_id(),
1025 0 : "dataTypeSize": c.type_size(),
1026 0 : "dataTypeModifier": c.type_modifier(),
1027 0 : "format": "text",
1028 0 : }));
1029 0 : columns.push(client.get_type(c.type_oid()).await?);
1030 : }
1031 :
1032 0 : let array_mode = data.array_mode.unwrap_or(parsed_headers.default_array_mode);
1033 :
1034 : // convert rows to JSON
1035 0 : let rows = rows
1036 0 : .iter()
1037 0 : .map(|row| pg_text_row_to_json(row, &columns, parsed_headers.raw_output, array_mode))
1038 0 : .collect::<Result<Vec<_>, _>>()?;
1039 :
1040 : // Resulting JSON format is based on the format of node-postgres result.
1041 0 : let results = json!({
1042 0 : "command": command_tag_name.to_string(),
1043 0 : "rowCount": command_tag_count,
1044 0 : "rows": rows,
1045 0 : "fields": fields,
1046 0 : "rowAsArray": array_mode,
1047 0 : });
1048 0 :
1049 0 : Ok((ready, results))
1050 0 : }
1051 :
1052 : enum Client {
1053 : Remote(conn_pool_lib::Client<tokio_postgres::Client>),
1054 : Local(conn_pool_lib::Client<tokio_postgres::Client>),
1055 : }
1056 :
1057 : enum Discard<'a> {
1058 : Remote(conn_pool_lib::Discard<'a, tokio_postgres::Client>),
1059 : Local(conn_pool_lib::Discard<'a, tokio_postgres::Client>),
1060 : }
1061 :
1062 : impl Client {
1063 0 : fn metrics(&self) -> Arc<MetricCounter> {
1064 0 : match self {
1065 0 : Client::Remote(client) => client.metrics(),
1066 0 : Client::Local(local_client) => local_client.metrics(),
1067 : }
1068 0 : }
1069 :
1070 0 : fn inner(&mut self) -> (&mut tokio_postgres::Client, Discard<'_>) {
1071 0 : match self {
1072 0 : Client::Remote(client) => {
1073 0 : let (c, d) = client.inner();
1074 0 : (c, Discard::Remote(d))
1075 : }
1076 0 : Client::Local(local_client) => {
1077 0 : let (c, d) = local_client.inner();
1078 0 : (c, Discard::Local(d))
1079 : }
1080 : }
1081 0 : }
1082 : }
1083 :
1084 : impl Discard<'_> {
1085 0 : fn check_idle(&mut self, status: ReadyForQueryStatus) {
1086 0 : match self {
1087 0 : Discard::Remote(discard) => discard.check_idle(status),
1088 0 : Discard::Local(discard) => discard.check_idle(status),
1089 : }
1090 0 : }
1091 0 : fn discard(&mut self) {
1092 0 : match self {
1093 0 : Discard::Remote(discard) => discard.discard(),
1094 0 : Discard::Local(discard) => discard.discard(),
1095 : }
1096 0 : }
1097 : }
|