LCOV - code coverage report
Current view: top level - proxy/src/auth/backend - mod.rs (source / functions) Coverage Total Hit
Test: 1e20c4f2b28aa592527961bb32170ebbd2c9172f.info Lines: 70.5 % 352 248
Test Date: 2025-07-16 12:29:03 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::config::AuthenticationConfig;
      20              : use crate::context::RequestContext;
      21              : use crate::control_plane::client::ControlPlaneClient;
      22              : use crate::control_plane::errors::GetAuthInfoError;
      23              : use crate::control_plane::messages::EndpointRateLimitConfig;
      24              : use crate::control_plane::{
      25              :     self, AccessBlockerFlags, AuthSecret, CachedNodeInfo, ControlPlaneApi, EndpointAccessControl,
      26              :     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::config::AuthenticationConfig;
     437              :     use crate::context::RequestContext;
     438              :     use crate::control_plane::messages::EndpointRateLimitConfig;
     439              :     use crate::control_plane::{
     440              :         self, AccessBlockerFlags, CachedNodeInfo, EndpointAccessControl, RoleAccessControl,
     441              :     };
     442              :     use crate::proxy::NeonOptions;
     443              :     use crate::rate_limiter::EndpointRateLimiter;
     444              :     use crate::scram::ServerSecret;
     445              :     use crate::scram::threadpool::ThreadPool;
     446              :     use crate::stream::{PqStream, Stream};
     447              : 
     448              :     struct Auth {
     449              :         ips: Vec<IpPattern>,
     450              :         vpc_endpoint_ids: Vec<String>,
     451              :         access_blocker_flags: AccessBlockerFlags,
     452              :         secret: AuthSecret,
     453              :     }
     454              : 
     455              :     impl control_plane::ControlPlaneApi for Auth {
     456            3 :         async fn get_role_access_control(
     457            3 :             &self,
     458            3 :             _ctx: &RequestContext,
     459            3 :             _endpoint: &crate::types::EndpointId,
     460            3 :             _role: &crate::types::RoleName,
     461            3 :         ) -> Result<RoleAccessControl, control_plane::errors::GetAuthInfoError> {
     462            3 :             Ok(RoleAccessControl {
     463            3 :                 secret: Some(self.secret.clone()),
     464            3 :             })
     465            3 :         }
     466              : 
     467            3 :         async fn get_endpoint_access_control(
     468            3 :             &self,
     469            3 :             _ctx: &RequestContext,
     470            3 :             _endpoint: &crate::types::EndpointId,
     471            3 :             _role: &crate::types::RoleName,
     472            3 :         ) -> Result<EndpointAccessControl, control_plane::errors::GetAuthInfoError> {
     473            3 :             Ok(EndpointAccessControl {
     474            3 :                 allowed_ips: Arc::new(self.ips.clone()),
     475            3 :                 allowed_vpce: Arc::new(self.vpc_endpoint_ids.clone()),
     476            3 :                 flags: self.access_blocker_flags,
     477            3 :                 rate_limits: EndpointRateLimitConfig::default(),
     478            3 :             })
     479            3 :         }
     480              : 
     481            0 :         async fn get_endpoint_jwks(
     482            0 :             &self,
     483            0 :             _ctx: &RequestContext,
     484            0 :             _endpoint: &crate::types::EndpointId,
     485            0 :         ) -> Result<Vec<super::jwt::AuthRule>, control_plane::errors::GetEndpointJwksError>
     486            0 :         {
     487            0 :             unimplemented!()
     488              :         }
     489              : 
     490            0 :         async fn wake_compute(
     491            0 :             &self,
     492            0 :             _ctx: &RequestContext,
     493            0 :             _user_info: &super::ComputeUserInfo,
     494            0 :         ) -> Result<CachedNodeInfo, control_plane::errors::WakeComputeError> {
     495            0 :             unimplemented!()
     496              :         }
     497              :     }
     498              : 
     499              :     static CONFIG: Lazy<AuthenticationConfig> = Lazy::new(|| AuthenticationConfig {
     500            3 :         jwks_cache: JwkCache::default(),
     501            3 :         thread_pool: ThreadPool::new(1),
     502            3 :         scram_protocol_timeout: std::time::Duration::from_secs(5),
     503              :         ip_allowlist_check_enabled: true,
     504              :         is_vpc_acccess_proxy: false,
     505              :         is_auth_broker: false,
     506              :         accept_jwts: false,
     507            3 :         console_redirect_confirmation_timeout: std::time::Duration::from_secs(5),
     508            3 :     });
     509              : 
     510            5 :     async fn read_message(r: &mut (impl AsyncRead + Unpin), b: &mut BytesMut) -> PgMessage {
     511              :         loop {
     512            7 :             r.read_buf(&mut *b).await.unwrap();
     513            7 :             if let Some(m) = PgMessage::parse(&mut *b).unwrap() {
     514            5 :                 break m;
     515            2 :             }
     516              :         }
     517            5 :     }
     518              : 
     519              :     #[tokio::test]
     520            1 :     async fn auth_quirks_scram() {
     521            1 :         let (mut client, server) = tokio::io::duplex(1024);
     522            1 :         let mut stream = PqStream::new_skip_handshake(Stream::from_raw(server));
     523              : 
     524            1 :         let ctx = RequestContext::test();
     525            1 :         let api = Auth {
     526            1 :             ips: vec![],
     527            1 :             vpc_endpoint_ids: vec![],
     528            1 :             access_blocker_flags: AccessBlockerFlags::default(),
     529            1 :             secret: AuthSecret::Scram(ServerSecret::build("my-secret-password").await.unwrap()),
     530              :         };
     531              : 
     532            1 :         let user_info = ComputeUserInfoMaybeEndpoint {
     533            1 :             user: "conrad".into(),
     534            1 :             endpoint_id: Some("endpoint".into()),
     535            1 :             options: NeonOptions::default(),
     536            1 :         };
     537              : 
     538            1 :         let handle = tokio::spawn(async move {
     539            1 :             let mut scram = ScramSha256::new(b"my-secret-password", ChannelBinding::unsupported());
     540              : 
     541            1 :             let mut read = BytesMut::new();
     542              : 
     543              :             // server should offer scram
     544            1 :             match read_message(&mut client, &mut read).await {
     545            1 :                 PgMessage::AuthenticationSasl(a) => {
     546            1 :                     let options: Vec<&str> = a.mechanisms().collect().unwrap();
     547            1 :                     assert_eq!(options, ["SCRAM-SHA-256"]);
     548              :                 }
     549            0 :                 _ => panic!("wrong message"),
     550              :             }
     551              : 
     552              :             // client sends client-first-message
     553            1 :             let mut write = BytesMut::new();
     554            1 :             frontend::sasl_initial_response("SCRAM-SHA-256", scram.message(), &mut write).unwrap();
     555            1 :             client.write_all(&write).await.unwrap();
     556              : 
     557              :             // server response with server-first-message
     558            1 :             match read_message(&mut client, &mut read).await {
     559            1 :                 PgMessage::AuthenticationSaslContinue(a) => {
     560            1 :                     scram.update(a.data()).await.unwrap();
     561              :                 }
     562            0 :                 _ => panic!("wrong message"),
     563              :             }
     564              : 
     565              :             // client response with client-final-message
     566            1 :             write.clear();
     567            1 :             frontend::sasl_response(scram.message(), &mut write).unwrap();
     568            1 :             client.write_all(&write).await.unwrap();
     569              : 
     570              :             // server response with server-final-message
     571            1 :             match read_message(&mut client, &mut read).await {
     572            1 :                 PgMessage::AuthenticationSaslFinal(a) => {
     573            1 :                     scram.finish(a.data()).unwrap();
     574            1 :                 }
     575            0 :                 _ => panic!("wrong message"),
     576              :             }
     577            1 :         });
     578            1 :         let endpoint_rate_limiter = Arc::new(EndpointRateLimiter::new_with_shards(
     579              :             EndpointRateLimiter::DEFAULT,
     580              :             64,
     581              :         ));
     582              : 
     583            1 :         let _creds = auth_quirks(
     584            1 :             &ctx,
     585            1 :             &api,
     586            1 :             user_info,
     587            1 :             &mut stream,
     588            1 :             false,
     589            1 :             &CONFIG,
     590            1 :             endpoint_rate_limiter,
     591            1 :         )
     592            1 :         .await
     593            1 :         .unwrap();
     594              : 
     595              :         // flush the final server message
     596            1 :         stream.flush().await.unwrap();
     597              : 
     598            1 :         handle.await.unwrap();
     599            1 :     }
     600              : 
     601              :     #[tokio::test]
     602            1 :     async fn auth_quirks_cleartext() {
     603            1 :         let (mut client, server) = tokio::io::duplex(1024);
     604            1 :         let mut stream = PqStream::new_skip_handshake(Stream::from_raw(server));
     605              : 
     606            1 :         let ctx = RequestContext::test();
     607            1 :         let api = Auth {
     608            1 :             ips: vec![],
     609            1 :             vpc_endpoint_ids: vec![],
     610            1 :             access_blocker_flags: AccessBlockerFlags::default(),
     611            1 :             secret: AuthSecret::Scram(ServerSecret::build("my-secret-password").await.unwrap()),
     612              :         };
     613              : 
     614            1 :         let user_info = ComputeUserInfoMaybeEndpoint {
     615            1 :             user: "conrad".into(),
     616            1 :             endpoint_id: Some("endpoint".into()),
     617            1 :             options: NeonOptions::default(),
     618            1 :         };
     619              : 
     620            1 :         let handle = tokio::spawn(async move {
     621            1 :             let mut read = BytesMut::new();
     622            1 :             let mut write = BytesMut::new();
     623              : 
     624              :             // server should offer cleartext
     625            1 :             match read_message(&mut client, &mut read).await {
     626            1 :                 PgMessage::AuthenticationCleartextPassword => {}
     627            0 :                 _ => panic!("wrong message"),
     628              :             }
     629              : 
     630              :             // client responds with password
     631            1 :             write.clear();
     632            1 :             frontend::password_message(b"my-secret-password", &mut write).unwrap();
     633            1 :             client.write_all(&write).await.unwrap();
     634            1 :         });
     635            1 :         let endpoint_rate_limiter = Arc::new(EndpointRateLimiter::new_with_shards(
     636              :             EndpointRateLimiter::DEFAULT,
     637              :             64,
     638              :         ));
     639              : 
     640            1 :         let _creds = auth_quirks(
     641            1 :             &ctx,
     642            1 :             &api,
     643            1 :             user_info,
     644            1 :             &mut stream,
     645            1 :             true,
     646            1 :             &CONFIG,
     647            1 :             endpoint_rate_limiter,
     648            1 :         )
     649            1 :         .await
     650            1 :         .unwrap();
     651              : 
     652            1 :         handle.await.unwrap();
     653            1 :     }
     654              : 
     655              :     #[tokio::test]
     656            1 :     async fn auth_quirks_password_hack() {
     657            1 :         let (mut client, server) = tokio::io::duplex(1024);
     658            1 :         let mut stream = PqStream::new_skip_handshake(Stream::from_raw(server));
     659              : 
     660            1 :         let ctx = RequestContext::test();
     661            1 :         let api = Auth {
     662            1 :             ips: vec![],
     663            1 :             vpc_endpoint_ids: vec![],
     664            1 :             access_blocker_flags: AccessBlockerFlags::default(),
     665            1 :             secret: AuthSecret::Scram(ServerSecret::build("my-secret-password").await.unwrap()),
     666              :         };
     667              : 
     668            1 :         let user_info = ComputeUserInfoMaybeEndpoint {
     669            1 :             user: "conrad".into(),
     670            1 :             endpoint_id: None,
     671            1 :             options: NeonOptions::default(),
     672            1 :         };
     673              : 
     674            1 :         let handle = tokio::spawn(async move {
     675            1 :             let mut read = BytesMut::new();
     676              : 
     677              :             // server should offer cleartext
     678            1 :             match read_message(&mut client, &mut read).await {
     679            1 :                 PgMessage::AuthenticationCleartextPassword => {}
     680            0 :                 _ => panic!("wrong message"),
     681              :             }
     682              : 
     683              :             // client responds with password
     684            1 :             let mut write = BytesMut::new();
     685            1 :             frontend::password_message(b"endpoint=my-endpoint;my-secret-password", &mut write)
     686            1 :                 .unwrap();
     687            1 :             client.write_all(&write).await.unwrap();
     688            1 :         });
     689              : 
     690            1 :         let endpoint_rate_limiter = Arc::new(EndpointRateLimiter::new_with_shards(
     691              :             EndpointRateLimiter::DEFAULT,
     692              :             64,
     693              :         ));
     694              : 
     695            1 :         let creds = auth_quirks(
     696            1 :             &ctx,
     697            1 :             &api,
     698            1 :             user_info,
     699            1 :             &mut stream,
     700            1 :             true,
     701            1 :             &CONFIG,
     702            1 :             endpoint_rate_limiter,
     703            1 :         )
     704            1 :         .await
     705            1 :         .unwrap();
     706              : 
     707            1 :         assert_eq!(creds.info.endpoint, "my-endpoint");
     708              : 
     709            1 :         handle.await.unwrap();
     710            1 :     }
     711              : }
        

Generated by: LCOV version 2.1-beta