LCOV - code coverage report
Current view: top level - proxy/src/auth/backend - mod.rs (source / functions) Coverage Total Hit
Test: c8f8d331b83562868d9054d9e0e68f866772aeaa.info Lines: 70.5 % 352 248
Test Date: 2025-07-26 17:20:05 Functions: 44.6 % 56 25

            Line data    Source code
       1              : mod classic;
       2              : mod console_redirect;
       3              : mod hacks;
       4              : pub mod jwt;
       5              : pub mod local;
       6              : 
       7              : use std::sync::Arc;
       8              : 
       9              : pub use console_redirect::ConsoleRedirectBackend;
      10              : pub(crate) use console_redirect::ConsoleRedirectError;
      11              : use local::LocalBackend;
      12              : use postgres_client::config::AuthKeys;
      13              : use serde::{Deserialize, Serialize};
      14              : use tokio::io::{AsyncRead, AsyncWrite};
      15              : use tracing::{debug, info};
      16              : 
      17              : use crate::auth::{self, ComputeUserInfoMaybeEndpoint, validate_password_and_exchange};
      18              : use crate::cache::Cached;
      19              : use crate::cache::node_info::CachedNodeInfo;
      20              : use crate::config::AuthenticationConfig;
      21              : use crate::context::RequestContext;
      22              : use crate::control_plane::client::ControlPlaneClient;
      23              : use crate::control_plane::errors::GetAuthInfoError;
      24              : use crate::control_plane::messages::EndpointRateLimitConfig;
      25              : use crate::control_plane::{
      26              :     self, AccessBlockerFlags, AuthSecret, ControlPlaneApi, EndpointAccessControl, RoleAccessControl,
      27              : };
      28              : use crate::intern::EndpointIdInt;
      29              : use crate::pqproto::BeMessage;
      30              : use crate::proxy::NeonOptions;
      31              : use crate::proxy::wake_compute::WakeComputeBackend;
      32              : use crate::rate_limiter::EndpointRateLimiter;
      33              : use crate::stream::Stream;
      34              : use crate::types::{EndpointCacheKey, EndpointId, RoleName};
      35              : use crate::{scram, stream};
      36              : 
      37              : /// Alternative to [`std::borrow::Cow`] but doesn't need `T: ToOwned` as we don't need that functionality
      38              : pub enum MaybeOwned<'a, T> {
      39              :     Owned(T),
      40              :     Borrowed(&'a T),
      41              : }
      42              : 
      43              : impl<T> std::ops::Deref for MaybeOwned<'_, T> {
      44              :     type Target = T;
      45              : 
      46           21 :     fn deref(&self) -> &Self::Target {
      47           21 :         match self {
      48           21 :             MaybeOwned::Owned(t) => t,
      49            0 :             MaybeOwned::Borrowed(t) => t,
      50              :         }
      51           21 :     }
      52              : }
      53              : 
      54              : /// This type serves two purposes:
      55              : ///
      56              : /// * When `T` is `()`, it's just a regular auth backend selector
      57              : ///   which we use in [`crate::config::ProxyConfig`].
      58              : ///
      59              : /// * However, when we substitute `T` with [`ComputeUserInfoMaybeEndpoint`],
      60              : ///   this helps us provide the credentials only to those auth
      61              : ///   backends which require them for the authentication process.
      62              : pub enum Backend<'a, T> {
      63              :     /// Cloud API (V2).
      64              :     ControlPlane(MaybeOwned<'a, ControlPlaneClient>, T),
      65              :     /// Local proxy uses configured auth credentials and does not wake compute
      66              :     Local(MaybeOwned<'a, LocalBackend>),
      67              : }
      68              : 
      69              : impl std::fmt::Display for Backend<'_, ()> {
      70            0 :     fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
      71            0 :         match self {
      72            0 :             Self::ControlPlane(api, ()) => match &**api {
      73            0 :                 ControlPlaneClient::ProxyV1(endpoint) => fmt
      74            0 :                     .debug_tuple("ControlPlane::ProxyV1")
      75            0 :                     .field(&endpoint.url())
      76            0 :                     .finish(),
      77              :                 #[cfg(any(test, feature = "testing"))]
      78            0 :                 ControlPlaneClient::PostgresMock(endpoint) => {
      79            0 :                     let url = endpoint.url();
      80            0 :                     match url::Url::parse(url) {
      81            0 :                         Ok(mut url) => {
      82            0 :                             let _ = url.set_password(Some("_redacted_"));
      83            0 :                             let url = url.as_str();
      84            0 :                             fmt.debug_tuple("ControlPlane::PostgresMock")
      85            0 :                                 .field(&url)
      86            0 :                                 .finish()
      87              :                         }
      88            0 :                         Err(_) => fmt
      89            0 :                             .debug_tuple("ControlPlane::PostgresMock")
      90            0 :                             .field(&url)
      91            0 :                             .finish(),
      92              :                     }
      93              :                 }
      94              :                 #[cfg(test)]
      95            0 :                 ControlPlaneClient::Test(_) => fmt.debug_tuple("ControlPlane::Test").finish(),
      96              :             },
      97            0 :             Self::Local(_) => fmt.debug_tuple("Local").finish(),
      98              :         }
      99            0 :     }
     100              : }
     101              : 
     102              : impl<T> Backend<'_, T> {
     103              :     /// Very similar to [`std::option::Option::as_ref`].
     104              :     /// This helps us pass structured config to async tasks.
     105            0 :     pub(crate) fn as_ref(&self) -> Backend<'_, &T> {
     106            0 :         match self {
     107            0 :             Self::ControlPlane(c, x) => Backend::ControlPlane(MaybeOwned::Borrowed(c), x),
     108            0 :             Self::Local(l) => Backend::Local(MaybeOwned::Borrowed(l)),
     109              :         }
     110            0 :     }
     111              : 
     112            0 :     pub(crate) fn get_api(&self) -> &ControlPlaneClient {
     113            0 :         match self {
     114            0 :             Self::ControlPlane(api, _) => api,
     115            0 :             Self::Local(_) => panic!("Local backend has no API"),
     116              :         }
     117            0 :     }
     118              : 
     119            0 :     pub(crate) fn is_local_proxy(&self) -> bool {
     120            0 :         matches!(self, Self::Local(_))
     121            0 :     }
     122              : }
     123              : 
     124              : impl<'a, T> Backend<'a, T> {
     125              :     /// Very similar to [`std::option::Option::map`].
     126              :     /// Maps [`Backend<T>`] to [`Backend<R>`] by applying
     127              :     /// a function to a contained value.
     128            0 :     pub(crate) fn map<R>(self, f: impl FnOnce(T) -> R) -> Backend<'a, R> {
     129            0 :         match self {
     130            0 :             Self::ControlPlane(c, x) => Backend::ControlPlane(c, f(x)),
     131            0 :             Self::Local(l) => Backend::Local(l),
     132              :         }
     133            0 :     }
     134              : }
     135              : impl<'a, T, E> Backend<'a, Result<T, E>> {
     136              :     /// Very similar to [`std::option::Option::transpose`].
     137              :     /// This is most useful for error handling.
     138            0 :     pub(crate) fn transpose(self) -> Result<Backend<'a, T>, E> {
     139            0 :         match self {
     140            0 :             Self::ControlPlane(c, x) => x.map(|x| Backend::ControlPlane(c, x)),
     141            0 :             Self::Local(l) => Ok(Backend::Local(l)),
     142              :         }
     143            0 :     }
     144              : }
     145              : 
     146              : pub(crate) struct ComputeCredentials {
     147              :     pub(crate) info: ComputeUserInfo,
     148              :     pub(crate) keys: ComputeCredentialKeys,
     149              : }
     150              : 
     151              : #[derive(Debug, Clone)]
     152              : pub(crate) struct ComputeUserInfoNoEndpoint {
     153              :     pub(crate) user: RoleName,
     154              :     pub(crate) options: NeonOptions,
     155              : }
     156              : 
     157            0 : #[derive(Debug, Clone, Default, Serialize, Deserialize)]
     158              : pub(crate) struct ComputeUserInfo {
     159              :     pub(crate) endpoint: EndpointId,
     160              :     pub(crate) user: RoleName,
     161              :     pub(crate) options: NeonOptions,
     162              : }
     163              : 
     164              : impl ComputeUserInfo {
     165            2 :     pub(crate) fn endpoint_cache_key(&self) -> EndpointCacheKey {
     166            2 :         self.options.get_cache_key(&self.endpoint)
     167            2 :     }
     168              : }
     169              : 
     170              : #[cfg_attr(test, derive(Debug))]
     171              : pub(crate) enum ComputeCredentialKeys {
     172              :     AuthKeys(AuthKeys),
     173              :     JwtPayload(Vec<u8>),
     174              : }
     175              : 
     176              : impl TryFrom<ComputeUserInfoMaybeEndpoint> for ComputeUserInfo {
     177              :     // user name
     178              :     type Error = ComputeUserInfoNoEndpoint;
     179              : 
     180            3 :     fn try_from(user_info: ComputeUserInfoMaybeEndpoint) -> Result<Self, Self::Error> {
     181            3 :         match user_info.endpoint_id {
     182            1 :             None => Err(ComputeUserInfoNoEndpoint {
     183            1 :                 user: user_info.user,
     184            1 :                 options: user_info.options,
     185            1 :             }),
     186            2 :             Some(endpoint) => Ok(ComputeUserInfo {
     187            2 :                 endpoint,
     188            2 :                 user: user_info.user,
     189            2 :                 options: user_info.options,
     190            2 :             }),
     191              :         }
     192            3 :     }
     193              : }
     194              : 
     195              : /// True to its name, this function encapsulates our current auth trade-offs.
     196              : /// Here, we choose the appropriate auth flow based on circumstances.
     197              : ///
     198              : /// All authentication flows will emit an AuthenticationOk message if successful.
     199            3 : async fn auth_quirks(
     200            3 :     ctx: &RequestContext,
     201            3 :     api: &impl control_plane::ControlPlaneApi,
     202            3 :     user_info: ComputeUserInfoMaybeEndpoint,
     203            3 :     client: &mut stream::PqStream<Stream<impl AsyncRead + AsyncWrite + Unpin>>,
     204            3 :     allow_cleartext: bool,
     205            3 :     config: &'static AuthenticationConfig,
     206            3 :     endpoint_rate_limiter: Arc<EndpointRateLimiter>,
     207            3 : ) -> auth::Result<ComputeCredentials> {
     208              :     // If there's no project so far, that entails that client doesn't
     209              :     // support SNI or other means of passing the endpoint (project) name.
     210              :     // We now expect to see a very specific payload in the place of password.
     211            3 :     let (info, unauthenticated_password) = match user_info.try_into() {
     212            1 :         Err(info) => {
     213            1 :             let (info, password) =
     214            1 :                 hacks::password_hack_no_authentication(ctx, info, client).await?;
     215            1 :             ctx.set_endpoint_id(info.endpoint.clone());
     216            1 :             (info, Some(password))
     217              :         }
     218            2 :         Ok(info) => (info, None),
     219              :     };
     220              : 
     221            3 :     debug!("fetching authentication info and allowlists");
     222              : 
     223            3 :     let access_controls = api
     224            3 :         .get_endpoint_access_control(ctx, &info.endpoint, &info.user)
     225            3 :         .await?;
     226              : 
     227            3 :     access_controls.check(
     228            3 :         ctx,
     229            3 :         config.ip_allowlist_check_enabled,
     230            3 :         config.is_vpc_acccess_proxy,
     231            0 :     )?;
     232              : 
     233            3 :     access_controls.connection_attempt_rate_limit(ctx, &info.endpoint, &endpoint_rate_limiter)?;
     234              : 
     235            3 :     let role_access = api
     236            3 :         .get_role_access_control(ctx, &info.endpoint, &info.user)
     237            3 :         .await?;
     238              : 
     239            3 :     let secret = if let Some(secret) = role_access.secret {
     240            3 :         secret
     241              :     } else {
     242              :         // If we don't have an authentication secret, we mock one to
     243              :         // prevent malicious probing (possible due to missing protocol steps).
     244              :         // This mocked secret will never lead to successful authentication.
     245            0 :         info!("authentication info not found, mocking it");
     246            0 :         AuthSecret::Scram(scram::ServerSecret::mock(rand::random()))
     247              :     };
     248              : 
     249            3 :     match authenticate_with_secret(
     250            3 :         ctx,
     251            3 :         secret,
     252            3 :         info,
     253            3 :         client,
     254            3 :         unauthenticated_password,
     255            3 :         allow_cleartext,
     256            3 :         config,
     257              :     )
     258            3 :     .await
     259              :     {
     260            3 :         Ok(keys) => Ok(keys),
     261            0 :         Err(e) => Err(e),
     262              :     }
     263            3 : }
     264              : 
     265            3 : async fn authenticate_with_secret(
     266            3 :     ctx: &RequestContext,
     267            3 :     secret: AuthSecret,
     268            3 :     info: ComputeUserInfo,
     269            3 :     client: &mut stream::PqStream<Stream<impl AsyncRead + AsyncWrite + Unpin>>,
     270            3 :     unauthenticated_password: Option<Vec<u8>>,
     271            3 :     allow_cleartext: bool,
     272            3 :     config: &'static AuthenticationConfig,
     273            3 : ) -> auth::Result<ComputeCredentials> {
     274            3 :     if let Some(password) = unauthenticated_password {
     275            1 :         let ep = EndpointIdInt::from(&info.endpoint);
     276              : 
     277            1 :         let auth_outcome =
     278            1 :             validate_password_and_exchange(&config.thread_pool, ep, &password, secret).await?;
     279            1 :         let keys = match auth_outcome {
     280            1 :             crate::sasl::Outcome::Success(key) => key,
     281            0 :             crate::sasl::Outcome::Failure(reason) => {
     282            0 :                 info!("auth backend failed with an error: {reason}");
     283            0 :                 return Err(auth::AuthError::password_failed(&*info.user));
     284              :             }
     285              :         };
     286              : 
     287              :         // we have authenticated the password
     288            1 :         client.write_message(BeMessage::AuthenticationOk);
     289              : 
     290            1 :         return Ok(ComputeCredentials { info, keys });
     291            2 :     }
     292              : 
     293              :     // -- the remaining flows are self-authenticating --
     294              : 
     295              :     // Perform cleartext auth if we're allowed to do that.
     296              :     // Currently, we use it for websocket connections (latency).
     297            2 :     if allow_cleartext {
     298            1 :         ctx.set_auth_method(crate::context::AuthMethod::Cleartext);
     299            1 :         return hacks::authenticate_cleartext(ctx, info, client, secret, config).await;
     300            1 :     }
     301              : 
     302              :     // Finally, proceed with the main auth flow (SCRAM-based).
     303            1 :     classic::authenticate(ctx, info, client, config, secret).await
     304            3 : }
     305              : 
     306              : impl<'a> Backend<'a, ComputeUserInfoMaybeEndpoint> {
     307              :     /// Get username from the credentials.
     308            0 :     pub(crate) fn get_user(&self) -> &str {
     309            0 :         match self {
     310            0 :             Self::ControlPlane(_, user_info) => &user_info.user,
     311            0 :             Self::Local(_) => "local",
     312              :         }
     313            0 :     }
     314              : 
     315              :     /// Authenticate the client via the requested backend, possibly using credentials.
     316              :     #[tracing::instrument(fields(allow_cleartext = allow_cleartext), skip_all)]
     317              :     pub(crate) async fn authenticate(
     318              :         self,
     319              :         ctx: &RequestContext,
     320              :         client: &mut stream::PqStream<Stream<impl AsyncRead + AsyncWrite + Unpin>>,
     321              :         allow_cleartext: bool,
     322              :         config: &'static AuthenticationConfig,
     323              :         endpoint_rate_limiter: Arc<EndpointRateLimiter>,
     324              :     ) -> auth::Result<Backend<'a, ComputeCredentials>> {
     325              :         let res = match self {
     326              :             Self::ControlPlane(api, user_info) => {
     327              :                 debug!(
     328              :                     user = &*user_info.user,
     329              :                     project = user_info.endpoint(),
     330              :                     "performing authentication using the console"
     331              :                 );
     332              : 
     333              :                 let auth_res = auth_quirks(
     334              :                     ctx,
     335              :                     &*api,
     336              :                     user_info.clone(),
     337              :                     client,
     338              :                     allow_cleartext,
     339              :                     config,
     340              :                     endpoint_rate_limiter,
     341              :                 )
     342              :                 .await;
     343              :                 match auth_res {
     344              :                     Ok(credentials) => Ok(Backend::ControlPlane(api, credentials)),
     345              :                     Err(e) => {
     346              :                         // The password could have been changed, so we invalidate the cache.
     347              :                         // We should only invalidate the cache if the TTL might have expired.
     348              :                         if e.is_password_failed()
     349              :                             && let ControlPlaneClient::ProxyV1(api) = &*api
     350              :                             && let Some(ep) = &user_info.endpoint_id
     351              :                         {
     352              :                             api.caches
     353              :                                 .project_info
     354              :                                 .maybe_invalidate_role_secret(ep, &user_info.user);
     355              :                         }
     356              : 
     357              :                         Err(e)
     358              :                     }
     359              :                 }
     360              :             }
     361              :             Self::Local(_) => {
     362              :                 return Err(auth::AuthError::bad_auth_method("invalid for local proxy"));
     363              :             }
     364              :         };
     365              : 
     366              :         // TODO: replace with some metric
     367              :         info!("user successfully authenticated");
     368              :         res
     369              :     }
     370              : }
     371              : 
     372              : impl Backend<'_, ComputeUserInfo> {
     373            0 :     pub(crate) async fn get_role_secret(
     374            0 :         &self,
     375            0 :         ctx: &RequestContext,
     376            0 :     ) -> Result<RoleAccessControl, GetAuthInfoError> {
     377            0 :         match self {
     378            0 :             Self::ControlPlane(api, user_info) => {
     379            0 :                 api.get_role_access_control(ctx, &user_info.endpoint, &user_info.user)
     380            0 :                     .await
     381              :             }
     382            0 :             Self::Local(_) => Ok(RoleAccessControl { secret: None }),
     383              :         }
     384            0 :     }
     385              : 
     386            0 :     pub(crate) async fn get_endpoint_access_control(
     387            0 :         &self,
     388            0 :         ctx: &RequestContext,
     389            0 :     ) -> Result<EndpointAccessControl, GetAuthInfoError> {
     390            0 :         match self {
     391            0 :             Self::ControlPlane(api, user_info) => {
     392            0 :                 api.get_endpoint_access_control(ctx, &user_info.endpoint, &user_info.user)
     393            0 :                     .await
     394              :             }
     395            0 :             Self::Local(_) => Ok(EndpointAccessControl {
     396            0 :                 allowed_ips: Arc::new(vec![]),
     397            0 :                 allowed_vpce: Arc::new(vec![]),
     398            0 :                 flags: AccessBlockerFlags::default(),
     399            0 :                 rate_limits: EndpointRateLimitConfig::default(),
     400            0 :             }),
     401              :         }
     402            0 :     }
     403              : }
     404              : 
     405              : #[async_trait::async_trait]
     406              : impl WakeComputeBackend for Backend<'_, ComputeUserInfo> {
     407           21 :     async fn wake_compute(
     408              :         &self,
     409              :         ctx: &RequestContext,
     410           21 :     ) -> Result<CachedNodeInfo, control_plane::errors::WakeComputeError> {
     411           21 :         match self {
     412           21 :             Self::ControlPlane(api, info) => api.wake_compute(ctx, info).await,
     413            0 :             Self::Local(local) => Ok(Cached::new_uncached(local.node_info.clone())),
     414              :         }
     415           42 :     }
     416              : }
     417              : 
     418              : #[cfg(test)]
     419              : mod tests {
     420              :     #![allow(clippy::unimplemented, clippy::unwrap_used)]
     421              : 
     422              :     use std::sync::Arc;
     423              : 
     424              :     use bytes::BytesMut;
     425              :     use control_plane::AuthSecret;
     426              :     use fallible_iterator::FallibleIterator;
     427              :     use once_cell::sync::Lazy;
     428              :     use postgres_protocol::authentication::sasl::{ChannelBinding, ScramSha256};
     429              :     use postgres_protocol::message::backend::Message as PgMessage;
     430              :     use postgres_protocol::message::frontend;
     431              :     use tokio::io::{AsyncRead, AsyncReadExt, AsyncWriteExt};
     432              : 
     433              :     use super::auth_quirks;
     434              :     use super::jwt::JwkCache;
     435              :     use crate::auth::{ComputeUserInfoMaybeEndpoint, IpPattern};
     436              :     use crate::cache::node_info::CachedNodeInfo;
     437              :     use crate::config::AuthenticationConfig;
     438              :     use crate::context::RequestContext;
     439              :     use crate::control_plane::messages::EndpointRateLimitConfig;
     440              :     use crate::control_plane::{
     441              :         self, AccessBlockerFlags, EndpointAccessControl, RoleAccessControl,
     442              :     };
     443              :     use crate::proxy::NeonOptions;
     444              :     use crate::rate_limiter::EndpointRateLimiter;
     445              :     use crate::scram::ServerSecret;
     446              :     use crate::scram::threadpool::ThreadPool;
     447              :     use crate::stream::{PqStream, Stream};
     448              : 
     449              :     struct Auth {
     450              :         ips: Vec<IpPattern>,
     451              :         vpc_endpoint_ids: Vec<String>,
     452              :         access_blocker_flags: AccessBlockerFlags,
     453              :         secret: AuthSecret,
     454              :     }
     455              : 
     456              :     impl control_plane::ControlPlaneApi for Auth {
     457            3 :         async fn get_role_access_control(
     458            3 :             &self,
     459            3 :             _ctx: &RequestContext,
     460            3 :             _endpoint: &crate::types::EndpointId,
     461            3 :             _role: &crate::types::RoleName,
     462            3 :         ) -> Result<RoleAccessControl, control_plane::errors::GetAuthInfoError> {
     463            3 :             Ok(RoleAccessControl {
     464            3 :                 secret: Some(self.secret.clone()),
     465            3 :             })
     466            3 :         }
     467              : 
     468            3 :         async fn get_endpoint_access_control(
     469            3 :             &self,
     470            3 :             _ctx: &RequestContext,
     471            3 :             _endpoint: &crate::types::EndpointId,
     472            3 :             _role: &crate::types::RoleName,
     473            3 :         ) -> Result<EndpointAccessControl, control_plane::errors::GetAuthInfoError> {
     474            3 :             Ok(EndpointAccessControl {
     475            3 :                 allowed_ips: Arc::new(self.ips.clone()),
     476            3 :                 allowed_vpce: Arc::new(self.vpc_endpoint_ids.clone()),
     477            3 :                 flags: self.access_blocker_flags,
     478            3 :                 rate_limits: EndpointRateLimitConfig::default(),
     479            3 :             })
     480            3 :         }
     481              : 
     482            0 :         async fn get_endpoint_jwks(
     483            0 :             &self,
     484            0 :             _ctx: &RequestContext,
     485            0 :             _endpoint: &crate::types::EndpointId,
     486            0 :         ) -> Result<Vec<super::jwt::AuthRule>, control_plane::errors::GetEndpointJwksError>
     487            0 :         {
     488            0 :             unimplemented!()
     489              :         }
     490              : 
     491            0 :         async fn wake_compute(
     492            0 :             &self,
     493            0 :             _ctx: &RequestContext,
     494            0 :             _user_info: &super::ComputeUserInfo,
     495            0 :         ) -> Result<CachedNodeInfo, control_plane::errors::WakeComputeError> {
     496            0 :             unimplemented!()
     497              :         }
     498              :     }
     499              : 
     500              :     static CONFIG: Lazy<AuthenticationConfig> = Lazy::new(|| AuthenticationConfig {
     501            3 :         jwks_cache: JwkCache::default(),
     502            3 :         thread_pool: ThreadPool::new(1),
     503            3 :         scram_protocol_timeout: std::time::Duration::from_secs(5),
     504              :         ip_allowlist_check_enabled: true,
     505              :         is_vpc_acccess_proxy: false,
     506              :         is_auth_broker: false,
     507              :         accept_jwts: false,
     508            3 :         console_redirect_confirmation_timeout: std::time::Duration::from_secs(5),
     509            3 :     });
     510              : 
     511            5 :     async fn read_message(r: &mut (impl AsyncRead + Unpin), b: &mut BytesMut) -> PgMessage {
     512              :         loop {
     513            7 :             r.read_buf(&mut *b).await.unwrap();
     514            7 :             if let Some(m) = PgMessage::parse(&mut *b).unwrap() {
     515            5 :                 break m;
     516            2 :             }
     517              :         }
     518            5 :     }
     519              : 
     520              :     #[tokio::test]
     521            1 :     async fn auth_quirks_scram() {
     522            1 :         let (mut client, server) = tokio::io::duplex(1024);
     523            1 :         let mut stream = PqStream::new_skip_handshake(Stream::from_raw(server));
     524              : 
     525            1 :         let ctx = RequestContext::test();
     526            1 :         let api = Auth {
     527            1 :             ips: vec![],
     528            1 :             vpc_endpoint_ids: vec![],
     529            1 :             access_blocker_flags: AccessBlockerFlags::default(),
     530            1 :             secret: AuthSecret::Scram(ServerSecret::build("my-secret-password").await.unwrap()),
     531              :         };
     532              : 
     533            1 :         let user_info = ComputeUserInfoMaybeEndpoint {
     534            1 :             user: "conrad".into(),
     535            1 :             endpoint_id: Some("endpoint".into()),
     536            1 :             options: NeonOptions::default(),
     537            1 :         };
     538              : 
     539            1 :         let handle = tokio::spawn(async move {
     540            1 :             let mut scram = ScramSha256::new(b"my-secret-password", ChannelBinding::unsupported());
     541              : 
     542            1 :             let mut read = BytesMut::new();
     543              : 
     544              :             // server should offer scram
     545            1 :             match read_message(&mut client, &mut read).await {
     546            1 :                 PgMessage::AuthenticationSasl(a) => {
     547            1 :                     let options: Vec<&str> = a.mechanisms().collect().unwrap();
     548            1 :                     assert_eq!(options, ["SCRAM-SHA-256"]);
     549              :                 }
     550            0 :                 _ => panic!("wrong message"),
     551              :             }
     552              : 
     553              :             // client sends client-first-message
     554            1 :             let mut write = BytesMut::new();
     555            1 :             frontend::sasl_initial_response("SCRAM-SHA-256", scram.message(), &mut write).unwrap();
     556            1 :             client.write_all(&write).await.unwrap();
     557              : 
     558              :             // server response with server-first-message
     559            1 :             match read_message(&mut client, &mut read).await {
     560            1 :                 PgMessage::AuthenticationSaslContinue(a) => {
     561            1 :                     scram.update(a.data()).await.unwrap();
     562              :                 }
     563            0 :                 _ => panic!("wrong message"),
     564              :             }
     565              : 
     566              :             // client response with client-final-message
     567            1 :             write.clear();
     568            1 :             frontend::sasl_response(scram.message(), &mut write).unwrap();
     569            1 :             client.write_all(&write).await.unwrap();
     570              : 
     571              :             // server response with server-final-message
     572            1 :             match read_message(&mut client, &mut read).await {
     573            1 :                 PgMessage::AuthenticationSaslFinal(a) => {
     574            1 :                     scram.finish(a.data()).unwrap();
     575            1 :                 }
     576            0 :                 _ => panic!("wrong message"),
     577              :             }
     578            1 :         });
     579            1 :         let endpoint_rate_limiter = Arc::new(EndpointRateLimiter::new_with_shards(
     580              :             EndpointRateLimiter::DEFAULT,
     581              :             64,
     582              :         ));
     583              : 
     584            1 :         let _creds = auth_quirks(
     585            1 :             &ctx,
     586            1 :             &api,
     587            1 :             user_info,
     588            1 :             &mut stream,
     589            1 :             false,
     590            1 :             &CONFIG,
     591            1 :             endpoint_rate_limiter,
     592            1 :         )
     593            1 :         .await
     594            1 :         .unwrap();
     595              : 
     596              :         // flush the final server message
     597            1 :         stream.flush().await.unwrap();
     598              : 
     599            1 :         handle.await.unwrap();
     600            1 :     }
     601              : 
     602              :     #[tokio::test]
     603            1 :     async fn auth_quirks_cleartext() {
     604            1 :         let (mut client, server) = tokio::io::duplex(1024);
     605            1 :         let mut stream = PqStream::new_skip_handshake(Stream::from_raw(server));
     606              : 
     607            1 :         let ctx = RequestContext::test();
     608            1 :         let api = Auth {
     609            1 :             ips: vec![],
     610            1 :             vpc_endpoint_ids: vec![],
     611            1 :             access_blocker_flags: AccessBlockerFlags::default(),
     612            1 :             secret: AuthSecret::Scram(ServerSecret::build("my-secret-password").await.unwrap()),
     613              :         };
     614              : 
     615            1 :         let user_info = ComputeUserInfoMaybeEndpoint {
     616            1 :             user: "conrad".into(),
     617            1 :             endpoint_id: Some("endpoint".into()),
     618            1 :             options: NeonOptions::default(),
     619            1 :         };
     620              : 
     621            1 :         let handle = tokio::spawn(async move {
     622            1 :             let mut read = BytesMut::new();
     623            1 :             let mut write = BytesMut::new();
     624              : 
     625              :             // server should offer cleartext
     626            1 :             match read_message(&mut client, &mut read).await {
     627            1 :                 PgMessage::AuthenticationCleartextPassword => {}
     628            0 :                 _ => panic!("wrong message"),
     629              :             }
     630              : 
     631              :             // client responds with password
     632            1 :             write.clear();
     633            1 :             frontend::password_message(b"my-secret-password", &mut write).unwrap();
     634            1 :             client.write_all(&write).await.unwrap();
     635            1 :         });
     636            1 :         let endpoint_rate_limiter = Arc::new(EndpointRateLimiter::new_with_shards(
     637              :             EndpointRateLimiter::DEFAULT,
     638              :             64,
     639              :         ));
     640              : 
     641            1 :         let _creds = auth_quirks(
     642            1 :             &ctx,
     643            1 :             &api,
     644            1 :             user_info,
     645            1 :             &mut stream,
     646            1 :             true,
     647            1 :             &CONFIG,
     648            1 :             endpoint_rate_limiter,
     649            1 :         )
     650            1 :         .await
     651            1 :         .unwrap();
     652              : 
     653            1 :         handle.await.unwrap();
     654            1 :     }
     655              : 
     656              :     #[tokio::test]
     657            1 :     async fn auth_quirks_password_hack() {
     658            1 :         let (mut client, server) = tokio::io::duplex(1024);
     659            1 :         let mut stream = PqStream::new_skip_handshake(Stream::from_raw(server));
     660              : 
     661            1 :         let ctx = RequestContext::test();
     662            1 :         let api = Auth {
     663            1 :             ips: vec![],
     664            1 :             vpc_endpoint_ids: vec![],
     665            1 :             access_blocker_flags: AccessBlockerFlags::default(),
     666            1 :             secret: AuthSecret::Scram(ServerSecret::build("my-secret-password").await.unwrap()),
     667              :         };
     668              : 
     669            1 :         let user_info = ComputeUserInfoMaybeEndpoint {
     670            1 :             user: "conrad".into(),
     671            1 :             endpoint_id: None,
     672            1 :             options: NeonOptions::default(),
     673            1 :         };
     674              : 
     675            1 :         let handle = tokio::spawn(async move {
     676            1 :             let mut read = BytesMut::new();
     677              : 
     678              :             // server should offer cleartext
     679            1 :             match read_message(&mut client, &mut read).await {
     680            1 :                 PgMessage::AuthenticationCleartextPassword => {}
     681            0 :                 _ => panic!("wrong message"),
     682              :             }
     683              : 
     684              :             // client responds with password
     685            1 :             let mut write = BytesMut::new();
     686            1 :             frontend::password_message(b"endpoint=my-endpoint;my-secret-password", &mut write)
     687            1 :                 .unwrap();
     688            1 :             client.write_all(&write).await.unwrap();
     689            1 :         });
     690              : 
     691            1 :         let endpoint_rate_limiter = Arc::new(EndpointRateLimiter::new_with_shards(
     692              :             EndpointRateLimiter::DEFAULT,
     693              :             64,
     694              :         ));
     695              : 
     696            1 :         let creds = auth_quirks(
     697            1 :             &ctx,
     698            1 :             &api,
     699            1 :             user_info,
     700            1 :             &mut stream,
     701            1 :             true,
     702            1 :             &CONFIG,
     703            1 :             endpoint_rate_limiter,
     704            1 :         )
     705            1 :         .await
     706            1 :         .unwrap();
     707              : 
     708            1 :         assert_eq!(creds.info.endpoint, "my-endpoint");
     709              : 
     710            1 :         handle.await.unwrap();
     711            1 :     }
     712              : }
        

Generated by: LCOV version 2.1-beta