LCOV - code coverage report
Current view: top level - proxy/src/auth/backend - mod.rs (source / functions) Coverage Total Hit
Test: f2bfe5dc5ab550768e936d6bc7b94d9b2e2d4cc9.info Lines: 77.4 % 504 390
Test Date: 2025-01-27 20:39:28 Functions: 42.3 % 71 30

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

Generated by: LCOV version 2.1-beta