Line data Source code
1 : use std::fmt;
2 :
3 : use async_trait::async_trait;
4 : use postgres_client::config::SslMode;
5 : use pq_proto::BeMessage as Be;
6 : use thiserror::Error;
7 : use tokio::io::{AsyncRead, AsyncWrite};
8 : use tracing::{info, info_span};
9 :
10 : use super::ComputeCredentialKeys;
11 : use crate::auth::backend::ComputeUserInfo;
12 : use crate::auth::IpPattern;
13 : use crate::cache::Cached;
14 : use crate::config::AuthenticationConfig;
15 : use crate::context::RequestContext;
16 : use crate::control_plane::client::cplane_proxy_v1;
17 : use crate::control_plane::{self, CachedNodeInfo, NodeInfo};
18 : use crate::error::{ReportableError, UserFacingError};
19 : use crate::proxy::connect_compute::ComputeConnectBackend;
20 : use crate::proxy::NeonOptions;
21 : use crate::stream::PqStream;
22 : use crate::types::RoleName;
23 : use crate::{auth, compute, waiters};
24 :
25 : #[derive(Debug, Error)]
26 : pub(crate) enum ConsoleRedirectError {
27 : #[error(transparent)]
28 : WaiterRegister(#[from] waiters::RegisterError),
29 :
30 : #[error(transparent)]
31 : WaiterWait(#[from] waiters::WaitError),
32 :
33 : #[error(transparent)]
34 : Io(#[from] std::io::Error),
35 : }
36 :
37 : #[derive(Debug)]
38 : pub struct ConsoleRedirectBackend {
39 : console_uri: reqwest::Url,
40 : api: cplane_proxy_v1::NeonControlPlaneClient,
41 : }
42 :
43 : impl fmt::Debug for cplane_proxy_v1::NeonControlPlaneClient {
44 0 : fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
45 0 : write!(f, "NeonControlPlaneClient")
46 0 : }
47 : }
48 :
49 : impl UserFacingError for ConsoleRedirectError {
50 0 : fn to_string_client(&self) -> String {
51 0 : "Internal error".to_string()
52 0 : }
53 : }
54 :
55 : impl ReportableError for ConsoleRedirectError {
56 0 : fn get_error_kind(&self) -> crate::error::ErrorKind {
57 0 : match self {
58 0 : Self::WaiterRegister(_) => crate::error::ErrorKind::Service,
59 0 : Self::WaiterWait(_) => crate::error::ErrorKind::Service,
60 0 : Self::Io(_) => crate::error::ErrorKind::ClientDisconnect,
61 : }
62 0 : }
63 : }
64 :
65 0 : fn hello_message(
66 0 : redirect_uri: &reqwest::Url,
67 0 : session_id: &str,
68 0 : duration: std::time::Duration,
69 0 : ) -> String {
70 0 : let formatted_duration = humantime::format_duration(duration).to_string();
71 0 : format!(
72 0 : concat![
73 0 : "Welcome to Neon!\n",
74 0 : "Authenticate by visiting (will expire in {duration}):\n",
75 0 : " {redirect_uri}{session_id}\n\n",
76 0 : ],
77 0 : duration = formatted_duration,
78 0 : redirect_uri = redirect_uri,
79 0 : session_id = session_id,
80 0 : )
81 0 : }
82 :
83 0 : pub(crate) fn new_psql_session_id() -> String {
84 0 : hex::encode(rand::random::<[u8; 8]>())
85 0 : }
86 :
87 : impl ConsoleRedirectBackend {
88 0 : pub fn new(console_uri: reqwest::Url, api: cplane_proxy_v1::NeonControlPlaneClient) -> Self {
89 0 : Self { console_uri, api }
90 0 : }
91 :
92 0 : pub(crate) fn get_api(&self) -> &cplane_proxy_v1::NeonControlPlaneClient {
93 0 : &self.api
94 0 : }
95 :
96 0 : pub(crate) async fn authenticate(
97 0 : &self,
98 0 : ctx: &RequestContext,
99 0 : auth_config: &'static AuthenticationConfig,
100 0 : client: &mut PqStream<impl AsyncRead + AsyncWrite + Unpin>,
101 0 : ) -> auth::Result<(
102 0 : ConsoleRedirectNodeInfo,
103 0 : ComputeUserInfo,
104 0 : Option<Vec<IpPattern>>,
105 0 : )> {
106 0 : authenticate(ctx, auth_config, &self.console_uri, client)
107 0 : .await
108 0 : .map(|(node_info, user_info, ip_allowlist)| {
109 0 : (ConsoleRedirectNodeInfo(node_info), user_info, ip_allowlist)
110 0 : })
111 0 : }
112 : }
113 :
114 : pub struct ConsoleRedirectNodeInfo(pub(super) NodeInfo);
115 :
116 : #[async_trait]
117 : impl ComputeConnectBackend for ConsoleRedirectNodeInfo {
118 0 : async fn wake_compute(
119 0 : &self,
120 0 : _ctx: &RequestContext,
121 0 : ) -> Result<CachedNodeInfo, control_plane::errors::WakeComputeError> {
122 0 : Ok(Cached::new_uncached(self.0.clone()))
123 0 : }
124 :
125 0 : fn get_keys(&self) -> &ComputeCredentialKeys {
126 0 : &ComputeCredentialKeys::None
127 0 : }
128 : }
129 :
130 0 : async fn authenticate(
131 0 : ctx: &RequestContext,
132 0 : auth_config: &'static AuthenticationConfig,
133 0 : link_uri: &reqwest::Url,
134 0 : client: &mut PqStream<impl AsyncRead + AsyncWrite + Unpin>,
135 0 : ) -> auth::Result<(NodeInfo, ComputeUserInfo, Option<Vec<IpPattern>>)> {
136 0 : ctx.set_auth_method(crate::context::AuthMethod::ConsoleRedirect);
137 :
138 : // registering waiter can fail if we get unlucky with rng.
139 : // just try again.
140 0 : let (psql_session_id, waiter) = loop {
141 0 : let psql_session_id = new_psql_session_id();
142 :
143 0 : if let Ok(waiter) = control_plane::mgmt::get_waiter(&psql_session_id) {
144 0 : break (psql_session_id, waiter);
145 0 : }
146 : };
147 :
148 0 : let span = info_span!("console_redirect", psql_session_id = &psql_session_id);
149 0 : let greeting = hello_message(
150 0 : link_uri,
151 0 : &psql_session_id,
152 0 : auth_config.console_redirect_confirmation_timeout,
153 0 : );
154 0 :
155 0 : // Give user a URL to spawn a new database.
156 0 : info!(parent: &span, "sending the auth URL to the user");
157 0 : client
158 0 : .write_message_noflush(&Be::AuthenticationOk)?
159 0 : .write_message_noflush(&Be::CLIENT_ENCODING)?
160 0 : .write_message(&Be::NoticeResponse(&greeting))
161 0 : .await?;
162 :
163 : // Wait for console response via control plane (see `mgmt`).
164 0 : info!(parent: &span, "waiting for console's reply...");
165 0 : let db_info = tokio::time::timeout(auth_config.console_redirect_confirmation_timeout, waiter)
166 0 : .await
167 0 : .map_err(|_elapsed| {
168 0 : auth::AuthError::confirmation_timeout(
169 0 : auth_config.console_redirect_confirmation_timeout.into(),
170 0 : )
171 0 : })?
172 0 : .map_err(ConsoleRedirectError::from)?;
173 :
174 0 : if auth_config.ip_allowlist_check_enabled {
175 0 : if let Some(allowed_ips) = &db_info.allowed_ips {
176 0 : if !auth::check_peer_addr_is_in_list(&ctx.peer_addr(), allowed_ips) {
177 0 : return Err(auth::AuthError::ip_address_not_allowed(ctx.peer_addr()));
178 0 : }
179 0 : }
180 0 : }
181 :
182 : // Check if the access over the public internet is allowed, otherwise block. Note that
183 : // the console redirect is not behind the VPC service endpoint, so we don't need to check
184 : // the VPC endpoint ID.
185 0 : if let Some(public_access_allowed) = db_info.public_access_allowed {
186 0 : if !public_access_allowed {
187 0 : return Err(auth::AuthError::NetworkNotAllowed);
188 0 : }
189 0 : }
190 :
191 0 : client.write_message_noflush(&Be::NoticeResponse("Connecting to database."))?;
192 :
193 : // This config should be self-contained, because we won't
194 : // take username or dbname from client's startup message.
195 0 : let mut config = compute::ConnCfg::new(db_info.host.to_string(), db_info.port);
196 0 : config.dbname(&db_info.dbname).user(&db_info.user);
197 0 :
198 0 : let user: RoleName = db_info.user.into();
199 0 : let user_info = ComputeUserInfo {
200 0 : endpoint: db_info.aux.endpoint_id.as_str().into(),
201 0 : user: user.clone(),
202 0 : options: NeonOptions::default(),
203 0 : };
204 0 :
205 0 : ctx.set_dbname(db_info.dbname.into());
206 0 : ctx.set_user(user);
207 0 : ctx.set_project(db_info.aux.clone());
208 0 : info!("woken up a compute node");
209 :
210 : // Backwards compatibility. pg_sni_proxy uses "--" in domain names
211 : // while direct connections do not. Once we migrate to pg_sni_proxy
212 : // everywhere, we can remove this.
213 0 : if db_info.host.contains("--") {
214 0 : // we need TLS connection with SNI info to properly route it
215 0 : config.ssl_mode(SslMode::Require);
216 0 : } else {
217 0 : config.ssl_mode(SslMode::Disable);
218 0 : }
219 :
220 0 : if let Some(password) = db_info.password {
221 0 : config.password(password.as_ref());
222 0 : }
223 :
224 0 : Ok((
225 0 : NodeInfo {
226 0 : config,
227 0 : aux: db_info.aux,
228 0 : },
229 0 : user_info,
230 0 : db_info.allowed_ips,
231 0 : ))
232 0 : }
|