Line data Source code
1 : //! Mock console backend which relies on a user-provided postgres instance.
2 :
3 : use super::{
4 : errors::{ApiError, GetAuthInfoError, WakeComputeError},
5 : AuthInfo, AuthSecret, CachedNodeInfo, NodeInfo,
6 : };
7 : use crate::context::RequestMonitoring;
8 : use crate::{auth::backend::ComputeUserInfo, compute, error::io_error, scram, url::ApiUrl};
9 : use crate::{auth::IpPattern, cache::Cached};
10 : use crate::{
11 : console::{
12 : messages::MetricsAuxInfo,
13 : provider::{CachedAllowedIps, CachedRoleSecret},
14 : },
15 : BranchId, EndpointId, ProjectId,
16 : };
17 : use futures::TryFutureExt;
18 : use std::{str::FromStr, sync::Arc};
19 : use thiserror::Error;
20 : use tokio_postgres::{config::SslMode, Client};
21 : use tracing::{error, info, info_span, warn, Instrument};
22 :
23 0 : #[derive(Debug, Error)]
24 : enum MockApiError {
25 : #[error("Failed to read password: {0}")]
26 : PasswordNotSet(tokio_postgres::Error),
27 : }
28 :
29 : impl From<MockApiError> for ApiError {
30 0 : fn from(e: MockApiError) -> Self {
31 0 : io_error(e).into()
32 0 : }
33 : }
34 :
35 : impl From<tokio_postgres::Error> for ApiError {
36 0 : fn from(e: tokio_postgres::Error) -> Self {
37 0 : io_error(e).into()
38 0 : }
39 : }
40 :
41 : #[derive(Clone)]
42 : pub struct Api {
43 : endpoint: ApiUrl,
44 : }
45 :
46 : impl Api {
47 0 : pub fn new(endpoint: ApiUrl) -> Self {
48 0 : Self { endpoint }
49 0 : }
50 :
51 0 : pub(crate) fn url(&self) -> &str {
52 0 : self.endpoint.as_str()
53 0 : }
54 :
55 0 : async fn do_get_auth_info(
56 0 : &self,
57 0 : user_info: &ComputeUserInfo,
58 0 : ) -> Result<AuthInfo, GetAuthInfoError> {
59 0 : let (secret, allowed_ips) = async {
60 : // Perhaps we could persist this connection, but then we'd have to
61 : // write more code for reopening it if it got closed, which doesn't
62 : // seem worth it.
63 0 : let (client, connection) =
64 0 : tokio_postgres::connect(self.endpoint.as_str(), tokio_postgres::NoTls).await?;
65 :
66 0 : tokio::spawn(connection);
67 0 : let secret = if let Some(entry) = get_execute_postgres_query(
68 0 : &client,
69 0 : "select rolpassword from pg_catalog.pg_authid where rolname = $1",
70 0 : &[&&*user_info.user],
71 0 : "rolpassword",
72 0 : )
73 0 : .await?
74 : {
75 0 : info!("got a secret: {entry}"); // safe since it's not a prod scenario
76 0 : let secret = scram::ServerSecret::parse(&entry).map(AuthSecret::Scram);
77 0 : secret.or_else(|| parse_md5(&entry).map(AuthSecret::Md5))
78 : } else {
79 0 : warn!("user '{}' does not exist", user_info.user);
80 0 : None
81 : };
82 0 : let allowed_ips = match get_execute_postgres_query(
83 0 : &client,
84 0 : "select allowed_ips from neon_control_plane.endpoints where endpoint_id = $1",
85 0 : &[&user_info.endpoint.as_str()],
86 0 : "allowed_ips",
87 0 : )
88 0 : .await?
89 : {
90 0 : Some(s) => {
91 0 : info!("got allowed_ips: {s}");
92 0 : s.split(',')
93 0 : .map(|s| IpPattern::from_str(s).unwrap())
94 0 : .collect()
95 : }
96 0 : None => vec![],
97 : };
98 :
99 0 : Ok((secret, allowed_ips))
100 0 : }
101 0 : .map_err(crate::error::log_error::<GetAuthInfoError>)
102 0 : .instrument(info_span!("postgres", url = self.endpoint.as_str()))
103 0 : .await?;
104 0 : Ok(AuthInfo {
105 0 : secret,
106 0 : allowed_ips,
107 0 : project_id: None,
108 0 : })
109 0 : }
110 :
111 0 : async fn do_wake_compute(&self) -> Result<NodeInfo, WakeComputeError> {
112 0 : let mut config = compute::ConnCfg::new();
113 0 : config
114 0 : .host(self.endpoint.host_str().unwrap_or("localhost"))
115 0 : .port(self.endpoint.port().unwrap_or(5432))
116 0 : .ssl_mode(SslMode::Disable);
117 0 :
118 0 : let node = NodeInfo {
119 0 : config,
120 0 : aux: MetricsAuxInfo {
121 0 : endpoint_id: (&EndpointId::from("endpoint")).into(),
122 0 : project_id: (&ProjectId::from("project")).into(),
123 0 : branch_id: (&BranchId::from("branch")).into(),
124 0 : cold_start_info: crate::console::messages::ColdStartInfo::Warm,
125 0 : },
126 0 : allow_self_signed_compute: false,
127 0 : };
128 0 :
129 0 : Ok(node)
130 0 : }
131 : }
132 :
133 0 : async fn get_execute_postgres_query(
134 0 : client: &Client,
135 0 : query: &str,
136 0 : params: &[&(dyn tokio_postgres::types::ToSql + Sync)],
137 0 : idx: &str,
138 0 : ) -> Result<Option<String>, GetAuthInfoError> {
139 0 : let rows = client.query(query, params).await?;
140 :
141 : // We can get at most one row, because `rolname` is unique.
142 0 : let Some(row) = rows.first() else {
143 : // This means that the user doesn't exist, so there can be no secret.
144 : // However, this is still a *valid* outcome which is very similar
145 : // to getting `404 Not found` from the Neon console.
146 0 : return Ok(None);
147 : };
148 :
149 0 : let entry = row.try_get(idx).map_err(MockApiError::PasswordNotSet)?;
150 0 : Ok(Some(entry))
151 0 : }
152 :
153 : impl super::Api for Api {
154 0 : #[tracing::instrument(skip_all)]
155 : async fn get_role_secret(
156 : &self,
157 : _ctx: &RequestMonitoring,
158 : user_info: &ComputeUserInfo,
159 : ) -> Result<CachedRoleSecret, GetAuthInfoError> {
160 : Ok(CachedRoleSecret::new_uncached(
161 : self.do_get_auth_info(user_info).await?.secret,
162 : ))
163 : }
164 :
165 0 : async fn get_allowed_ips_and_secret(
166 0 : &self,
167 0 : _ctx: &RequestMonitoring,
168 0 : user_info: &ComputeUserInfo,
169 0 : ) -> Result<(CachedAllowedIps, Option<CachedRoleSecret>), GetAuthInfoError> {
170 0 : Ok((
171 0 : Cached::new_uncached(Arc::new(
172 0 : self.do_get_auth_info(user_info).await?.allowed_ips,
173 : )),
174 0 : None,
175 : ))
176 0 : }
177 :
178 0 : #[tracing::instrument(skip_all)]
179 : async fn wake_compute(
180 : &self,
181 : _ctx: &RequestMonitoring,
182 : _user_info: &ComputeUserInfo,
183 : ) -> Result<CachedNodeInfo, WakeComputeError> {
184 : self.do_wake_compute().map_ok(Cached::new_uncached).await
185 : }
186 : }
187 :
188 0 : fn parse_md5(input: &str) -> Option<[u8; 16]> {
189 0 : let text = input.strip_prefix("md5")?;
190 :
191 0 : let mut bytes = [0u8; 16];
192 0 : hex::decode_to_slice(text, &mut bytes).ok()?;
193 :
194 0 : Some(bytes)
195 0 : }
|