LCOV - code coverage report
Current view: top level - proxy/src/auth - backend.rs (source / functions) Coverage Total Hit
Test: 691a4c28fe7169edd60b367c52d448a0a6605f1f.info Lines: 75.6 % 499 377
Test Date: 2024-05-10 13:18:37 Functions: 40.5 % 74 30

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

Generated by: LCOV version 2.1-beta